#!/usr/bin/env node
import { createRequire as __cjs_createRequire } from 'node:module'; const require = __cjs_createRequire(import.meta.url);
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod5) => function __require3() {
  return mod5 || (0, cb[__getOwnPropNames(cb)[0]])((mod5 = { exports: {} }).exports, mod5), mod5.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from14, except, desc) => {
  if (from14 && typeof from14 === "object" || typeof from14 === "function") {
    for (let key of __getOwnPropNames(from14))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from14[key], enumerable: !(desc = __getOwnPropDesc(from14, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod5, isNodeMode, target) => (target = mod5 != null ? __create(__getProtoOf(mod5)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod5 || !mod5.__esModule ? __defProp(target, "default", { value: mod5, enumerable: true }) : target,
  mod5
));

// node_modules/abitype/dist/esm/version.js
var version;
var init_version = __esm({
  "node_modules/abitype/dist/esm/version.js"() {
    "use strict";
    version = "1.2.3";
  }
});

// node_modules/abitype/dist/esm/errors.js
var BaseError;
var init_errors = __esm({
  "node_modules/abitype/dist/esm/errors.js"() {
    "use strict";
    init_version();
    BaseError = class _BaseError extends Error {
      constructor(shortMessage, args = {}) {
        const details = args.cause instanceof _BaseError ? args.cause.details : args.cause?.message ? args.cause.message : args.details;
        const docsPath8 = args.cause instanceof _BaseError ? args.cause.docsPath || args.docsPath : args.docsPath;
        const message = [
          shortMessage || "An error occurred.",
          "",
          ...args.metaMessages ? [...args.metaMessages, ""] : [],
          ...docsPath8 ? [`Docs: https://abitype.dev${docsPath8}`] : [],
          ...details ? [`Details: ${details}`] : [],
          `Version: abitype@${version}`
        ].join("\n");
        super(message);
        Object.defineProperty(this, "details", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "docsPath", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "metaMessages", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "shortMessage", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "AbiTypeError"
        });
        if (args.cause)
          this.cause = args.cause;
        this.details = details;
        this.docsPath = docsPath8;
        this.metaMessages = args.metaMessages;
        this.shortMessage = shortMessage;
      }
    };
  }
});

// node_modules/abitype/dist/esm/regex.js
function execTyped(regex, string) {
  const match = regex.exec(string);
  return match?.groups;
}
var bytesRegex, integerRegex, isTupleRegex;
var init_regex = __esm({
  "node_modules/abitype/dist/esm/regex.js"() {
    "use strict";
    bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;
    integerRegex = /^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;
    isTupleRegex = /^\(.+?\).*?$/;
  }
});

// node_modules/abitype/dist/esm/human-readable/formatAbiParameter.js
function formatAbiParameter(abiParameter) {
  let type = abiParameter.type;
  if (tupleRegex.test(abiParameter.type) && "components" in abiParameter) {
    type = "(";
    const length = abiParameter.components.length;
    for (let i = 0; i < length; i++) {
      const component = abiParameter.components[i];
      type += formatAbiParameter(component);
      if (i < length - 1)
        type += ", ";
    }
    const result = execTyped(tupleRegex, abiParameter.type);
    type += `)${result?.array || ""}`;
    return formatAbiParameter({
      ...abiParameter,
      type
    });
  }
  if ("indexed" in abiParameter && abiParameter.indexed)
    type = `${type} indexed`;
  if (abiParameter.name)
    return `${type} ${abiParameter.name}`;
  return type;
}
var tupleRegex;
var init_formatAbiParameter = __esm({
  "node_modules/abitype/dist/esm/human-readable/formatAbiParameter.js"() {
    "use strict";
    init_regex();
    tupleRegex = /^tuple(?<array>(\[(\d*)\])*)$/;
  }
});

// node_modules/abitype/dist/esm/human-readable/formatAbiParameters.js
function formatAbiParameters(abiParameters) {
  let params = "";
  const length = abiParameters.length;
  for (let i = 0; i < length; i++) {
    const abiParameter = abiParameters[i];
    params += formatAbiParameter(abiParameter);
    if (i !== length - 1)
      params += ", ";
  }
  return params;
}
var init_formatAbiParameters = __esm({
  "node_modules/abitype/dist/esm/human-readable/formatAbiParameters.js"() {
    "use strict";
    init_formatAbiParameter();
  }
});

// node_modules/abitype/dist/esm/human-readable/formatAbiItem.js
function formatAbiItem(abiItem) {
  if (abiItem.type === "function")
    return `function ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability && abiItem.stateMutability !== "nonpayable" ? ` ${abiItem.stateMutability}` : ""}${abiItem.outputs?.length ? ` returns (${formatAbiParameters(abiItem.outputs)})` : ""}`;
  if (abiItem.type === "event")
    return `event ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`;
  if (abiItem.type === "error")
    return `error ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`;
  if (abiItem.type === "constructor")
    return `constructor(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability === "payable" ? " payable" : ""}`;
  if (abiItem.type === "fallback")
    return `fallback() external${abiItem.stateMutability === "payable" ? " payable" : ""}`;
  return "receive() external payable";
}
var init_formatAbiItem = __esm({
  "node_modules/abitype/dist/esm/human-readable/formatAbiItem.js"() {
    "use strict";
    init_formatAbiParameters();
  }
});

// node_modules/abitype/dist/esm/human-readable/runtime/signatures.js
function isErrorSignature(signature2) {
  return errorSignatureRegex.test(signature2);
}
function execErrorSignature(signature2) {
  return execTyped(errorSignatureRegex, signature2);
}
function isEventSignature(signature2) {
  return eventSignatureRegex.test(signature2);
}
function execEventSignature(signature2) {
  return execTyped(eventSignatureRegex, signature2);
}
function isFunctionSignature(signature2) {
  return functionSignatureRegex.test(signature2);
}
function execFunctionSignature(signature2) {
  return execTyped(functionSignatureRegex, signature2);
}
function isStructSignature(signature2) {
  return structSignatureRegex.test(signature2);
}
function execStructSignature(signature2) {
  return execTyped(structSignatureRegex, signature2);
}
function isConstructorSignature(signature2) {
  return constructorSignatureRegex.test(signature2);
}
function execConstructorSignature(signature2) {
  return execTyped(constructorSignatureRegex, signature2);
}
function isFallbackSignature(signature2) {
  return fallbackSignatureRegex.test(signature2);
}
function execFallbackSignature(signature2) {
  return execTyped(fallbackSignatureRegex, signature2);
}
function isReceiveSignature(signature2) {
  return receiveSignatureRegex.test(signature2);
}
var errorSignatureRegex, eventSignatureRegex, functionSignatureRegex, structSignatureRegex, constructorSignatureRegex, fallbackSignatureRegex, receiveSignatureRegex, modifiers, eventModifiers, functionModifiers;
var init_signatures = __esm({
  "node_modules/abitype/dist/esm/human-readable/runtime/signatures.js"() {
    "use strict";
    init_regex();
    errorSignatureRegex = /^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;
    eventSignatureRegex = /^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;
    functionSignatureRegex = /^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;
    structSignatureRegex = /^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;
    constructorSignatureRegex = /^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;
    fallbackSignatureRegex = /^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;
    receiveSignatureRegex = /^receive\(\) external payable$/;
    modifiers = /* @__PURE__ */ new Set([
      "memory",
      "indexed",
      "storage",
      "calldata"
    ]);
    eventModifiers = /* @__PURE__ */ new Set(["indexed"]);
    functionModifiers = /* @__PURE__ */ new Set([
      "calldata",
      "memory",
      "storage"
    ]);
  }
});

// node_modules/abitype/dist/esm/human-readable/errors/abiItem.js
var InvalidAbiItemError, UnknownTypeError, UnknownSolidityTypeError;
var init_abiItem = __esm({
  "node_modules/abitype/dist/esm/human-readable/errors/abiItem.js"() {
    "use strict";
    init_errors();
    InvalidAbiItemError = class extends BaseError {
      constructor({ signature: signature2 }) {
        super("Failed to parse ABI item.", {
          details: `parseAbiItem(${JSON.stringify(signature2, null, 2)})`,
          docsPath: "/api/human#parseabiitem-1"
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "InvalidAbiItemError"
        });
      }
    };
    UnknownTypeError = class extends BaseError {
      constructor({ type }) {
        super("Unknown type.", {
          metaMessages: [
            `Type "${type}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`
          ]
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "UnknownTypeError"
        });
      }
    };
    UnknownSolidityTypeError = class extends BaseError {
      constructor({ type }) {
        super("Unknown type.", {
          metaMessages: [`Type "${type}" is not a valid ABI type.`]
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "UnknownSolidityTypeError"
        });
      }
    };
  }
});

// node_modules/abitype/dist/esm/human-readable/errors/abiParameter.js
var InvalidAbiParametersError, InvalidParameterError, SolidityProtectedKeywordError, InvalidModifierError, InvalidFunctionModifierError, InvalidAbiTypeParameterError;
var init_abiParameter = __esm({
  "node_modules/abitype/dist/esm/human-readable/errors/abiParameter.js"() {
    "use strict";
    init_errors();
    InvalidAbiParametersError = class extends BaseError {
      constructor({ params }) {
        super("Failed to parse ABI parameters.", {
          details: `parseAbiParameters(${JSON.stringify(params, null, 2)})`,
          docsPath: "/api/human#parseabiparameters-1"
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "InvalidAbiParametersError"
        });
      }
    };
    InvalidParameterError = class extends BaseError {
      constructor({ param }) {
        super("Invalid ABI parameter.", {
          details: param
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "InvalidParameterError"
        });
      }
    };
    SolidityProtectedKeywordError = class extends BaseError {
      constructor({ param, name }) {
        super("Invalid ABI parameter.", {
          details: param,
          metaMessages: [
            `"${name}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`
          ]
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "SolidityProtectedKeywordError"
        });
      }
    };
    InvalidModifierError = class extends BaseError {
      constructor({ param, type, modifier }) {
        super("Invalid ABI parameter.", {
          details: param,
          metaMessages: [
            `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ""}.`
          ]
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "InvalidModifierError"
        });
      }
    };
    InvalidFunctionModifierError = class extends BaseError {
      constructor({ param, type, modifier }) {
        super("Invalid ABI parameter.", {
          details: param,
          metaMessages: [
            `Modifier "${modifier}" not allowed${type ? ` in "${type}" type` : ""}.`,
            `Data location can only be specified for array, struct, or mapping types, but "${modifier}" was given.`
          ]
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "InvalidFunctionModifierError"
        });
      }
    };
    InvalidAbiTypeParameterError = class extends BaseError {
      constructor({ abiParameter }) {
        super("Invalid ABI parameter.", {
          details: JSON.stringify(abiParameter, null, 2),
          metaMessages: ["ABI parameter type is invalid."]
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "InvalidAbiTypeParameterError"
        });
      }
    };
  }
});

// node_modules/abitype/dist/esm/human-readable/errors/signature.js
var InvalidSignatureError, UnknownSignatureError, InvalidStructSignatureError;
var init_signature = __esm({
  "node_modules/abitype/dist/esm/human-readable/errors/signature.js"() {
    "use strict";
    init_errors();
    InvalidSignatureError = class extends BaseError {
      constructor({ signature: signature2, type }) {
        super(`Invalid ${type} signature.`, {
          details: signature2
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "InvalidSignatureError"
        });
      }
    };
    UnknownSignatureError = class extends BaseError {
      constructor({ signature: signature2 }) {
        super("Unknown signature.", {
          details: signature2
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "UnknownSignatureError"
        });
      }
    };
    InvalidStructSignatureError = class extends BaseError {
      constructor({ signature: signature2 }) {
        super("Invalid struct signature.", {
          details: signature2,
          metaMessages: ["No properties exist."]
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "InvalidStructSignatureError"
        });
      }
    };
  }
});

// node_modules/abitype/dist/esm/human-readable/errors/struct.js
var CircularReferenceError;
var init_struct = __esm({
  "node_modules/abitype/dist/esm/human-readable/errors/struct.js"() {
    "use strict";
    init_errors();
    CircularReferenceError = class extends BaseError {
      constructor({ type }) {
        super("Circular reference detected.", {
          metaMessages: [`Struct "${type}" is a circular reference.`]
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "CircularReferenceError"
        });
      }
    };
  }
});

// node_modules/abitype/dist/esm/human-readable/errors/splitParameters.js
var InvalidParenthesisError;
var init_splitParameters = __esm({
  "node_modules/abitype/dist/esm/human-readable/errors/splitParameters.js"() {
    "use strict";
    init_errors();
    InvalidParenthesisError = class extends BaseError {
      constructor({ current, depth }) {
        super("Unbalanced parentheses.", {
          metaMessages: [
            `"${current.trim()}" has too many ${depth > 0 ? "opening" : "closing"} parentheses.`
          ],
          details: `Depth "${depth}"`
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "InvalidParenthesisError"
        });
      }
    };
  }
});

// node_modules/abitype/dist/esm/human-readable/runtime/cache.js
function getParameterCacheKey(param, type, structs) {
  let structKey = "";
  if (structs)
    for (const struct of Object.entries(structs)) {
      if (!struct)
        continue;
      let propertyKey = "";
      for (const property of struct[1]) {
        propertyKey += `[${property.type}${property.name ? `:${property.name}` : ""}]`;
      }
      structKey += `(${struct[0]}{${propertyKey}})`;
    }
  if (type)
    return `${type}:${param}${structKey}`;
  return `${param}${structKey}`;
}
var parameterCache;
var init_cache = __esm({
  "node_modules/abitype/dist/esm/human-readable/runtime/cache.js"() {
    "use strict";
    parameterCache = /* @__PURE__ */ new Map([
      // Unnamed
      ["address", { type: "address" }],
      ["bool", { type: "bool" }],
      ["bytes", { type: "bytes" }],
      ["bytes32", { type: "bytes32" }],
      ["int", { type: "int256" }],
      ["int256", { type: "int256" }],
      ["string", { type: "string" }],
      ["uint", { type: "uint256" }],
      ["uint8", { type: "uint8" }],
      ["uint16", { type: "uint16" }],
      ["uint24", { type: "uint24" }],
      ["uint32", { type: "uint32" }],
      ["uint64", { type: "uint64" }],
      ["uint96", { type: "uint96" }],
      ["uint112", { type: "uint112" }],
      ["uint160", { type: "uint160" }],
      ["uint192", { type: "uint192" }],
      ["uint256", { type: "uint256" }],
      // Named
      ["address owner", { type: "address", name: "owner" }],
      ["address to", { type: "address", name: "to" }],
      ["bool approved", { type: "bool", name: "approved" }],
      ["bytes _data", { type: "bytes", name: "_data" }],
      ["bytes data", { type: "bytes", name: "data" }],
      ["bytes signature", { type: "bytes", name: "signature" }],
      ["bytes32 hash", { type: "bytes32", name: "hash" }],
      ["bytes32 r", { type: "bytes32", name: "r" }],
      ["bytes32 root", { type: "bytes32", name: "root" }],
      ["bytes32 s", { type: "bytes32", name: "s" }],
      ["string name", { type: "string", name: "name" }],
      ["string symbol", { type: "string", name: "symbol" }],
      ["string tokenURI", { type: "string", name: "tokenURI" }],
      ["uint tokenId", { type: "uint256", name: "tokenId" }],
      ["uint8 v", { type: "uint8", name: "v" }],
      ["uint256 balance", { type: "uint256", name: "balance" }],
      ["uint256 tokenId", { type: "uint256", name: "tokenId" }],
      ["uint256 value", { type: "uint256", name: "value" }],
      // Indexed
      [
        "event:address indexed from",
        { type: "address", name: "from", indexed: true }
      ],
      ["event:address indexed to", { type: "address", name: "to", indexed: true }],
      [
        "event:uint indexed tokenId",
        { type: "uint256", name: "tokenId", indexed: true }
      ],
      [
        "event:uint256 indexed tokenId",
        { type: "uint256", name: "tokenId", indexed: true }
      ]
    ]);
  }
});

// node_modules/abitype/dist/esm/human-readable/runtime/utils.js
function parseSignature(signature2, structs = {}) {
  if (isFunctionSignature(signature2))
    return parseFunctionSignature(signature2, structs);
  if (isEventSignature(signature2))
    return parseEventSignature(signature2, structs);
  if (isErrorSignature(signature2))
    return parseErrorSignature(signature2, structs);
  if (isConstructorSignature(signature2))
    return parseConstructorSignature(signature2, structs);
  if (isFallbackSignature(signature2))
    return parseFallbackSignature(signature2);
  if (isReceiveSignature(signature2))
    return {
      type: "receive",
      stateMutability: "payable"
    };
  throw new UnknownSignatureError({ signature: signature2 });
}
function parseFunctionSignature(signature2, structs = {}) {
  const match = execFunctionSignature(signature2);
  if (!match)
    throw new InvalidSignatureError({ signature: signature2, type: "function" });
  const inputParams = splitParameters(match.parameters);
  const inputs = [];
  const inputLength = inputParams.length;
  for (let i = 0; i < inputLength; i++) {
    inputs.push(parseAbiParameter(inputParams[i], {
      modifiers: functionModifiers,
      structs,
      type: "function"
    }));
  }
  const outputs = [];
  if (match.returns) {
    const outputParams = splitParameters(match.returns);
    const outputLength = outputParams.length;
    for (let i = 0; i < outputLength; i++) {
      outputs.push(parseAbiParameter(outputParams[i], {
        modifiers: functionModifiers,
        structs,
        type: "function"
      }));
    }
  }
  return {
    name: match.name,
    type: "function",
    stateMutability: match.stateMutability ?? "nonpayable",
    inputs,
    outputs
  };
}
function parseEventSignature(signature2, structs = {}) {
  const match = execEventSignature(signature2);
  if (!match)
    throw new InvalidSignatureError({ signature: signature2, type: "event" });
  const params = splitParameters(match.parameters);
  const abiParameters = [];
  const length = params.length;
  for (let i = 0; i < length; i++)
    abiParameters.push(parseAbiParameter(params[i], {
      modifiers: eventModifiers,
      structs,
      type: "event"
    }));
  return { name: match.name, type: "event", inputs: abiParameters };
}
function parseErrorSignature(signature2, structs = {}) {
  const match = execErrorSignature(signature2);
  if (!match)
    throw new InvalidSignatureError({ signature: signature2, type: "error" });
  const params = splitParameters(match.parameters);
  const abiParameters = [];
  const length = params.length;
  for (let i = 0; i < length; i++)
    abiParameters.push(parseAbiParameter(params[i], { structs, type: "error" }));
  return { name: match.name, type: "error", inputs: abiParameters };
}
function parseConstructorSignature(signature2, structs = {}) {
  const match = execConstructorSignature(signature2);
  if (!match)
    throw new InvalidSignatureError({ signature: signature2, type: "constructor" });
  const params = splitParameters(match.parameters);
  const abiParameters = [];
  const length = params.length;
  for (let i = 0; i < length; i++)
    abiParameters.push(parseAbiParameter(params[i], { structs, type: "constructor" }));
  return {
    type: "constructor",
    stateMutability: match.stateMutability ?? "nonpayable",
    inputs: abiParameters
  };
}
function parseFallbackSignature(signature2) {
  const match = execFallbackSignature(signature2);
  if (!match)
    throw new InvalidSignatureError({ signature: signature2, type: "fallback" });
  return {
    type: "fallback",
    stateMutability: match.stateMutability ?? "nonpayable"
  };
}
function parseAbiParameter(param, options) {
  const parameterCacheKey = getParameterCacheKey(param, options?.type, options?.structs);
  if (parameterCache.has(parameterCacheKey))
    return parameterCache.get(parameterCacheKey);
  const isTuple = isTupleRegex.test(param);
  const match = execTyped(isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex, param);
  if (!match)
    throw new InvalidParameterError({ param });
  if (match.name && isSolidityKeyword(match.name))
    throw new SolidityProtectedKeywordError({ param, name: match.name });
  const name = match.name ? { name: match.name } : {};
  const indexed = match.modifier === "indexed" ? { indexed: true } : {};
  const structs = options?.structs ?? {};
  let type;
  let components = {};
  if (isTuple) {
    type = "tuple";
    const params = splitParameters(match.type);
    const components_ = [];
    const length = params.length;
    for (let i = 0; i < length; i++) {
      components_.push(parseAbiParameter(params[i], { structs }));
    }
    components = { components: components_ };
  } else if (match.type in structs) {
    type = "tuple";
    components = { components: structs[match.type] };
  } else if (dynamicIntegerRegex.test(match.type)) {
    type = `${match.type}256`;
  } else if (match.type === "address payable") {
    type = "address";
  } else {
    type = match.type;
    if (!(options?.type === "struct") && !isSolidityType(type))
      throw new UnknownSolidityTypeError({ type });
  }
  if (match.modifier) {
    if (!options?.modifiers?.has?.(match.modifier))
      throw new InvalidModifierError({
        param,
        type: options?.type,
        modifier: match.modifier
      });
    if (functionModifiers.has(match.modifier) && !isValidDataLocation(type, !!match.array))
      throw new InvalidFunctionModifierError({
        param,
        type: options?.type,
        modifier: match.modifier
      });
  }
  const abiParameter = {
    type: `${type}${match.array ?? ""}`,
    ...name,
    ...indexed,
    ...components
  };
  parameterCache.set(parameterCacheKey, abiParameter);
  return abiParameter;
}
function splitParameters(params, result = [], current = "", depth = 0) {
  const length = params.trim().length;
  for (let i = 0; i < length; i++) {
    const char = params[i];
    const tail = params.slice(i + 1);
    switch (char) {
      case ",":
        return depth === 0 ? splitParameters(tail, [...result, current.trim()]) : splitParameters(tail, result, `${current}${char}`, depth);
      case "(":
        return splitParameters(tail, result, `${current}${char}`, depth + 1);
      case ")":
        return splitParameters(tail, result, `${current}${char}`, depth - 1);
      default:
        return splitParameters(tail, result, `${current}${char}`, depth);
    }
  }
  if (current === "")
    return result;
  if (depth !== 0)
    throw new InvalidParenthesisError({ current, depth });
  result.push(current.trim());
  return result;
}
function isSolidityType(type) {
  return type === "address" || type === "bool" || type === "function" || type === "string" || bytesRegex.test(type) || integerRegex.test(type);
}
function isSolidityKeyword(name) {
  return name === "address" || name === "bool" || name === "function" || name === "string" || name === "tuple" || bytesRegex.test(name) || integerRegex.test(name) || protectedKeywordsRegex.test(name);
}
function isValidDataLocation(type, isArray) {
  return isArray || type === "bytes" || type === "string" || type === "tuple";
}
var abiParameterWithoutTupleRegex, abiParameterWithTupleRegex, dynamicIntegerRegex, protectedKeywordsRegex;
var init_utils = __esm({
  "node_modules/abitype/dist/esm/human-readable/runtime/utils.js"() {
    "use strict";
    init_regex();
    init_abiItem();
    init_abiParameter();
    init_signature();
    init_splitParameters();
    init_cache();
    init_signatures();
    abiParameterWithoutTupleRegex = /^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/;
    abiParameterWithTupleRegex = /^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/;
    dynamicIntegerRegex = /^u?int$/;
    protectedKeywordsRegex = /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;
  }
});

// node_modules/abitype/dist/esm/human-readable/runtime/structs.js
function parseStructs(signatures) {
  const shallowStructs = {};
  const signaturesLength = signatures.length;
  for (let i = 0; i < signaturesLength; i++) {
    const signature2 = signatures[i];
    if (!isStructSignature(signature2))
      continue;
    const match = execStructSignature(signature2);
    if (!match)
      throw new InvalidSignatureError({ signature: signature2, type: "struct" });
    const properties = match.properties.split(";");
    const components = [];
    const propertiesLength = properties.length;
    for (let k = 0; k < propertiesLength; k++) {
      const property = properties[k];
      const trimmed = property.trim();
      if (!trimmed)
        continue;
      const abiParameter = parseAbiParameter(trimmed, {
        type: "struct"
      });
      components.push(abiParameter);
    }
    if (!components.length)
      throw new InvalidStructSignatureError({ signature: signature2 });
    shallowStructs[match.name] = components;
  }
  const resolvedStructs = {};
  const entries = Object.entries(shallowStructs);
  const entriesLength = entries.length;
  for (let i = 0; i < entriesLength; i++) {
    const [name, parameters] = entries[i];
    resolvedStructs[name] = resolveStructs(parameters, shallowStructs);
  }
  return resolvedStructs;
}
function resolveStructs(abiParameters = [], structs = {}, ancestors = /* @__PURE__ */ new Set()) {
  const components = [];
  const length = abiParameters.length;
  for (let i = 0; i < length; i++) {
    const abiParameter = abiParameters[i];
    const isTuple = isTupleRegex.test(abiParameter.type);
    if (isTuple)
      components.push(abiParameter);
    else {
      const match = execTyped(typeWithoutTupleRegex, abiParameter.type);
      if (!match?.type)
        throw new InvalidAbiTypeParameterError({ abiParameter });
      const { array, type } = match;
      if (type in structs) {
        if (ancestors.has(type))
          throw new CircularReferenceError({ type });
        components.push({
          ...abiParameter,
          type: `tuple${array ?? ""}`,
          components: resolveStructs(structs[type], structs, /* @__PURE__ */ new Set([...ancestors, type]))
        });
      } else {
        if (isSolidityType(type))
          components.push(abiParameter);
        else
          throw new UnknownTypeError({ type });
      }
    }
  }
  return components;
}
var typeWithoutTupleRegex;
var init_structs = __esm({
  "node_modules/abitype/dist/esm/human-readable/runtime/structs.js"() {
    "use strict";
    init_regex();
    init_abiItem();
    init_abiParameter();
    init_signature();
    init_struct();
    init_signatures();
    init_utils();
    typeWithoutTupleRegex = /^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;
  }
});

// node_modules/abitype/dist/esm/human-readable/parseAbi.js
function parseAbi(signatures) {
  const structs = parseStructs(signatures);
  const abi2 = [];
  const length = signatures.length;
  for (let i = 0; i < length; i++) {
    const signature2 = signatures[i];
    if (isStructSignature(signature2))
      continue;
    abi2.push(parseSignature(signature2, structs));
  }
  return abi2;
}
var init_parseAbi = __esm({
  "node_modules/abitype/dist/esm/human-readable/parseAbi.js"() {
    "use strict";
    init_signatures();
    init_structs();
    init_utils();
  }
});

// node_modules/abitype/dist/esm/human-readable/parseAbiItem.js
function parseAbiItem(signature2) {
  let abiItem;
  if (typeof signature2 === "string")
    abiItem = parseSignature(signature2);
  else {
    const structs = parseStructs(signature2);
    const length = signature2.length;
    for (let i = 0; i < length; i++) {
      const signature_ = signature2[i];
      if (isStructSignature(signature_))
        continue;
      abiItem = parseSignature(signature_, structs);
      break;
    }
  }
  if (!abiItem)
    throw new InvalidAbiItemError({ signature: signature2 });
  return abiItem;
}
var init_parseAbiItem = __esm({
  "node_modules/abitype/dist/esm/human-readable/parseAbiItem.js"() {
    "use strict";
    init_abiItem();
    init_signatures();
    init_structs();
    init_utils();
  }
});

// node_modules/abitype/dist/esm/human-readable/parseAbiParameters.js
function parseAbiParameters(params) {
  const abiParameters = [];
  if (typeof params === "string") {
    const parameters = splitParameters(params);
    const length = parameters.length;
    for (let i = 0; i < length; i++) {
      abiParameters.push(parseAbiParameter(parameters[i], { modifiers }));
    }
  } else {
    const structs = parseStructs(params);
    const length = params.length;
    for (let i = 0; i < length; i++) {
      const signature2 = params[i];
      if (isStructSignature(signature2))
        continue;
      const parameters = splitParameters(signature2);
      const length2 = parameters.length;
      for (let k = 0; k < length2; k++) {
        abiParameters.push(parseAbiParameter(parameters[k], { modifiers, structs }));
      }
    }
  }
  if (abiParameters.length === 0)
    throw new InvalidAbiParametersError({ params });
  return abiParameters;
}
var init_parseAbiParameters = __esm({
  "node_modules/abitype/dist/esm/human-readable/parseAbiParameters.js"() {
    "use strict";
    init_abiParameter();
    init_signatures();
    init_structs();
    init_utils();
    init_utils();
  }
});

// node_modules/abitype/dist/esm/exports/index.js
var init_exports = __esm({
  "node_modules/abitype/dist/esm/exports/index.js"() {
    "use strict";
    init_formatAbiItem();
    init_formatAbiParameters();
    init_parseAbi();
    init_parseAbiItem();
    init_parseAbiParameters();
  }
});

// node_modules/viem/_esm/utils/getAction.js
function getAction(client, actionFn, name) {
  const action_implicit = client[actionFn.name];
  if (typeof action_implicit === "function")
    return action_implicit;
  const action_explicit = client[name];
  if (typeof action_explicit === "function")
    return action_explicit;
  return (params) => actionFn(client, params);
}
var init_getAction = __esm({
  "node_modules/viem/_esm/utils/getAction.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/utils/abi/formatAbiItem.js
function formatAbiItem2(abiItem, { includeName = false } = {}) {
  if (abiItem.type !== "function" && abiItem.type !== "event" && abiItem.type !== "error")
    throw new InvalidDefinitionTypeError(abiItem.type);
  return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`;
}
function formatAbiParams(params, { includeName = false } = {}) {
  if (!params)
    return "";
  return params.map((param) => formatAbiParam(param, { includeName })).join(includeName ? ", " : ",");
}
function formatAbiParam(param, { includeName }) {
  if (param.type.startsWith("tuple")) {
    return `(${formatAbiParams(param.components, { includeName })})${param.type.slice("tuple".length)}`;
  }
  return param.type + (includeName && param.name ? ` ${param.name}` : "");
}
var init_formatAbiItem2 = __esm({
  "node_modules/viem/_esm/utils/abi/formatAbiItem.js"() {
    "use strict";
    init_abi();
  }
});

// node_modules/viem/_esm/utils/data/isHex.js
function isHex(value, { strict = true } = {}) {
  if (!value)
    return false;
  if (typeof value !== "string")
    return false;
  return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith("0x");
}
var init_isHex = __esm({
  "node_modules/viem/_esm/utils/data/isHex.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/utils/data/size.js
function size(value) {
  if (isHex(value, { strict: false }))
    return Math.ceil((value.length - 2) / 2);
  return value.length;
}
var init_size = __esm({
  "node_modules/viem/_esm/utils/data/size.js"() {
    "use strict";
    init_isHex();
  }
});

// node_modules/viem/_esm/errors/version.js
var version2;
var init_version2 = __esm({
  "node_modules/viem/_esm/errors/version.js"() {
    "use strict";
    version2 = "2.48.11";
  }
});

// node_modules/viem/_esm/errors/base.js
function walk(err, fn) {
  if (fn?.(err))
    return err;
  if (err && typeof err === "object" && "cause" in err && err.cause !== void 0)
    return walk(err.cause, fn);
  return fn ? null : err;
}
var errorConfig, BaseError2;
var init_base = __esm({
  "node_modules/viem/_esm/errors/base.js"() {
    "use strict";
    init_version2();
    errorConfig = {
      getDocsUrl: ({ docsBaseUrl, docsPath: docsPath8 = "", docsSlug }) => docsPath8 ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath8}${docsSlug ? `#${docsSlug}` : ""}` : void 0,
      version: `viem@${version2}`
    };
    BaseError2 = class _BaseError extends Error {
      constructor(shortMessage, args = {}) {
        const details = (() => {
          if (args.cause instanceof _BaseError)
            return args.cause.details;
          if (args.cause?.message)
            return args.cause.message;
          return args.details;
        })();
        const docsPath8 = (() => {
          if (args.cause instanceof _BaseError)
            return args.cause.docsPath || args.docsPath;
          return args.docsPath;
        })();
        const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath: docsPath8 });
        const message = [
          shortMessage || "An error occurred.",
          "",
          ...args.metaMessages ? [...args.metaMessages, ""] : [],
          ...docsUrl ? [`Docs: ${docsUrl}`] : [],
          ...details ? [`Details: ${details}`] : [],
          ...errorConfig.version ? [`Version: ${errorConfig.version}`] : []
        ].join("\n");
        super(message, args.cause ? { cause: args.cause } : void 0);
        Object.defineProperty(this, "details", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "docsPath", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "metaMessages", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "shortMessage", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "version", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "BaseError"
        });
        this.details = details;
        this.docsPath = docsPath8;
        this.metaMessages = args.metaMessages;
        this.name = args.name ?? this.name;
        this.shortMessage = shortMessage;
        this.version = version2;
      }
      walk(fn) {
        return walk(this, fn);
      }
    };
  }
});

// node_modules/viem/_esm/errors/abi.js
var AbiConstructorNotFoundError, AbiConstructorParamsNotFoundError, AbiDecodingDataSizeTooSmallError, AbiDecodingZeroDataError, AbiEncodingArrayLengthMismatchError, AbiEncodingBytesSizeMismatchError, AbiEncodingLengthMismatchError, AbiErrorInputsNotFoundError, AbiErrorNotFoundError, AbiErrorSignatureNotFoundError, AbiEventSignatureEmptyTopicsError, AbiEventSignatureNotFoundError, AbiEventNotFoundError, AbiFunctionNotFoundError, AbiFunctionOutputsNotFoundError, AbiFunctionSignatureNotFoundError, AbiItemAmbiguityError, BytesSizeMismatchError, DecodeLogDataMismatch, DecodeLogTopicsMismatch, InvalidAbiEncodingTypeError, InvalidAbiDecodingTypeError, InvalidArrayError, InvalidDefinitionTypeError;
var init_abi = __esm({
  "node_modules/viem/_esm/errors/abi.js"() {
    "use strict";
    init_formatAbiItem2();
    init_size();
    init_base();
    AbiConstructorNotFoundError = class extends BaseError2 {
      constructor({ docsPath: docsPath8 }) {
        super([
          "A constructor was not found on the ABI.",
          "Make sure you are using the correct ABI and that the constructor exists on it."
        ].join("\n"), {
          docsPath: docsPath8,
          name: "AbiConstructorNotFoundError"
        });
      }
    };
    AbiConstructorParamsNotFoundError = class extends BaseError2 {
      constructor({ docsPath: docsPath8 }) {
        super([
          "Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.",
          "Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."
        ].join("\n"), {
          docsPath: docsPath8,
          name: "AbiConstructorParamsNotFoundError"
        });
      }
    };
    AbiDecodingDataSizeTooSmallError = class extends BaseError2 {
      constructor({ data, params, size: size5 }) {
        super([`Data size of ${size5} bytes is too small for given parameters.`].join("\n"), {
          metaMessages: [
            `Params: (${formatAbiParams(params, { includeName: true })})`,
            `Data:   ${data} (${size5} bytes)`
          ],
          name: "AbiDecodingDataSizeTooSmallError"
        });
        Object.defineProperty(this, "data", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "params", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "size", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.data = data;
        this.params = params;
        this.size = size5;
      }
    };
    AbiDecodingZeroDataError = class extends BaseError2 {
      constructor({ cause } = {}) {
        super('Cannot decode zero data ("0x") with ABI parameters.', {
          name: "AbiDecodingZeroDataError",
          cause
        });
      }
    };
    AbiEncodingArrayLengthMismatchError = class extends BaseError2 {
      constructor({ expectedLength, givenLength, type }) {
        super([
          `ABI encoding array length mismatch for type ${type}.`,
          `Expected length: ${expectedLength}`,
          `Given length: ${givenLength}`
        ].join("\n"), { name: "AbiEncodingArrayLengthMismatchError" });
      }
    };
    AbiEncodingBytesSizeMismatchError = class extends BaseError2 {
      constructor({ expectedSize, value }) {
        super(`Size of bytes "${value}" (bytes${size(value)}) does not match expected size (bytes${expectedSize}).`, { name: "AbiEncodingBytesSizeMismatchError" });
      }
    };
    AbiEncodingLengthMismatchError = class extends BaseError2 {
      constructor({ expectedLength, givenLength }) {
        super([
          "ABI encoding params/values length mismatch.",
          `Expected length (params): ${expectedLength}`,
          `Given length (values): ${givenLength}`
        ].join("\n"), { name: "AbiEncodingLengthMismatchError" });
      }
    };
    AbiErrorInputsNotFoundError = class extends BaseError2 {
      constructor(errorName, { docsPath: docsPath8 }) {
        super([
          `Arguments (\`args\`) were provided to "${errorName}", but "${errorName}" on the ABI does not contain any parameters (\`inputs\`).`,
          "Cannot encode error result without knowing what the parameter types are.",
          "Make sure you are using the correct ABI and that the inputs exist on it."
        ].join("\n"), {
          docsPath: docsPath8,
          name: "AbiErrorInputsNotFoundError"
        });
      }
    };
    AbiErrorNotFoundError = class extends BaseError2 {
      constructor(errorName, { docsPath: docsPath8 } = {}) {
        super([
          `Error ${errorName ? `"${errorName}" ` : ""}not found on ABI.`,
          "Make sure you are using the correct ABI and that the error exists on it."
        ].join("\n"), {
          docsPath: docsPath8,
          name: "AbiErrorNotFoundError"
        });
      }
    };
    AbiErrorSignatureNotFoundError = class extends BaseError2 {
      constructor(signature2, { docsPath: docsPath8, cause }) {
        super([
          `Encoded error signature "${signature2}" not found on ABI.`,
          "Make sure you are using the correct ABI and that the error exists on it.",
          `You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${signature2}.`
        ].join("\n"), {
          docsPath: docsPath8,
          name: "AbiErrorSignatureNotFoundError",
          cause
        });
        Object.defineProperty(this, "signature", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.signature = signature2;
      }
    };
    AbiEventSignatureEmptyTopicsError = class extends BaseError2 {
      constructor({ docsPath: docsPath8 }) {
        super("Cannot extract event signature from empty topics.", {
          docsPath: docsPath8,
          name: "AbiEventSignatureEmptyTopicsError"
        });
      }
    };
    AbiEventSignatureNotFoundError = class extends BaseError2 {
      constructor(signature2, { docsPath: docsPath8 }) {
        super([
          `Encoded event signature "${signature2}" not found on ABI.`,
          "Make sure you are using the correct ABI and that the event exists on it.",
          `You can look up the signature here: https://4byte.sourcify.dev/?q=${signature2}.`
        ].join("\n"), {
          docsPath: docsPath8,
          name: "AbiEventSignatureNotFoundError"
        });
      }
    };
    AbiEventNotFoundError = class extends BaseError2 {
      constructor(eventName, { docsPath: docsPath8 } = {}) {
        super([
          `Event ${eventName ? `"${eventName}" ` : ""}not found on ABI.`,
          "Make sure you are using the correct ABI and that the event exists on it."
        ].join("\n"), {
          docsPath: docsPath8,
          name: "AbiEventNotFoundError"
        });
      }
    };
    AbiFunctionNotFoundError = class extends BaseError2 {
      constructor(functionName, { docsPath: docsPath8 } = {}) {
        super([
          `Function ${functionName ? `"${functionName}" ` : ""}not found on ABI.`,
          "Make sure you are using the correct ABI and that the function exists on it."
        ].join("\n"), {
          docsPath: docsPath8,
          name: "AbiFunctionNotFoundError"
        });
      }
    };
    AbiFunctionOutputsNotFoundError = class extends BaseError2 {
      constructor(functionName, { docsPath: docsPath8 }) {
        super([
          `Function "${functionName}" does not contain any \`outputs\` on ABI.`,
          "Cannot decode function result without knowing what the parameter types are.",
          "Make sure you are using the correct ABI and that the function exists on it."
        ].join("\n"), {
          docsPath: docsPath8,
          name: "AbiFunctionOutputsNotFoundError"
        });
      }
    };
    AbiFunctionSignatureNotFoundError = class extends BaseError2 {
      constructor(signature2, { docsPath: docsPath8 }) {
        super([
          `Encoded function signature "${signature2}" not found on ABI.`,
          "Make sure you are using the correct ABI and that the function exists on it.",
          `You can look up the signature here: https://4byte.sourcify.dev/?q=${signature2}.`
        ].join("\n"), {
          docsPath: docsPath8,
          name: "AbiFunctionSignatureNotFoundError"
        });
      }
    };
    AbiItemAmbiguityError = class extends BaseError2 {
      constructor(x, y) {
        super("Found ambiguous types in overloaded ABI items.", {
          metaMessages: [
            `\`${x.type}\` in \`${formatAbiItem2(x.abiItem)}\`, and`,
            `\`${y.type}\` in \`${formatAbiItem2(y.abiItem)}\``,
            "",
            "These types encode differently and cannot be distinguished at runtime.",
            "Remove one of the ambiguous items in the ABI."
          ],
          name: "AbiItemAmbiguityError"
        });
      }
    };
    BytesSizeMismatchError = class extends BaseError2 {
      constructor({ expectedSize, givenSize }) {
        super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, {
          name: "BytesSizeMismatchError"
        });
      }
    };
    DecodeLogDataMismatch = class extends BaseError2 {
      constructor({ abiItem, data, params, size: size5 }) {
        super([
          `Data size of ${size5} bytes is too small for non-indexed event parameters.`
        ].join("\n"), {
          metaMessages: [
            `Params: (${formatAbiParams(params, { includeName: true })})`,
            `Data:   ${data} (${size5} bytes)`
          ],
          name: "DecodeLogDataMismatch"
        });
        Object.defineProperty(this, "abiItem", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "data", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "params", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "size", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.abiItem = abiItem;
        this.data = data;
        this.params = params;
        this.size = size5;
      }
    };
    DecodeLogTopicsMismatch = class extends BaseError2 {
      constructor({ abiItem, param }) {
        super([
          `Expected a topic for indexed event parameter${param.name ? ` "${param.name}"` : ""} on event "${formatAbiItem2(abiItem, { includeName: true })}".`
        ].join("\n"), { name: "DecodeLogTopicsMismatch" });
        Object.defineProperty(this, "abiItem", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.abiItem = abiItem;
      }
    };
    InvalidAbiEncodingTypeError = class extends BaseError2 {
      constructor(type, { docsPath: docsPath8 }) {
        super([
          `Type "${type}" is not a valid encoding type.`,
          "Please provide a valid ABI type."
        ].join("\n"), { docsPath: docsPath8, name: "InvalidAbiEncodingType" });
      }
    };
    InvalidAbiDecodingTypeError = class extends BaseError2 {
      constructor(type, { docsPath: docsPath8 }) {
        super([
          `Type "${type}" is not a valid decoding type.`,
          "Please provide a valid ABI type."
        ].join("\n"), { docsPath: docsPath8, name: "InvalidAbiDecodingType" });
      }
    };
    InvalidArrayError = class extends BaseError2 {
      constructor(value) {
        super([`Value "${value}" is not a valid array.`].join("\n"), {
          name: "InvalidArrayError"
        });
      }
    };
    InvalidDefinitionTypeError = class extends BaseError2 {
      constructor(type) {
        super([
          `"${type}" is not a valid definition type.`,
          'Valid types: "function", "event", "error"'
        ].join("\n"), { name: "InvalidDefinitionTypeError" });
      }
    };
  }
});

// node_modules/viem/_esm/errors/log.js
var FilterTypeNotSupportedError;
var init_log = __esm({
  "node_modules/viem/_esm/errors/log.js"() {
    "use strict";
    init_base();
    FilterTypeNotSupportedError = class extends BaseError2 {
      constructor(type) {
        super(`Filter type "${type}" is not supported.`, {
          name: "FilterTypeNotSupportedError"
        });
      }
    };
  }
});

// node_modules/viem/_esm/errors/data.js
var SliceOffsetOutOfBoundsError, SizeExceedsPaddingSizeError, InvalidBytesLengthError;
var init_data = __esm({
  "node_modules/viem/_esm/errors/data.js"() {
    "use strict";
    init_base();
    SliceOffsetOutOfBoundsError = class extends BaseError2 {
      constructor({ offset, position, size: size5 }) {
        super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset}" is out-of-bounds (size: ${size5}).`, { name: "SliceOffsetOutOfBoundsError" });
      }
    };
    SizeExceedsPaddingSizeError = class extends BaseError2 {
      constructor({ size: size5, targetSize, type }) {
        super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size5}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" });
      }
    };
    InvalidBytesLengthError = class extends BaseError2 {
      constructor({ size: size5, targetSize, type }) {
        super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size5} ${type} long.`, { name: "InvalidBytesLengthError" });
      }
    };
  }
});

// node_modules/viem/_esm/utils/data/pad.js
function pad(hexOrBytes, { dir, size: size5 = 32 } = {}) {
  if (typeof hexOrBytes === "string")
    return padHex(hexOrBytes, { dir, size: size5 });
  return padBytes(hexOrBytes, { dir, size: size5 });
}
function padHex(hex_, { dir, size: size5 = 32 } = {}) {
  if (size5 === null)
    return hex_;
  const hex = hex_.replace("0x", "");
  if (hex.length > size5 * 2)
    throw new SizeExceedsPaddingSizeError({
      size: Math.ceil(hex.length / 2),
      targetSize: size5,
      type: "hex"
    });
  return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size5 * 2, "0")}`;
}
function padBytes(bytes, { dir, size: size5 = 32 } = {}) {
  if (size5 === null)
    return bytes;
  if (bytes.length > size5)
    throw new SizeExceedsPaddingSizeError({
      size: bytes.length,
      targetSize: size5,
      type: "bytes"
    });
  const paddedBytes = new Uint8Array(size5);
  for (let i = 0; i < size5; i++) {
    const padEnd = dir === "right";
    paddedBytes[padEnd ? i : size5 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
  }
  return paddedBytes;
}
var init_pad = __esm({
  "node_modules/viem/_esm/utils/data/pad.js"() {
    "use strict";
    init_data();
  }
});

// node_modules/viem/_esm/errors/encoding.js
var IntegerOutOfRangeError, InvalidBytesBooleanError, InvalidHexBooleanError, SizeOverflowError;
var init_encoding = __esm({
  "node_modules/viem/_esm/errors/encoding.js"() {
    "use strict";
    init_base();
    IntegerOutOfRangeError = class extends BaseError2 {
      constructor({ max, min, signed, size: size5, value }) {
        super(`Number "${value}" is not in safe ${size5 ? `${size5 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: "IntegerOutOfRangeError" });
      }
    };
    InvalidBytesBooleanError = class extends BaseError2 {
      constructor(bytes) {
        super(`Bytes value "${bytes}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`, {
          name: "InvalidBytesBooleanError"
        });
      }
    };
    InvalidHexBooleanError = class extends BaseError2 {
      constructor(hex) {
        super(`Hex value "${hex}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`, { name: "InvalidHexBooleanError" });
      }
    };
    SizeOverflowError = class extends BaseError2 {
      constructor({ givenSize, maxSize }) {
        super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: "SizeOverflowError" });
      }
    };
  }
});

// node_modules/viem/_esm/utils/data/trim.js
function trim(hexOrBytes, { dir = "left" } = {}) {
  let data = typeof hexOrBytes === "string" ? hexOrBytes.replace("0x", "") : hexOrBytes;
  let sliceLength = 0;
  for (let i = 0; i < data.length - 1; i++) {
    if (data[dir === "left" ? i : data.length - i - 1].toString() === "0")
      sliceLength++;
    else
      break;
  }
  data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength);
  if (typeof hexOrBytes === "string") {
    if (data.length === 1 && dir === "right")
      data = `${data}0`;
    return `0x${data.length % 2 === 1 ? `0${data}` : data}`;
  }
  return data;
}
var init_trim = __esm({
  "node_modules/viem/_esm/utils/data/trim.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/utils/encoding/fromHex.js
function assertSize(hexOrBytes, { size: size5 }) {
  if (size(hexOrBytes) > size5)
    throw new SizeOverflowError({
      givenSize: size(hexOrBytes),
      maxSize: size5
    });
}
function hexToBigInt(hex, opts = {}) {
  const { signed } = opts;
  if (opts.size)
    assertSize(hex, { size: opts.size });
  const value = BigInt(hex);
  if (!signed)
    return value;
  const size5 = (hex.length - 2) / 2;
  const max = (1n << BigInt(size5) * 8n - 1n) - 1n;
  if (value <= max)
    return value;
  return value - BigInt(`0x${"f".padStart(size5 * 2, "f")}`) - 1n;
}
function hexToBool(hex_, opts = {}) {
  let hex = hex_;
  if (opts.size) {
    assertSize(hex, { size: opts.size });
    hex = trim(hex);
  }
  if (trim(hex) === "0x00")
    return false;
  if (trim(hex) === "0x01")
    return true;
  throw new InvalidHexBooleanError(hex);
}
function hexToNumber(hex, opts = {}) {
  const value = hexToBigInt(hex, opts);
  const number = Number(value);
  if (!Number.isSafeInteger(number))
    throw new IntegerOutOfRangeError({
      max: `${Number.MAX_SAFE_INTEGER}`,
      min: `${Number.MIN_SAFE_INTEGER}`,
      signed: opts.signed,
      size: opts.size,
      value: `${value}n`
    });
  return number;
}
var init_fromHex = __esm({
  "node_modules/viem/_esm/utils/encoding/fromHex.js"() {
    "use strict";
    init_encoding();
    init_size();
    init_trim();
  }
});

// node_modules/viem/_esm/utils/encoding/toHex.js
function toHex(value, opts = {}) {
  if (typeof value === "number" || typeof value === "bigint")
    return numberToHex(value, opts);
  if (typeof value === "string") {
    return stringToHex(value, opts);
  }
  if (typeof value === "boolean")
    return boolToHex(value, opts);
  return bytesToHex(value, opts);
}
function boolToHex(value, opts = {}) {
  const hex = `0x${Number(value)}`;
  if (typeof opts.size === "number") {
    assertSize(hex, { size: opts.size });
    return pad(hex, { size: opts.size });
  }
  return hex;
}
function bytesToHex(value, opts = {}) {
  let string = "";
  for (let i = 0; i < value.length; i++) {
    string += hexes[value[i]];
  }
  const hex = `0x${string}`;
  if (typeof opts.size === "number") {
    assertSize(hex, { size: opts.size });
    return pad(hex, { dir: "right", size: opts.size });
  }
  return hex;
}
function numberToHex(value_, opts = {}) {
  const { signed, size: size5 } = opts;
  const value = BigInt(value_);
  let maxValue;
  if (size5) {
    if (signed)
      maxValue = (1n << BigInt(size5) * 8n - 1n) - 1n;
    else
      maxValue = 2n ** (BigInt(size5) * 8n) - 1n;
  } else if (typeof value_ === "number") {
    maxValue = BigInt(Number.MAX_SAFE_INTEGER);
  }
  const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0;
  if (maxValue && value > maxValue || value < minValue) {
    const suffix = typeof value_ === "bigint" ? "n" : "";
    throw new IntegerOutOfRangeError({
      max: maxValue ? `${maxValue}${suffix}` : void 0,
      min: `${minValue}${suffix}`,
      signed,
      size: size5,
      value: `${value_}${suffix}`
    });
  }
  const hex = `0x${(signed && value < 0 ? (1n << BigInt(size5 * 8)) + BigInt(value) : value).toString(16)}`;
  if (size5)
    return pad(hex, { size: size5 });
  return hex;
}
function stringToHex(value_, opts = {}) {
  const value = encoder.encode(value_);
  return bytesToHex(value, opts);
}
var hexes, encoder;
var init_toHex = __esm({
  "node_modules/viem/_esm/utils/encoding/toHex.js"() {
    "use strict";
    init_encoding();
    init_pad();
    init_fromHex();
    hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0"));
    encoder = /* @__PURE__ */ new TextEncoder();
  }
});

// node_modules/viem/_esm/utils/encoding/toBytes.js
function toBytes(value, opts = {}) {
  if (typeof value === "number" || typeof value === "bigint")
    return numberToBytes(value, opts);
  if (typeof value === "boolean")
    return boolToBytes(value, opts);
  if (isHex(value))
    return hexToBytes(value, opts);
  return stringToBytes(value, opts);
}
function boolToBytes(value, opts = {}) {
  const bytes = new Uint8Array(1);
  bytes[0] = Number(value);
  if (typeof opts.size === "number") {
    assertSize(bytes, { size: opts.size });
    return pad(bytes, { size: opts.size });
  }
  return bytes;
}
function charCodeToBase16(char) {
  if (char >= charCodeMap.zero && char <= charCodeMap.nine)
    return char - charCodeMap.zero;
  if (char >= charCodeMap.A && char <= charCodeMap.F)
    return char - (charCodeMap.A - 10);
  if (char >= charCodeMap.a && char <= charCodeMap.f)
    return char - (charCodeMap.a - 10);
  return void 0;
}
function hexToBytes(hex_, opts = {}) {
  let hex = hex_;
  if (opts.size) {
    assertSize(hex, { size: opts.size });
    hex = pad(hex, { dir: "right", size: opts.size });
  }
  let hexString = hex.slice(2);
  if (hexString.length % 2)
    hexString = `0${hexString}`;
  const length = hexString.length / 2;
  const bytes = new Uint8Array(length);
  for (let index2 = 0, j = 0; index2 < length; index2++) {
    const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++));
    const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++));
    if (nibbleLeft === void 0 || nibbleRight === void 0) {
      throw new BaseError2(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`);
    }
    bytes[index2] = nibbleLeft * 16 + nibbleRight;
  }
  return bytes;
}
function numberToBytes(value, opts) {
  const hex = numberToHex(value, opts);
  return hexToBytes(hex);
}
function stringToBytes(value, opts = {}) {
  const bytes = encoder2.encode(value);
  if (typeof opts.size === "number") {
    assertSize(bytes, { size: opts.size });
    return pad(bytes, { dir: "right", size: opts.size });
  }
  return bytes;
}
var encoder2, charCodeMap;
var init_toBytes = __esm({
  "node_modules/viem/_esm/utils/encoding/toBytes.js"() {
    "use strict";
    init_base();
    init_isHex();
    init_pad();
    init_fromHex();
    init_toHex();
    encoder2 = /* @__PURE__ */ new TextEncoder();
    charCodeMap = {
      zero: 48,
      nine: 57,
      A: 65,
      F: 70,
      a: 97,
      f: 102
    };
  }
});

// node_modules/viem/node_modules/@noble/hashes/esm/_u64.js
function fromBig(n, le = false) {
  if (le)
    return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
  return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
  const len = lst.length;
  let Ah = new Uint32Array(len);
  let Al = new Uint32Array(len);
  for (let i = 0; i < len; i++) {
    const { h, l: l2 } = fromBig(lst[i], le);
    [Ah[i], Al[i]] = [h, l2];
  }
  return [Ah, Al];
}
var U32_MASK64, _32n, rotlSH, rotlSL, rotlBH, rotlBL;
var init_u64 = __esm({
  "node_modules/viem/node_modules/@noble/hashes/esm/_u64.js"() {
    "use strict";
    U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
    _32n = /* @__PURE__ */ BigInt(32);
    rotlSH = (h, l2, s3) => h << s3 | l2 >>> 32 - s3;
    rotlSL = (h, l2, s3) => l2 << s3 | h >>> 32 - s3;
    rotlBH = (h, l2, s3) => l2 << s3 - 32 | h >>> 64 - s3;
    rotlBL = (h, l2, s3) => h << s3 - 32 | l2 >>> 64 - s3;
  }
});

// node_modules/viem/node_modules/@noble/hashes/esm/cryptoNode.js
import * as nc from "crypto";
var crypto2;
var init_cryptoNode = __esm({
  "node_modules/viem/node_modules/@noble/hashes/esm/cryptoNode.js"() {
    "use strict";
    crypto2 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
  }
});

// node_modules/viem/node_modules/@noble/hashes/esm/utils.js
function isBytes(a) {
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
function anumber(n) {
  if (!Number.isSafeInteger(n) || n < 0)
    throw new Error("positive integer expected, got " + n);
}
function abytes(b, ...lengths) {
  if (!isBytes(b))
    throw new Error("Uint8Array expected");
  if (lengths.length > 0 && !lengths.includes(b.length))
    throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
}
function ahash(h) {
  if (typeof h !== "function" || typeof h.create !== "function")
    throw new Error("Hash should be wrapped by utils.createHasher");
  anumber(h.outputLen);
  anumber(h.blockLen);
}
function aexists(instance, checkFinished = true) {
  if (instance.destroyed)
    throw new Error("Hash instance has been destroyed");
  if (checkFinished && instance.finished)
    throw new Error("Hash#digest() has already been called");
}
function aoutput(out, instance) {
  abytes(out);
  const min = instance.outputLen;
  if (out.length < min) {
    throw new Error("digestInto() expects output buffer of length at least " + min);
  }
}
function u32(arr) {
  return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
function clean(...arrays) {
  for (let i = 0; i < arrays.length; i++) {
    arrays[i].fill(0);
  }
}
function createView(arr) {
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
function rotr(word, shift) {
  return word << 32 - shift | word >>> shift;
}
function byteSwap(word) {
  return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
}
function byteSwap32(arr) {
  for (let i = 0; i < arr.length; i++) {
    arr[i] = byteSwap(arr[i]);
  }
  return arr;
}
function utf8ToBytes(str) {
  if (typeof str !== "string")
    throw new Error("string expected");
  return new Uint8Array(new TextEncoder().encode(str));
}
function toBytes2(data) {
  if (typeof data === "string")
    data = utf8ToBytes(data);
  abytes(data);
  return data;
}
function concatBytes(...arrays) {
  let sum = 0;
  for (let i = 0; i < arrays.length; i++) {
    const a = arrays[i];
    abytes(a);
    sum += a.length;
  }
  const res = new Uint8Array(sum);
  for (let i = 0, pad4 = 0; i < arrays.length; i++) {
    const a = arrays[i];
    res.set(a, pad4);
    pad4 += a.length;
  }
  return res;
}
function createHasher(hashCons) {
  const hashC = (msg) => hashCons().update(toBytes2(msg)).digest();
  const tmp = hashCons();
  hashC.outputLen = tmp.outputLen;
  hashC.blockLen = tmp.blockLen;
  hashC.create = () => hashCons();
  return hashC;
}
function randomBytes(bytesLength = 32) {
  if (crypto2 && typeof crypto2.getRandomValues === "function") {
    return crypto2.getRandomValues(new Uint8Array(bytesLength));
  }
  if (crypto2 && typeof crypto2.randomBytes === "function") {
    return Uint8Array.from(crypto2.randomBytes(bytesLength));
  }
  throw new Error("crypto.getRandomValues must be defined");
}
var isLE, swap32IfBE, Hash;
var init_utils2 = __esm({
  "node_modules/viem/node_modules/@noble/hashes/esm/utils.js"() {
    "use strict";
    init_cryptoNode();
    isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
    swap32IfBE = isLE ? (u) => u : byteSwap32;
    Hash = class {
    };
  }
});

// node_modules/viem/node_modules/@noble/hashes/esm/sha3.js
function keccakP(s3, rounds = 24) {
  const B = new Uint32Array(5 * 2);
  for (let round = 24 - rounds; round < 24; round++) {
    for (let x = 0; x < 10; x++)
      B[x] = s3[x] ^ s3[x + 10] ^ s3[x + 20] ^ s3[x + 30] ^ s3[x + 40];
    for (let x = 0; x < 10; x += 2) {
      const idx1 = (x + 8) % 10;
      const idx0 = (x + 2) % 10;
      const B0 = B[idx0];
      const B1 = B[idx0 + 1];
      const Th = rotlH(B0, B1, 1) ^ B[idx1];
      const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
      for (let y = 0; y < 50; y += 10) {
        s3[x + y] ^= Th;
        s3[x + y + 1] ^= Tl;
      }
    }
    let curH = s3[2];
    let curL = s3[3];
    for (let t = 0; t < 24; t++) {
      const shift = SHA3_ROTL[t];
      const Th = rotlH(curH, curL, shift);
      const Tl = rotlL(curH, curL, shift);
      const PI = SHA3_PI[t];
      curH = s3[PI];
      curL = s3[PI + 1];
      s3[PI] = Th;
      s3[PI + 1] = Tl;
    }
    for (let y = 0; y < 50; y += 10) {
      for (let x = 0; x < 10; x++)
        B[x] = s3[y + x];
      for (let x = 0; x < 10; x++)
        s3[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
    }
    s3[0] ^= SHA3_IOTA_H[round];
    s3[1] ^= SHA3_IOTA_L[round];
  }
  clean(B);
}
var _0n, _1n, _2n, _7n, _256n, _0x71n, SHA3_PI, SHA3_ROTL, _SHA3_IOTA, IOTAS, SHA3_IOTA_H, SHA3_IOTA_L, rotlH, rotlL, Keccak, gen, keccak_256;
var init_sha3 = __esm({
  "node_modules/viem/node_modules/@noble/hashes/esm/sha3.js"() {
    "use strict";
    init_u64();
    init_utils2();
    _0n = BigInt(0);
    _1n = BigInt(1);
    _2n = BigInt(2);
    _7n = BigInt(7);
    _256n = BigInt(256);
    _0x71n = BigInt(113);
    SHA3_PI = [];
    SHA3_ROTL = [];
    _SHA3_IOTA = [];
    for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
      [x, y] = [y, (2 * x + 3 * y) % 5];
      SHA3_PI.push(2 * (5 * y + x));
      SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
      let t = _0n;
      for (let j = 0; j < 7; j++) {
        R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n;
        if (R & _2n)
          t ^= _1n << (_1n << /* @__PURE__ */ BigInt(j)) - _1n;
      }
      _SHA3_IOTA.push(t);
    }
    IOTAS = split(_SHA3_IOTA, true);
    SHA3_IOTA_H = IOTAS[0];
    SHA3_IOTA_L = IOTAS[1];
    rotlH = (h, l2, s3) => s3 > 32 ? rotlBH(h, l2, s3) : rotlSH(h, l2, s3);
    rotlL = (h, l2, s3) => s3 > 32 ? rotlBL(h, l2, s3) : rotlSL(h, l2, s3);
    Keccak = class _Keccak extends Hash {
      // NOTE: we accept arguments in bytes instead of bits here.
      constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
        super();
        this.pos = 0;
        this.posOut = 0;
        this.finished = false;
        this.destroyed = false;
        this.enableXOF = false;
        this.blockLen = blockLen;
        this.suffix = suffix;
        this.outputLen = outputLen;
        this.enableXOF = enableXOF;
        this.rounds = rounds;
        anumber(outputLen);
        if (!(0 < blockLen && blockLen < 200))
          throw new Error("only keccak-f1600 function is supported");
        this.state = new Uint8Array(200);
        this.state32 = u32(this.state);
      }
      clone() {
        return this._cloneInto();
      }
      keccak() {
        swap32IfBE(this.state32);
        keccakP(this.state32, this.rounds);
        swap32IfBE(this.state32);
        this.posOut = 0;
        this.pos = 0;
      }
      update(data) {
        aexists(this);
        data = toBytes2(data);
        abytes(data);
        const { blockLen, state } = this;
        const len = data.length;
        for (let pos = 0; pos < len; ) {
          const take = Math.min(blockLen - this.pos, len - pos);
          for (let i = 0; i < take; i++)
            state[this.pos++] ^= data[pos++];
          if (this.pos === blockLen)
            this.keccak();
        }
        return this;
      }
      finish() {
        if (this.finished)
          return;
        this.finished = true;
        const { state, suffix, pos, blockLen } = this;
        state[pos] ^= suffix;
        if ((suffix & 128) !== 0 && pos === blockLen - 1)
          this.keccak();
        state[blockLen - 1] ^= 128;
        this.keccak();
      }
      writeInto(out) {
        aexists(this, false);
        abytes(out);
        this.finish();
        const bufferOut = this.state;
        const { blockLen } = this;
        for (let pos = 0, len = out.length; pos < len; ) {
          if (this.posOut >= blockLen)
            this.keccak();
          const take = Math.min(blockLen - this.posOut, len - pos);
          out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
          this.posOut += take;
          pos += take;
        }
        return out;
      }
      xofInto(out) {
        if (!this.enableXOF)
          throw new Error("XOF is not possible for this instance");
        return this.writeInto(out);
      }
      xof(bytes) {
        anumber(bytes);
        return this.xofInto(new Uint8Array(bytes));
      }
      digestInto(out) {
        aoutput(out, this);
        if (this.finished)
          throw new Error("digest() was already called");
        this.writeInto(out);
        this.destroy();
        return out;
      }
      digest() {
        return this.digestInto(new Uint8Array(this.outputLen));
      }
      destroy() {
        this.destroyed = true;
        clean(this.state);
      }
      _cloneInto(to) {
        const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
        to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
        to.state32.set(this.state32);
        to.pos = this.pos;
        to.posOut = this.posOut;
        to.finished = this.finished;
        to.rounds = rounds;
        to.suffix = suffix;
        to.outputLen = outputLen;
        to.enableXOF = enableXOF;
        to.destroyed = this.destroyed;
        return to;
      }
    };
    gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
    keccak_256 = /* @__PURE__ */ (() => gen(1, 136, 256 / 8))();
  }
});

// node_modules/viem/_esm/utils/hash/keccak256.js
function keccak256(value, to_) {
  const to = to_ || "hex";
  const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes(value) : value);
  if (to === "bytes")
    return bytes;
  return toHex(bytes);
}
var init_keccak256 = __esm({
  "node_modules/viem/_esm/utils/hash/keccak256.js"() {
    "use strict";
    init_sha3();
    init_isHex();
    init_toBytes();
    init_toHex();
  }
});

// node_modules/viem/_esm/utils/hash/hashSignature.js
function hashSignature(sig) {
  return hash(sig);
}
var hash;
var init_hashSignature = __esm({
  "node_modules/viem/_esm/utils/hash/hashSignature.js"() {
    "use strict";
    init_toBytes();
    init_keccak256();
    hash = (value) => keccak256(toBytes(value));
  }
});

// node_modules/viem/_esm/utils/hash/normalizeSignature.js
function normalizeSignature(signature2) {
  let active = true;
  let current = "";
  let level = 0;
  let result = "";
  let valid = false;
  for (let i = 0; i < signature2.length; i++) {
    const char = signature2[i];
    if (["(", ")", ","].includes(char))
      active = true;
    if (char === "(")
      level++;
    if (char === ")")
      level--;
    if (!active)
      continue;
    if (level === 0) {
      if (char === " " && ["event", "function", ""].includes(result))
        result = "";
      else {
        result += char;
        if (char === ")") {
          valid = true;
          break;
        }
      }
      continue;
    }
    if (char === " ") {
      if (signature2[i - 1] !== "," && current !== "," && current !== ",(") {
        current = "";
        active = false;
      }
      continue;
    }
    result += char;
    current += char;
  }
  if (!valid)
    throw new BaseError2("Unable to normalize signature.");
  return result;
}
var init_normalizeSignature = __esm({
  "node_modules/viem/_esm/utils/hash/normalizeSignature.js"() {
    "use strict";
    init_base();
  }
});

// node_modules/viem/_esm/utils/hash/toSignature.js
var toSignature;
var init_toSignature = __esm({
  "node_modules/viem/_esm/utils/hash/toSignature.js"() {
    "use strict";
    init_exports();
    init_normalizeSignature();
    toSignature = (def) => {
      const def_ = (() => {
        if (typeof def === "string")
          return def;
        return formatAbiItem(def);
      })();
      return normalizeSignature(def_);
    };
  }
});

// node_modules/viem/_esm/utils/hash/toSignatureHash.js
function toSignatureHash(fn) {
  return hashSignature(toSignature(fn));
}
var init_toSignatureHash = __esm({
  "node_modules/viem/_esm/utils/hash/toSignatureHash.js"() {
    "use strict";
    init_hashSignature();
    init_toSignature();
  }
});

// node_modules/viem/_esm/utils/hash/toEventSelector.js
var toEventSelector;
var init_toEventSelector = __esm({
  "node_modules/viem/_esm/utils/hash/toEventSelector.js"() {
    "use strict";
    init_toSignatureHash();
    toEventSelector = toSignatureHash;
  }
});

// node_modules/viem/_esm/errors/address.js
var InvalidAddressError;
var init_address = __esm({
  "node_modules/viem/_esm/errors/address.js"() {
    "use strict";
    init_base();
    InvalidAddressError = class extends BaseError2 {
      constructor({ address: address2 }) {
        super(`Address "${address2}" is invalid.`, {
          metaMessages: [
            "- Address must be a hex value of 20 bytes (40 hex characters).",
            "- Address must match its checksum counterpart."
          ],
          name: "InvalidAddressError"
        });
      }
    };
  }
});

// node_modules/viem/_esm/utils/lru.js
var LruMap;
var init_lru = __esm({
  "node_modules/viem/_esm/utils/lru.js"() {
    "use strict";
    LruMap = class extends Map {
      constructor(size5) {
        super();
        Object.defineProperty(this, "maxSize", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.maxSize = size5;
      }
      get(key) {
        const value = super.get(key);
        if (super.has(key)) {
          super.delete(key);
          super.set(key, value);
        }
        return value;
      }
      set(key, value) {
        if (super.has(key))
          super.delete(key);
        super.set(key, value);
        if (this.maxSize && this.size > this.maxSize) {
          const firstKey = super.keys().next().value;
          if (firstKey !== void 0)
            super.delete(firstKey);
        }
        return this;
      }
    };
  }
});

// node_modules/viem/_esm/utils/address/getAddress.js
function checksumAddress(address_, chainId) {
  if (checksumAddressCache.has(`${address_}.${chainId}`))
    return checksumAddressCache.get(`${address_}.${chainId}`);
  const hexAddress = chainId ? `${chainId}${address_.toLowerCase()}` : address_.substring(2).toLowerCase();
  const hash3 = keccak256(stringToBytes(hexAddress), "bytes");
  const address2 = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split("");
  for (let i = 0; i < 40; i += 2) {
    if (hash3[i >> 1] >> 4 >= 8 && address2[i]) {
      address2[i] = address2[i].toUpperCase();
    }
    if ((hash3[i >> 1] & 15) >= 8 && address2[i + 1]) {
      address2[i + 1] = address2[i + 1].toUpperCase();
    }
  }
  const result = `0x${address2.join("")}`;
  checksumAddressCache.set(`${address_}.${chainId}`, result);
  return result;
}
function getAddress(address2, chainId) {
  if (!isAddress(address2, { strict: false }))
    throw new InvalidAddressError({ address: address2 });
  return checksumAddress(address2, chainId);
}
var checksumAddressCache;
var init_getAddress = __esm({
  "node_modules/viem/_esm/utils/address/getAddress.js"() {
    "use strict";
    init_address();
    init_toBytes();
    init_keccak256();
    init_lru();
    init_isAddress();
    checksumAddressCache = /* @__PURE__ */ new LruMap(8192);
  }
});

// node_modules/viem/_esm/utils/address/isAddress.js
function isAddress(address2, options) {
  const { strict = true } = options ?? {};
  const cacheKey2 = `${address2}.${strict}`;
  if (isAddressCache.has(cacheKey2))
    return isAddressCache.get(cacheKey2);
  const result = (() => {
    if (!addressRegex.test(address2))
      return false;
    if (address2.toLowerCase() === address2)
      return true;
    if (strict)
      return checksumAddress(address2) === address2;
    return true;
  })();
  isAddressCache.set(cacheKey2, result);
  return result;
}
var addressRegex, isAddressCache;
var init_isAddress = __esm({
  "node_modules/viem/_esm/utils/address/isAddress.js"() {
    "use strict";
    init_lru();
    init_getAddress();
    addressRegex = /^0x[a-fA-F0-9]{40}$/;
    isAddressCache = /* @__PURE__ */ new LruMap(8192);
  }
});

// node_modules/viem/_esm/utils/data/concat.js
function concat(values) {
  if (typeof values[0] === "string")
    return concatHex(values);
  return concatBytes2(values);
}
function concatBytes2(values) {
  let length = 0;
  for (const arr of values) {
    length += arr.length;
  }
  const result = new Uint8Array(length);
  let offset = 0;
  for (const arr of values) {
    result.set(arr, offset);
    offset += arr.length;
  }
  return result;
}
function concatHex(values) {
  return `0x${values.reduce((acc, x) => acc + x.replace("0x", ""), "")}`;
}
var init_concat = __esm({
  "node_modules/viem/_esm/utils/data/concat.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/utils/data/slice.js
function slice(value, start, end, { strict } = {}) {
  if (isHex(value, { strict: false }))
    return sliceHex(value, start, end, {
      strict
    });
  return sliceBytes(value, start, end, {
    strict
  });
}
function assertStartOffset(value, start) {
  if (typeof start === "number" && start > 0 && start > size(value) - 1)
    throw new SliceOffsetOutOfBoundsError({
      offset: start,
      position: "start",
      size: size(value)
    });
}
function assertEndOffset(value, start, end) {
  if (typeof start === "number" && typeof end === "number" && size(value) !== end - start) {
    throw new SliceOffsetOutOfBoundsError({
      offset: end,
      position: "end",
      size: size(value)
    });
  }
}
function sliceBytes(value_, start, end, { strict } = {}) {
  assertStartOffset(value_, start);
  const value = value_.slice(start, end);
  if (strict)
    assertEndOffset(value, start, end);
  return value;
}
function sliceHex(value_, start, end, { strict } = {}) {
  assertStartOffset(value_, start);
  const value = `0x${value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`;
  if (strict)
    assertEndOffset(value, start, end);
  return value;
}
var init_slice = __esm({
  "node_modules/viem/_esm/utils/data/slice.js"() {
    "use strict";
    init_data();
    init_isHex();
    init_size();
  }
});

// node_modules/viem/_esm/utils/regex.js
var bytesRegex2, integerRegex2;
var init_regex2 = __esm({
  "node_modules/viem/_esm/utils/regex.js"() {
    "use strict";
    bytesRegex2 = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;
    integerRegex2 = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;
  }
});

// node_modules/viem/_esm/utils/abi/encodeAbiParameters.js
function encodeAbiParameters(params, values) {
  if (params.length !== values.length)
    throw new AbiEncodingLengthMismatchError({
      expectedLength: params.length,
      givenLength: values.length
    });
  const preparedParams = prepareParams({
    params,
    values
  });
  const data = encodeParams(preparedParams);
  if (data.length === 0)
    return "0x";
  return data;
}
function prepareParams({ params, values }) {
  const preparedParams = [];
  for (let i = 0; i < params.length; i++) {
    preparedParams.push(prepareParam({ param: params[i], value: values[i] }));
  }
  return preparedParams;
}
function prepareParam({ param, value }) {
  const arrayComponents = getArrayComponents(param.type);
  if (arrayComponents) {
    const [length, type] = arrayComponents;
    return encodeArray(value, { length, param: { ...param, type } });
  }
  if (param.type === "tuple") {
    return encodeTuple(value, {
      param
    });
  }
  if (param.type === "address") {
    return encodeAddress(value);
  }
  if (param.type === "bool") {
    return encodeBool(value);
  }
  if (param.type.startsWith("uint") || param.type.startsWith("int")) {
    const signed = param.type.startsWith("int");
    const [, , size5 = "256"] = integerRegex2.exec(param.type) ?? [];
    return encodeNumber(value, {
      signed,
      size: Number(size5)
    });
  }
  if (param.type.startsWith("bytes")) {
    return encodeBytes(value, { param });
  }
  if (param.type === "string") {
    return encodeString(value);
  }
  throw new InvalidAbiEncodingTypeError(param.type, {
    docsPath: "/docs/contract/encodeAbiParameters"
  });
}
function encodeParams(preparedParams) {
  let staticSize = 0;
  for (let i = 0; i < preparedParams.length; i++) {
    const { dynamic, encoded } = preparedParams[i];
    if (dynamic)
      staticSize += 32;
    else
      staticSize += size(encoded);
  }
  const staticParams = [];
  const dynamicParams = [];
  let dynamicSize = 0;
  for (let i = 0; i < preparedParams.length; i++) {
    const { dynamic, encoded } = preparedParams[i];
    if (dynamic) {
      staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 }));
      dynamicParams.push(encoded);
      dynamicSize += size(encoded);
    } else {
      staticParams.push(encoded);
    }
  }
  return concat([...staticParams, ...dynamicParams]);
}
function encodeAddress(value) {
  if (!isAddress(value))
    throw new InvalidAddressError({ address: value });
  return { dynamic: false, encoded: padHex(value.toLowerCase()) };
}
function encodeArray(value, { length, param }) {
  const dynamic = length === null;
  if (!Array.isArray(value))
    throw new InvalidArrayError(value);
  if (!dynamic && value.length !== length)
    throw new AbiEncodingArrayLengthMismatchError({
      expectedLength: length,
      givenLength: value.length,
      type: `${param.type}[${length}]`
    });
  let dynamicChild = false;
  const preparedParams = [];
  for (let i = 0; i < value.length; i++) {
    const preparedParam = prepareParam({ param, value: value[i] });
    if (preparedParam.dynamic)
      dynamicChild = true;
    preparedParams.push(preparedParam);
  }
  if (dynamic || dynamicChild) {
    const data = encodeParams(preparedParams);
    if (dynamic) {
      const length2 = numberToHex(preparedParams.length, { size: 32 });
      return {
        dynamic: true,
        encoded: preparedParams.length > 0 ? concat([length2, data]) : length2
      };
    }
    if (dynamicChild)
      return { dynamic: true, encoded: data };
  }
  return {
    dynamic: false,
    encoded: concat(preparedParams.map(({ encoded }) => encoded))
  };
}
function encodeBytes(value, { param }) {
  const [, paramSize] = param.type.split("bytes");
  const bytesSize = size(value);
  if (!paramSize) {
    let value_ = value;
    if (bytesSize % 32 !== 0)
      value_ = padHex(value_, {
        dir: "right",
        size: Math.ceil((value.length - 2) / 2 / 32) * 32
      });
    return {
      dynamic: true,
      encoded: concat([padHex(numberToHex(bytesSize, { size: 32 })), value_])
    };
  }
  if (bytesSize !== Number.parseInt(paramSize, 10))
    throw new AbiEncodingBytesSizeMismatchError({
      expectedSize: Number.parseInt(paramSize, 10),
      value
    });
  return { dynamic: false, encoded: padHex(value, { dir: "right" }) };
}
function encodeBool(value) {
  if (typeof value !== "boolean")
    throw new BaseError2(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`);
  return { dynamic: false, encoded: padHex(boolToHex(value)) };
}
function encodeNumber(value, { signed, size: size5 = 256 }) {
  if (typeof size5 === "number") {
    const max = 2n ** (BigInt(size5) - (signed ? 1n : 0n)) - 1n;
    const min = signed ? -max - 1n : 0n;
    if (value > max || value < min)
      throw new IntegerOutOfRangeError({
        max: max.toString(),
        min: min.toString(),
        signed,
        size: size5 / 8,
        value: value.toString()
      });
  }
  return {
    dynamic: false,
    encoded: numberToHex(value, {
      size: 32,
      signed
    })
  };
}
function encodeString(value) {
  const hexValue = stringToHex(value);
  const partsLength = Math.ceil(size(hexValue) / 32);
  const parts = [];
  for (let i = 0; i < partsLength; i++) {
    parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), {
      dir: "right"
    }));
  }
  return {
    dynamic: true,
    encoded: concat([
      padHex(numberToHex(size(hexValue), { size: 32 })),
      ...parts
    ])
  };
}
function encodeTuple(value, { param }) {
  let dynamic = false;
  const preparedParams = [];
  for (let i = 0; i < param.components.length; i++) {
    const param_ = param.components[i];
    const index2 = Array.isArray(value) ? i : param_.name;
    const preparedParam = prepareParam({
      param: param_,
      value: value[index2]
    });
    preparedParams.push(preparedParam);
    if (preparedParam.dynamic)
      dynamic = true;
  }
  return {
    dynamic,
    encoded: dynamic ? encodeParams(preparedParams) : concat(preparedParams.map(({ encoded }) => encoded))
  };
}
function getArrayComponents(type) {
  const matches = type.match(/^(.*)\[(\d+)?\]$/);
  return matches ? (
    // Return `null` if the array is dynamic.
    [matches[2] ? Number(matches[2]) : null, matches[1]]
  ) : void 0;
}
var init_encodeAbiParameters = __esm({
  "node_modules/viem/_esm/utils/abi/encodeAbiParameters.js"() {
    "use strict";
    init_abi();
    init_address();
    init_base();
    init_encoding();
    init_isAddress();
    init_concat();
    init_pad();
    init_size();
    init_slice();
    init_toHex();
    init_regex2();
  }
});

// node_modules/viem/_esm/utils/hash/toFunctionSelector.js
var toFunctionSelector;
var init_toFunctionSelector = __esm({
  "node_modules/viem/_esm/utils/hash/toFunctionSelector.js"() {
    "use strict";
    init_slice();
    init_toSignatureHash();
    toFunctionSelector = (fn) => slice(toSignatureHash(fn), 0, 4);
  }
});

// node_modules/viem/_esm/utils/abi/getAbiItem.js
function getAbiItem(parameters) {
  const { abi: abi2, args = [], name } = parameters;
  const isSelector = isHex(name, { strict: false });
  const abiItems = abi2.filter((abiItem) => {
    if (isSelector) {
      if (abiItem.type === "function")
        return toFunctionSelector(abiItem) === name;
      if (abiItem.type === "event")
        return toEventSelector(abiItem) === name;
      return false;
    }
    return "name" in abiItem && abiItem.name === name;
  });
  if (abiItems.length === 0)
    return void 0;
  if (abiItems.length === 1)
    return abiItems[0];
  let matchedAbiItem;
  for (const abiItem of abiItems) {
    if (!("inputs" in abiItem))
      continue;
    if (!args || args.length === 0) {
      if (!abiItem.inputs || abiItem.inputs.length === 0)
        return abiItem;
      continue;
    }
    if (!abiItem.inputs)
      continue;
    if (abiItem.inputs.length === 0)
      continue;
    if (abiItem.inputs.length !== args.length)
      continue;
    const matched = args.every((arg, index2) => {
      const abiParameter = "inputs" in abiItem && abiItem.inputs[index2];
      if (!abiParameter)
        return false;
      return isArgOfType(arg, abiParameter);
    });
    if (matched) {
      if (matchedAbiItem && "inputs" in matchedAbiItem && matchedAbiItem.inputs) {
        const ambiguousTypes = getAmbiguousTypes(abiItem.inputs, matchedAbiItem.inputs, args);
        if (ambiguousTypes)
          throw new AbiItemAmbiguityError({
            abiItem,
            type: ambiguousTypes[0]
          }, {
            abiItem: matchedAbiItem,
            type: ambiguousTypes[1]
          });
      }
      matchedAbiItem = abiItem;
    }
  }
  if (matchedAbiItem)
    return matchedAbiItem;
  return abiItems[0];
}
function isArgOfType(arg, abiParameter) {
  const argType = typeof arg;
  const abiParameterType = abiParameter.type;
  switch (abiParameterType) {
    case "address":
      return isAddress(arg, { strict: false });
    case "bool":
      return argType === "boolean";
    case "function":
      return argType === "string";
    case "string":
      return argType === "string";
    default: {
      if (abiParameterType === "tuple" && "components" in abiParameter)
        return Object.values(abiParameter.components).every((component, index2) => {
          return argType === "object" && isArgOfType(Object.values(arg)[index2], component);
        });
      if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType))
        return argType === "number" || argType === "bigint";
      if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType))
        return argType === "string" || arg instanceof Uint8Array;
      if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) {
        return Array.isArray(arg) && arg.every((x) => isArgOfType(x, {
          ...abiParameter,
          // Pop off `[]` or `[M]` from end of type
          type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "")
        }));
      }
      return false;
    }
  }
}
function getAmbiguousTypes(sourceParameters, targetParameters, args) {
  for (const parameterIndex in sourceParameters) {
    const sourceParameter = sourceParameters[parameterIndex];
    const targetParameter = targetParameters[parameterIndex];
    if (sourceParameter.type === "tuple" && targetParameter.type === "tuple" && "components" in sourceParameter && "components" in targetParameter)
      return getAmbiguousTypes(sourceParameter.components, targetParameter.components, args[parameterIndex]);
    const types = [sourceParameter.type, targetParameter.type];
    const ambiguous = (() => {
      if (types.includes("address") && types.includes("bytes20"))
        return true;
      if (types.includes("address") && types.includes("string"))
        return isAddress(args[parameterIndex], { strict: false });
      if (types.includes("address") && types.includes("bytes"))
        return isAddress(args[parameterIndex], { strict: false });
      return false;
    })();
    if (ambiguous)
      return types;
  }
  return;
}
var init_getAbiItem = __esm({
  "node_modules/viem/_esm/utils/abi/getAbiItem.js"() {
    "use strict";
    init_abi();
    init_isHex();
    init_isAddress();
    init_toEventSelector();
    init_toFunctionSelector();
  }
});

// node_modules/viem/_esm/utils/abi/encodeEventTopics.js
function encodeEventTopics(parameters) {
  const { abi: abi2, eventName, args } = parameters;
  let abiItem = abi2[0];
  if (eventName) {
    const item = getAbiItem({ abi: abi2, name: eventName });
    if (!item)
      throw new AbiEventNotFoundError(eventName, { docsPath });
    abiItem = item;
  }
  if (abiItem.type !== "event")
    throw new AbiEventNotFoundError(void 0, { docsPath });
  const definition = formatAbiItem2(abiItem);
  const signature2 = toEventSelector(definition);
  let topics = [];
  if (args && "inputs" in abiItem) {
    const indexedInputs = abiItem.inputs?.filter((param) => "indexed" in param && param.indexed);
    const args_ = Array.isArray(args) ? args : Object.values(args).length > 0 ? indexedInputs?.map((x) => args[x.name]) ?? [] : [];
    if (args_.length > 0) {
      topics = indexedInputs?.map((param, i) => {
        if (Array.isArray(args_[i]))
          return args_[i].map((_, j) => encodeArg({ param, value: args_[i][j] }));
        return typeof args_[i] !== "undefined" && args_[i] !== null ? encodeArg({ param, value: args_[i] }) : null;
      }) ?? [];
    }
  }
  return [signature2, ...topics];
}
function encodeArg({ param, value }) {
  if (param.type === "string" || param.type === "bytes")
    return keccak256(toBytes(value));
  if (param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/))
    throw new FilterTypeNotSupportedError(param.type);
  return encodeAbiParameters([param], [value]);
}
var docsPath;
var init_encodeEventTopics = __esm({
  "node_modules/viem/_esm/utils/abi/encodeEventTopics.js"() {
    "use strict";
    init_abi();
    init_log();
    init_toBytes();
    init_keccak256();
    init_toEventSelector();
    init_encodeAbiParameters();
    init_formatAbiItem2();
    init_getAbiItem();
    docsPath = "/docs/contract/encodeEventTopics";
  }
});

// node_modules/viem/_esm/utils/filters/createFilterRequestScope.js
function createFilterRequestScope(client, { method }) {
  const requestMap = {};
  if (client.transport.type === "fallback")
    client.transport.onResponse?.(({ method: method_, response: id, status, transport }) => {
      if (status === "success" && method === method_)
        requestMap[id] = transport.request;
    });
  return ((id) => requestMap[id] || client.request);
}
var init_createFilterRequestScope = __esm({
  "node_modules/viem/_esm/utils/filters/createFilterRequestScope.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/actions/public/createContractEventFilter.js
async function createContractEventFilter(client, parameters) {
  const { address: address2, abi: abi2, args, eventName, fromBlock, strict, toBlock } = parameters;
  const getRequest = createFilterRequestScope(client, {
    method: "eth_newFilter"
  });
  const topics = eventName ? encodeEventTopics({
    abi: abi2,
    args,
    eventName
  }) : void 0;
  const id = await client.request({
    method: "eth_newFilter",
    params: [
      {
        address: address2,
        fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock,
        toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock,
        topics
      }
    ]
  });
  return {
    abi: abi2,
    args,
    eventName,
    id,
    request: getRequest(id),
    strict: Boolean(strict),
    type: "event"
  };
}
var init_createContractEventFilter = __esm({
  "node_modules/viem/_esm/actions/public/createContractEventFilter.js"() {
    "use strict";
    init_encodeEventTopics();
    init_toHex();
    init_createFilterRequestScope();
  }
});

// node_modules/viem/_esm/accounts/utils/parseAccount.js
function parseAccount(account) {
  if (typeof account === "string")
    return { address: account, type: "json-rpc" };
  return account;
}
var init_parseAccount = __esm({
  "node_modules/viem/_esm/accounts/utils/parseAccount.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/utils/abi/prepareEncodeFunctionData.js
function prepareEncodeFunctionData(parameters) {
  const { abi: abi2, args, functionName } = parameters;
  let abiItem = abi2[0];
  if (functionName) {
    const item = getAbiItem({
      abi: abi2,
      args,
      name: functionName
    });
    if (!item)
      throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath2 });
    abiItem = item;
  }
  if (abiItem.type !== "function")
    throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath2 });
  return {
    abi: [abiItem],
    functionName: toFunctionSelector(formatAbiItem2(abiItem))
  };
}
var docsPath2;
var init_prepareEncodeFunctionData = __esm({
  "node_modules/viem/_esm/utils/abi/prepareEncodeFunctionData.js"() {
    "use strict";
    init_abi();
    init_toFunctionSelector();
    init_formatAbiItem2();
    init_getAbiItem();
    docsPath2 = "/docs/contract/encodeFunctionData";
  }
});

// node_modules/viem/_esm/utils/abi/encodeFunctionData.js
function encodeFunctionData(parameters) {
  const { args } = parameters;
  const { abi: abi2, functionName } = (() => {
    if (parameters.abi.length === 1 && parameters.functionName?.startsWith("0x"))
      return parameters;
    return prepareEncodeFunctionData(parameters);
  })();
  const abiItem = abi2[0];
  const signature2 = functionName;
  const data = "inputs" in abiItem && abiItem.inputs ? encodeAbiParameters(abiItem.inputs, args ?? []) : void 0;
  return concatHex([signature2, data ?? "0x"]);
}
var init_encodeFunctionData = __esm({
  "node_modules/viem/_esm/utils/abi/encodeFunctionData.js"() {
    "use strict";
    init_concat();
    init_encodeAbiParameters();
    init_prepareEncodeFunctionData();
  }
});

// node_modules/viem/_esm/constants/solidity.js
var panicReasons, solidityError, solidityPanic;
var init_solidity = __esm({
  "node_modules/viem/_esm/constants/solidity.js"() {
    "use strict";
    panicReasons = {
      1: "An `assert` condition failed.",
      17: "Arithmetic operation resulted in underflow or overflow.",
      18: "Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).",
      33: "Attempted to convert to an invalid type.",
      34: "Attempted to access a storage byte array that is incorrectly encoded.",
      49: "Performed `.pop()` on an empty array",
      50: "Array index is out of bounds.",
      65: "Allocated too much memory or created an array which is too large.",
      81: "Attempted to call a zero-initialized variable of internal function type."
    };
    solidityError = {
      inputs: [
        {
          name: "message",
          type: "string"
        }
      ],
      name: "Error",
      type: "error"
    };
    solidityPanic = {
      inputs: [
        {
          name: "reason",
          type: "uint256"
        }
      ],
      name: "Panic",
      type: "error"
    };
  }
});

// node_modules/viem/_esm/errors/cursor.js
var NegativeOffsetError, PositionOutOfBoundsError, RecursiveReadLimitExceededError;
var init_cursor = __esm({
  "node_modules/viem/_esm/errors/cursor.js"() {
    "use strict";
    init_base();
    NegativeOffsetError = class extends BaseError2 {
      constructor({ offset }) {
        super(`Offset \`${offset}\` cannot be negative.`, {
          name: "NegativeOffsetError"
        });
      }
    };
    PositionOutOfBoundsError = class extends BaseError2 {
      constructor({ length, position }) {
        super(`Position \`${position}\` is out of bounds (\`0 < position < ${length}\`).`, { name: "PositionOutOfBoundsError" });
      }
    };
    RecursiveReadLimitExceededError = class extends BaseError2 {
      constructor({ count, limit }) {
        super(`Recursive read limit of \`${limit}\` exceeded (recursive read count: \`${count}\`).`, { name: "RecursiveReadLimitExceededError" });
      }
    };
  }
});

// node_modules/viem/_esm/utils/cursor.js
function createCursor(bytes, { recursiveReadLimit = 8192 } = {}) {
  const cursor = Object.create(staticCursor);
  cursor.bytes = bytes;
  cursor.dataView = new DataView(bytes.buffer ?? bytes, bytes.byteOffset, bytes.byteLength);
  cursor.positionReadCount = /* @__PURE__ */ new Map();
  cursor.recursiveReadLimit = recursiveReadLimit;
  return cursor;
}
var staticCursor;
var init_cursor2 = __esm({
  "node_modules/viem/_esm/utils/cursor.js"() {
    "use strict";
    init_cursor();
    staticCursor = {
      bytes: new Uint8Array(),
      dataView: new DataView(new ArrayBuffer(0)),
      position: 0,
      positionReadCount: /* @__PURE__ */ new Map(),
      recursiveReadCount: 0,
      recursiveReadLimit: Number.POSITIVE_INFINITY,
      assertReadLimit() {
        if (this.recursiveReadCount >= this.recursiveReadLimit)
          throw new RecursiveReadLimitExceededError({
            count: this.recursiveReadCount + 1,
            limit: this.recursiveReadLimit
          });
      },
      assertPosition(position) {
        if (position < 0 || position > this.bytes.length - 1)
          throw new PositionOutOfBoundsError({
            length: this.bytes.length,
            position
          });
      },
      decrementPosition(offset) {
        if (offset < 0)
          throw new NegativeOffsetError({ offset });
        const position = this.position - offset;
        this.assertPosition(position);
        this.position = position;
      },
      getReadCount(position) {
        return this.positionReadCount.get(position || this.position) || 0;
      },
      incrementPosition(offset) {
        if (offset < 0)
          throw new NegativeOffsetError({ offset });
        const position = this.position + offset;
        this.assertPosition(position);
        this.position = position;
      },
      inspectByte(position_) {
        const position = position_ ?? this.position;
        this.assertPosition(position);
        return this.bytes[position];
      },
      inspectBytes(length, position_) {
        const position = position_ ?? this.position;
        this.assertPosition(position + length - 1);
        return this.bytes.subarray(position, position + length);
      },
      inspectUint8(position_) {
        const position = position_ ?? this.position;
        this.assertPosition(position);
        return this.bytes[position];
      },
      inspectUint16(position_) {
        const position = position_ ?? this.position;
        this.assertPosition(position + 1);
        return this.dataView.getUint16(position);
      },
      inspectUint24(position_) {
        const position = position_ ?? this.position;
        this.assertPosition(position + 2);
        return (this.dataView.getUint16(position) << 8) + this.dataView.getUint8(position + 2);
      },
      inspectUint32(position_) {
        const position = position_ ?? this.position;
        this.assertPosition(position + 3);
        return this.dataView.getUint32(position);
      },
      pushByte(byte) {
        this.assertPosition(this.position);
        this.bytes[this.position] = byte;
        this.position++;
      },
      pushBytes(bytes) {
        this.assertPosition(this.position + bytes.length - 1);
        this.bytes.set(bytes, this.position);
        this.position += bytes.length;
      },
      pushUint8(value) {
        this.assertPosition(this.position);
        this.bytes[this.position] = value;
        this.position++;
      },
      pushUint16(value) {
        this.assertPosition(this.position + 1);
        this.dataView.setUint16(this.position, value);
        this.position += 2;
      },
      pushUint24(value) {
        this.assertPosition(this.position + 2);
        this.dataView.setUint16(this.position, value >> 8);
        this.dataView.setUint8(this.position + 2, value & ~4294967040);
        this.position += 3;
      },
      pushUint32(value) {
        this.assertPosition(this.position + 3);
        this.dataView.setUint32(this.position, value);
        this.position += 4;
      },
      readByte() {
        this.assertReadLimit();
        this._touch();
        const value = this.inspectByte();
        this.position++;
        return value;
      },
      readBytes(length, size5) {
        this.assertReadLimit();
        this._touch();
        const value = this.inspectBytes(length);
        this.position += size5 ?? length;
        return value;
      },
      readUint8() {
        this.assertReadLimit();
        this._touch();
        const value = this.inspectUint8();
        this.position += 1;
        return value;
      },
      readUint16() {
        this.assertReadLimit();
        this._touch();
        const value = this.inspectUint16();
        this.position += 2;
        return value;
      },
      readUint24() {
        this.assertReadLimit();
        this._touch();
        const value = this.inspectUint24();
        this.position += 3;
        return value;
      },
      readUint32() {
        this.assertReadLimit();
        this._touch();
        const value = this.inspectUint32();
        this.position += 4;
        return value;
      },
      get remaining() {
        return this.bytes.length - this.position;
      },
      setPosition(position) {
        const oldPosition = this.position;
        this.assertPosition(position);
        this.position = position;
        return () => this.position = oldPosition;
      },
      _touch() {
        if (this.recursiveReadLimit === Number.POSITIVE_INFINITY)
          return;
        const count = this.getReadCount();
        this.positionReadCount.set(this.position, count + 1);
        if (count > 0)
          this.recursiveReadCount++;
      }
    };
  }
});

// node_modules/viem/_esm/utils/encoding/fromBytes.js
function bytesToBigInt(bytes, opts = {}) {
  if (typeof opts.size !== "undefined")
    assertSize(bytes, { size: opts.size });
  const hex = bytesToHex(bytes, opts);
  return hexToBigInt(hex, opts);
}
function bytesToBool(bytes_, opts = {}) {
  let bytes = bytes_;
  if (typeof opts.size !== "undefined") {
    assertSize(bytes, { size: opts.size });
    bytes = trim(bytes);
  }
  if (bytes.length > 1 || bytes[0] > 1)
    throw new InvalidBytesBooleanError(bytes);
  return Boolean(bytes[0]);
}
function bytesToNumber(bytes, opts = {}) {
  if (typeof opts.size !== "undefined")
    assertSize(bytes, { size: opts.size });
  const hex = bytesToHex(bytes, opts);
  return hexToNumber(hex, opts);
}
function bytesToString(bytes_, opts = {}) {
  let bytes = bytes_;
  if (typeof opts.size !== "undefined") {
    assertSize(bytes, { size: opts.size });
    bytes = trim(bytes, { dir: "right" });
  }
  return new TextDecoder().decode(bytes);
}
var init_fromBytes = __esm({
  "node_modules/viem/_esm/utils/encoding/fromBytes.js"() {
    "use strict";
    init_encoding();
    init_trim();
    init_fromHex();
    init_toHex();
  }
});

// node_modules/viem/_esm/utils/abi/decodeAbiParameters.js
function decodeAbiParameters(params, data) {
  const bytes = typeof data === "string" ? hexToBytes(data) : data;
  const cursor = createCursor(bytes);
  if (size(bytes) === 0 && params.length > 0)
    throw new AbiDecodingZeroDataError();
  if (size(data) && size(data) < 32)
    throw new AbiDecodingDataSizeTooSmallError({
      data: typeof data === "string" ? data : bytesToHex(data),
      params,
      size: size(data)
    });
  let consumed = 0;
  const values = [];
  for (let i = 0; i < params.length; ++i) {
    const param = params[i];
    cursor.setPosition(consumed);
    const [data2, consumed_] = decodeParameter(cursor, param, {
      staticPosition: 0
    });
    consumed += consumed_;
    values.push(data2);
  }
  return values;
}
function decodeParameter(cursor, param, { staticPosition }) {
  const arrayComponents = getArrayComponents(param.type);
  if (arrayComponents) {
    const [length, type] = arrayComponents;
    return decodeArray(cursor, { ...param, type }, { length, staticPosition });
  }
  if (param.type === "tuple")
    return decodeTuple(cursor, param, { staticPosition });
  if (param.type === "address")
    return decodeAddress(cursor);
  if (param.type === "bool")
    return decodeBool(cursor);
  if (param.type.startsWith("bytes"))
    return decodeBytes(cursor, param, { staticPosition });
  if (param.type.startsWith("uint") || param.type.startsWith("int"))
    return decodeNumber(cursor, param);
  if (param.type === "string")
    return decodeString(cursor, { staticPosition });
  throw new InvalidAbiDecodingTypeError(param.type, {
    docsPath: "/docs/contract/decodeAbiParameters"
  });
}
function decodeAddress(cursor) {
  const value = cursor.readBytes(32);
  return [checksumAddress(bytesToHex(sliceBytes(value, -20))), 32];
}
function decodeArray(cursor, param, { length, staticPosition }) {
  if (!length) {
    const offset = bytesToNumber(cursor.readBytes(sizeOfOffset));
    const start = staticPosition + offset;
    const startOfData = start + sizeOfLength;
    cursor.setPosition(start);
    const length2 = bytesToNumber(cursor.readBytes(sizeOfLength));
    const dynamicChild = hasDynamicChild(param);
    let consumed2 = 0;
    const value2 = [];
    for (let i = 0; i < length2; ++i) {
      cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed2));
      const [data, consumed_] = decodeParameter(cursor, param, {
        staticPosition: startOfData
      });
      consumed2 += consumed_;
      value2.push(data);
    }
    cursor.setPosition(staticPosition + 32);
    return [value2, 32];
  }
  if (hasDynamicChild(param)) {
    const offset = bytesToNumber(cursor.readBytes(sizeOfOffset));
    const start = staticPosition + offset;
    const value2 = [];
    for (let i = 0; i < length; ++i) {
      cursor.setPosition(start + i * 32);
      const [data] = decodeParameter(cursor, param, {
        staticPosition: start
      });
      value2.push(data);
    }
    cursor.setPosition(staticPosition + 32);
    return [value2, 32];
  }
  let consumed = 0;
  const value = [];
  for (let i = 0; i < length; ++i) {
    const [data, consumed_] = decodeParameter(cursor, param, {
      staticPosition: staticPosition + consumed
    });
    consumed += consumed_;
    value.push(data);
  }
  return [value, consumed];
}
function decodeBool(cursor) {
  return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32];
}
function decodeBytes(cursor, param, { staticPosition }) {
  const [_, size5] = param.type.split("bytes");
  if (!size5) {
    const offset = bytesToNumber(cursor.readBytes(32));
    cursor.setPosition(staticPosition + offset);
    const length = bytesToNumber(cursor.readBytes(32));
    if (length === 0) {
      cursor.setPosition(staticPosition + 32);
      return ["0x", 32];
    }
    const data = cursor.readBytes(length);
    cursor.setPosition(staticPosition + 32);
    return [bytesToHex(data), 32];
  }
  const value = bytesToHex(cursor.readBytes(Number.parseInt(size5, 10), 32));
  return [value, 32];
}
function decodeNumber(cursor, param) {
  const signed = param.type.startsWith("int");
  const size5 = Number.parseInt(param.type.split("int")[1] || "256", 10);
  const value = cursor.readBytes(32);
  return [
    size5 > 48 ? bytesToBigInt(value, { signed }) : bytesToNumber(value, { signed }),
    32
  ];
}
function decodeTuple(cursor, param, { staticPosition }) {
  const hasUnnamedChild = param.components.length === 0 || param.components.some(({ name }) => !name);
  const value = hasUnnamedChild ? [] : {};
  let consumed = 0;
  if (hasDynamicChild(param)) {
    const offset = bytesToNumber(cursor.readBytes(sizeOfOffset));
    const start = staticPosition + offset;
    for (let i = 0; i < param.components.length; ++i) {
      const component = param.components[i];
      cursor.setPosition(start + consumed);
      const [data, consumed_] = decodeParameter(cursor, component, {
        staticPosition: start
      });
      consumed += consumed_;
      value[hasUnnamedChild ? i : component?.name] = data;
    }
    cursor.setPosition(staticPosition + 32);
    return [value, 32];
  }
  for (let i = 0; i < param.components.length; ++i) {
    const component = param.components[i];
    const [data, consumed_] = decodeParameter(cursor, component, {
      staticPosition
    });
    value[hasUnnamedChild ? i : component?.name] = data;
    consumed += consumed_;
  }
  return [value, consumed];
}
function decodeString(cursor, { staticPosition }) {
  const offset = bytesToNumber(cursor.readBytes(32));
  const start = staticPosition + offset;
  cursor.setPosition(start);
  const length = bytesToNumber(cursor.readBytes(32));
  if (length === 0) {
    cursor.setPosition(staticPosition + 32);
    return ["", 32];
  }
  const data = cursor.readBytes(length, 32);
  const value = bytesToString(trim(data));
  cursor.setPosition(staticPosition + 32);
  return [value, 32];
}
function hasDynamicChild(param) {
  const { type } = param;
  if (type === "string")
    return true;
  if (type === "bytes")
    return true;
  if (type.endsWith("[]"))
    return true;
  if (type === "tuple")
    return param.components?.some(hasDynamicChild);
  const arrayComponents = getArrayComponents(param.type);
  if (arrayComponents && hasDynamicChild({ ...param, type: arrayComponents[1] }))
    return true;
  return false;
}
var sizeOfLength, sizeOfOffset;
var init_decodeAbiParameters = __esm({
  "node_modules/viem/_esm/utils/abi/decodeAbiParameters.js"() {
    "use strict";
    init_abi();
    init_getAddress();
    init_cursor2();
    init_size();
    init_slice();
    init_trim();
    init_fromBytes();
    init_toBytes();
    init_toHex();
    init_encodeAbiParameters();
    sizeOfLength = 32;
    sizeOfOffset = 32;
  }
});

// node_modules/viem/_esm/utils/abi/decodeErrorResult.js
function decodeErrorResult(parameters) {
  const { abi: abi2, data, cause } = parameters;
  const signature2 = slice(data, 0, 4);
  if (signature2 === "0x")
    throw new AbiDecodingZeroDataError({ cause });
  const abi_ = [...abi2 || [], solidityError, solidityPanic];
  const abiItem = abi_.find((x) => x.type === "error" && signature2 === toFunctionSelector(formatAbiItem2(x)));
  if (!abiItem)
    throw new AbiErrorSignatureNotFoundError(signature2, {
      docsPath: "/docs/contract/decodeErrorResult",
      cause
    });
  return {
    abiItem,
    args: "inputs" in abiItem && abiItem.inputs && abiItem.inputs.length > 0 ? decodeAbiParameters(abiItem.inputs, slice(data, 4)) : void 0,
    errorName: abiItem.name
  };
}
var init_decodeErrorResult = __esm({
  "node_modules/viem/_esm/utils/abi/decodeErrorResult.js"() {
    "use strict";
    init_solidity();
    init_abi();
    init_slice();
    init_toFunctionSelector();
    init_decodeAbiParameters();
    init_formatAbiItem2();
  }
});

// node_modules/viem/_esm/utils/stringify.js
var stringify;
var init_stringify = __esm({
  "node_modules/viem/_esm/utils/stringify.js"() {
    "use strict";
    stringify = (value, replacer, space) => JSON.stringify(value, (key, value_) => {
      const value2 = typeof value_ === "bigint" ? value_.toString() : value_;
      return typeof replacer === "function" ? replacer(key, value2) : value2;
    }, space);
  }
});

// node_modules/viem/_esm/utils/abi/formatAbiItemWithArgs.js
function formatAbiItemWithArgs({ abiItem, args, includeFunctionName = true, includeName = false }) {
  if (!("name" in abiItem))
    return;
  if (!("inputs" in abiItem))
    return;
  if (!abiItem.inputs)
    return;
  return `${includeFunctionName ? abiItem.name : ""}(${abiItem.inputs.map((input, i) => `${includeName && input.name ? `${input.name}: ` : ""}${typeof args[i] === "object" ? stringify(args[i]) : args[i]}`).join(", ")})`;
}
var init_formatAbiItemWithArgs = __esm({
  "node_modules/viem/_esm/utils/abi/formatAbiItemWithArgs.js"() {
    "use strict";
    init_stringify();
  }
});

// node_modules/viem/_esm/constants/unit.js
var etherUnits, gweiUnits;
var init_unit = __esm({
  "node_modules/viem/_esm/constants/unit.js"() {
    "use strict";
    etherUnits = {
      gwei: 9,
      wei: 18
    };
    gweiUnits = {
      ether: -9,
      wei: 9
    };
  }
});

// node_modules/viem/_esm/utils/unit/formatUnits.js
function formatUnits(value, decimals) {
  let display = value.toString();
  const negative = display.startsWith("-");
  if (negative)
    display = display.slice(1);
  display = display.padStart(decimals, "0");
  let [integer, fraction] = [
    display.slice(0, display.length - decimals),
    display.slice(display.length - decimals)
  ];
  fraction = fraction.replace(/(0+)$/, "");
  return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`;
}
var init_formatUnits = __esm({
  "node_modules/viem/_esm/utils/unit/formatUnits.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/utils/unit/formatEther.js
function formatEther(wei, unit = "wei") {
  return formatUnits(wei, etherUnits[unit]);
}
var init_formatEther = __esm({
  "node_modules/viem/_esm/utils/unit/formatEther.js"() {
    "use strict";
    init_unit();
    init_formatUnits();
  }
});

// node_modules/viem/_esm/utils/unit/formatGwei.js
function formatGwei(wei, unit = "wei") {
  return formatUnits(wei, gweiUnits[unit]);
}
var init_formatGwei = __esm({
  "node_modules/viem/_esm/utils/unit/formatGwei.js"() {
    "use strict";
    init_unit();
    init_formatUnits();
  }
});

// node_modules/viem/_esm/errors/stateOverride.js
function prettyStateMapping(stateMapping) {
  return stateMapping.reduce((pretty, { slot, value }) => {
    return `${pretty}        ${slot}: ${value}
`;
  }, "");
}
function prettyStateOverride(stateOverride) {
  return stateOverride.reduce((pretty, { address: address2, ...state }) => {
    let val = `${pretty}    ${address2}:
`;
    if (state.nonce)
      val += `      nonce: ${state.nonce}
`;
    if (state.balance)
      val += `      balance: ${state.balance}
`;
    if (state.code)
      val += `      code: ${state.code}
`;
    if (state.state) {
      val += "      state:\n";
      val += prettyStateMapping(state.state);
    }
    if (state.stateDiff) {
      val += "      stateDiff:\n";
      val += prettyStateMapping(state.stateDiff);
    }
    return val;
  }, "  State Override:\n").slice(0, -1);
}
var AccountStateConflictError, StateAssignmentConflictError;
var init_stateOverride = __esm({
  "node_modules/viem/_esm/errors/stateOverride.js"() {
    "use strict";
    init_base();
    AccountStateConflictError = class extends BaseError2 {
      constructor({ address: address2 }) {
        super(`State for account "${address2}" is set multiple times.`, {
          name: "AccountStateConflictError"
        });
      }
    };
    StateAssignmentConflictError = class extends BaseError2 {
      constructor() {
        super("state and stateDiff are set on the same account.", {
          name: "StateAssignmentConflictError"
        });
      }
    };
  }
});

// node_modules/viem/_esm/errors/transaction.js
function prettyPrint(args) {
  const entries = Object.entries(args).map(([key, value]) => {
    if (value === void 0 || value === false)
      return null;
    return [key, value];
  }).filter(Boolean);
  const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0);
  return entries.map(([key, value]) => `  ${`${key}:`.padEnd(maxLength + 1)}  ${value}`).join("\n");
}
var InvalidLegacyVError, InvalidSerializableTransactionError, InvalidStorageKeySizeError, TransactionExecutionError, TransactionNotFoundError, TransactionReceiptNotFoundError, TransactionReceiptRevertedError, WaitForTransactionReceiptTimeoutError;
var init_transaction = __esm({
  "node_modules/viem/_esm/errors/transaction.js"() {
    "use strict";
    init_formatEther();
    init_formatGwei();
    init_base();
    InvalidLegacyVError = class extends BaseError2 {
      constructor({ v }) {
        super(`Invalid \`v\` value "${v}". Expected 27 or 28.`, {
          name: "InvalidLegacyVError"
        });
      }
    };
    InvalidSerializableTransactionError = class extends BaseError2 {
      constructor({ transaction }) {
        super("Cannot infer a transaction type from provided transaction.", {
          metaMessages: [
            "Provided Transaction:",
            "{",
            prettyPrint(transaction),
            "}",
            "",
            "To infer the type, either provide:",
            "- a `type` to the Transaction, or",
            "- an EIP-1559 Transaction with `maxFeePerGas`, or",
            "- an EIP-2930 Transaction with `gasPrice` & `accessList`, or",
            "- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or",
            "- an EIP-7702 Transaction with `authorizationList`, or",
            "- a Legacy Transaction with `gasPrice`"
          ],
          name: "InvalidSerializableTransactionError"
        });
      }
    };
    InvalidStorageKeySizeError = class extends BaseError2 {
      constructor({ storageKey }) {
        super(`Size for storage key "${storageKey}" is invalid. Expected 32 bytes. Got ${Math.floor((storageKey.length - 2) / 2)} bytes.`, { name: "InvalidStorageKeySizeError" });
      }
    };
    TransactionExecutionError = class extends BaseError2 {
      constructor(cause, { account, docsPath: docsPath8, chain: chain3, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value }) {
        const prettyArgs = prettyPrint({
          chain: chain3 && `${chain3?.name} (id: ${chain3?.id})`,
          from: account?.address,
          to,
          value: typeof value !== "undefined" && `${formatEther(value)} ${chain3?.nativeCurrency?.symbol || "ETH"}`,
          data,
          gas,
          gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
          maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
          maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
          nonce
        });
        super(cause.shortMessage, {
          cause,
          docsPath: docsPath8,
          metaMessages: [
            ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
            "Request Arguments:",
            prettyArgs
          ].filter(Boolean),
          name: "TransactionExecutionError"
        });
        Object.defineProperty(this, "cause", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.cause = cause;
      }
    };
    TransactionNotFoundError = class extends BaseError2 {
      constructor({ blockHash, blockNumber, blockTag, hash: hash3, index: index2 }) {
        let identifier = "Transaction";
        if (blockTag && index2 !== void 0)
          identifier = `Transaction at block time "${blockTag}" at index "${index2}"`;
        if (blockHash && index2 !== void 0)
          identifier = `Transaction at block hash "${blockHash}" at index "${index2}"`;
        if (blockNumber && index2 !== void 0)
          identifier = `Transaction at block number "${blockNumber}" at index "${index2}"`;
        if (hash3)
          identifier = `Transaction with hash "${hash3}"`;
        super(`${identifier} could not be found.`, {
          name: "TransactionNotFoundError"
        });
      }
    };
    TransactionReceiptNotFoundError = class extends BaseError2 {
      constructor({ hash: hash3 }) {
        super(`Transaction receipt with hash "${hash3}" could not be found. The Transaction may not be processed on a block yet.`, {
          name: "TransactionReceiptNotFoundError"
        });
      }
    };
    TransactionReceiptRevertedError = class extends BaseError2 {
      constructor({ receipt }) {
        super(`Transaction with hash "${receipt.transactionHash}" reverted.`, {
          metaMessages: [
            'The receipt marked the transaction as "reverted". This could mean that the function on the contract you are trying to call threw an error.',
            " ",
            "You can attempt to extract the revert reason by:",
            "- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract",
            "- using the `call` Action with raw `data`"
          ],
          name: "TransactionReceiptRevertedError"
        });
        Object.defineProperty(this, "receipt", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.receipt = receipt;
      }
    };
    WaitForTransactionReceiptTimeoutError = class extends BaseError2 {
      constructor({ hash: hash3 }) {
        super(`Timed out while waiting for transaction with hash "${hash3}" to be confirmed.`, { name: "WaitForTransactionReceiptTimeoutError" });
      }
    };
  }
});

// node_modules/viem/_esm/errors/utils.js
var getContractAddress, getUrl;
var init_utils3 = __esm({
  "node_modules/viem/_esm/errors/utils.js"() {
    "use strict";
    getContractAddress = (address2) => address2;
    getUrl = (url) => {
      try {
        const parsed = new URL(url);
        if (!parsed.username && !parsed.password)
          return url;
        parsed.username = "";
        parsed.password = "";
        return parsed.toString();
      } catch {
        return url;
      }
    };
  }
});

// node_modules/viem/_esm/errors/contract.js
var CallExecutionError, ContractFunctionExecutionError, ContractFunctionRevertedError, ContractFunctionZeroDataError, CounterfactualDeploymentFailedError, RawContractError;
var init_contract = __esm({
  "node_modules/viem/_esm/errors/contract.js"() {
    "use strict";
    init_parseAccount();
    init_solidity();
    init_decodeErrorResult();
    init_formatAbiItem2();
    init_formatAbiItemWithArgs();
    init_getAbiItem();
    init_formatEther();
    init_formatGwei();
    init_abi();
    init_base();
    init_stateOverride();
    init_transaction();
    init_utils3();
    CallExecutionError = class extends BaseError2 {
      constructor(cause, { account: account_, docsPath: docsPath8, chain: chain3, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value, stateOverride }) {
        const account = account_ ? parseAccount(account_) : void 0;
        let prettyArgs = prettyPrint({
          from: account?.address,
          to,
          value: typeof value !== "undefined" && `${formatEther(value)} ${chain3?.nativeCurrency?.symbol || "ETH"}`,
          data,
          gas,
          gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
          maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
          maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
          nonce
        });
        if (stateOverride) {
          prettyArgs += `
${prettyStateOverride(stateOverride)}`;
        }
        super(cause.shortMessage, {
          cause,
          docsPath: docsPath8,
          metaMessages: [
            ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
            "Raw Call Arguments:",
            prettyArgs
          ].filter(Boolean),
          name: "CallExecutionError"
        });
        Object.defineProperty(this, "cause", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.cause = cause;
      }
    };
    ContractFunctionExecutionError = class extends BaseError2 {
      constructor(cause, { abi: abi2, args, contractAddress, docsPath: docsPath8, functionName, sender }) {
        const abiItem = getAbiItem({ abi: abi2, args, name: functionName });
        const formattedArgs = abiItem ? formatAbiItemWithArgs({
          abiItem,
          args,
          includeFunctionName: false,
          includeName: false
        }) : void 0;
        const functionWithParams = abiItem ? formatAbiItem2(abiItem, { includeName: true }) : void 0;
        const prettyArgs = prettyPrint({
          address: contractAddress && getContractAddress(contractAddress),
          function: functionWithParams,
          args: formattedArgs && formattedArgs !== "()" && `${[...Array(functionName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}`,
          sender
        });
        super(cause.shortMessage || `An unknown error occurred while executing the contract function "${functionName}".`, {
          cause,
          docsPath: docsPath8,
          metaMessages: [
            ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
            prettyArgs && "Contract Call:",
            prettyArgs
          ].filter(Boolean),
          name: "ContractFunctionExecutionError"
        });
        Object.defineProperty(this, "abi", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "args", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "cause", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "contractAddress", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "formattedArgs", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "functionName", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "sender", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.abi = abi2;
        this.args = args;
        this.cause = cause;
        this.contractAddress = contractAddress;
        this.functionName = functionName;
        this.sender = sender;
      }
    };
    ContractFunctionRevertedError = class extends BaseError2 {
      constructor({ abi: abi2, data, functionName, message, cause: error }) {
        let cause;
        let decodedData;
        let metaMessages;
        let reason;
        if (data && data !== "0x") {
          try {
            decodedData = decodeErrorResult({ abi: abi2, data, cause: error });
            const { abiItem, errorName, args: errorArgs } = decodedData;
            if (errorName === "Error") {
              reason = errorArgs[0];
            } else if (errorName === "Panic") {
              const [firstArg] = errorArgs;
              reason = panicReasons[firstArg];
            } else {
              const errorWithParams = abiItem ? formatAbiItem2(abiItem, { includeName: true }) : void 0;
              const formattedArgs = abiItem && errorArgs ? formatAbiItemWithArgs({
                abiItem,
                args: errorArgs,
                includeFunctionName: false,
                includeName: false
              }) : void 0;
              metaMessages = [
                errorWithParams ? `Error: ${errorWithParams}` : "",
                formattedArgs && formattedArgs !== "()" ? `       ${[...Array(errorName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}` : ""
              ];
            }
          } catch (err) {
            cause = err;
          }
        } else if (message)
          reason = message;
        let signature2;
        if (cause instanceof AbiErrorSignatureNotFoundError) {
          signature2 = cause.signature;
          metaMessages = [
            `Unable to decode signature "${signature2}" as it was not found on the provided ABI.`,
            "Make sure you are using the correct ABI and that the error exists on it.",
            `You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${signature2}.`
          ];
        }
        super(reason && reason !== "execution reverted" || signature2 ? [
          `The contract function "${functionName}" reverted with the following ${signature2 ? "signature" : "reason"}:`,
          reason || signature2
        ].join("\n") : `The contract function "${functionName}" reverted.`, {
          cause: cause ?? error,
          metaMessages,
          name: "ContractFunctionRevertedError"
        });
        Object.defineProperty(this, "data", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "raw", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "reason", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "signature", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.data = decodedData;
        this.raw = data;
        this.reason = reason;
        this.signature = signature2;
      }
    };
    ContractFunctionZeroDataError = class extends BaseError2 {
      constructor({ functionName, cause }) {
        super(`The contract function "${functionName}" returned no data ("0x").`, {
          metaMessages: [
            "This could be due to any of the following:",
            `  - The contract does not have the function "${functionName}",`,
            "  - The parameters passed to the contract function may be invalid, or",
            "  - The address is not a contract."
          ],
          name: "ContractFunctionZeroDataError",
          cause
        });
      }
    };
    CounterfactualDeploymentFailedError = class extends BaseError2 {
      constructor({ factory }) {
        super(`Deployment for counterfactual contract call failed${factory ? ` for factory "${factory}".` : ""}`, {
          metaMessages: [
            "Please ensure:",
            "- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).",
            "- The `factoryData` is a valid encoded function call for contract deployment function on the factory."
          ],
          name: "CounterfactualDeploymentFailedError"
        });
      }
    };
    RawContractError = class extends BaseError2 {
      constructor({ data, message }) {
        super(message || "", { name: "RawContractError" });
        Object.defineProperty(this, "code", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: 3
        });
        Object.defineProperty(this, "data", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.data = data;
      }
    };
  }
});

// node_modules/viem/_esm/errors/request.js
var HttpRequestError, RpcRequestError, TimeoutError;
var init_request = __esm({
  "node_modules/viem/_esm/errors/request.js"() {
    "use strict";
    init_stringify();
    init_base();
    init_utils3();
    HttpRequestError = class extends BaseError2 {
      constructor({ body, cause, details, headers, status, url }) {
        super("HTTP request failed.", {
          cause,
          details,
          metaMessages: [
            status && `Status: ${status}`,
            `URL: ${getUrl(url)}`,
            body && `Request body: ${stringify(body)}`
          ].filter(Boolean),
          name: "HttpRequestError"
        });
        Object.defineProperty(this, "body", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "headers", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "status", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "url", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.body = body;
        this.headers = headers;
        this.status = status;
        this.url = url;
      }
    };
    RpcRequestError = class extends BaseError2 {
      constructor({ body, error, url }) {
        super("RPC Request failed.", {
          cause: error,
          details: error.message,
          metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`],
          name: "RpcRequestError"
        });
        Object.defineProperty(this, "code", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "data", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "url", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.code = error.code;
        this.data = error.data;
        this.url = url;
      }
    };
    TimeoutError = class extends BaseError2 {
      constructor({ body, url }) {
        super("The request took too long to respond.", {
          details: "The request timed out.",
          metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`],
          name: "TimeoutError"
        });
        Object.defineProperty(this, "url", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.url = url;
      }
    };
  }
});

// node_modules/viem/_esm/errors/rpc.js
var unknownErrorCode, RpcError, ProviderRpcError, ParseRpcError, InvalidRequestRpcError, MethodNotFoundRpcError, InvalidParamsRpcError, InternalRpcError, InvalidInputRpcError, ResourceNotFoundRpcError, ResourceUnavailableRpcError, TransactionRejectedRpcError, MethodNotSupportedRpcError, LimitExceededRpcError, JsonRpcVersionUnsupportedError, UserRejectedRequestError, UnauthorizedProviderError, UnsupportedProviderMethodError, ProviderDisconnectedError, ChainDisconnectedError, SwitchChainError, UnsupportedNonOptionalCapabilityError, UnsupportedChainIdError, DuplicateIdError, UnknownBundleIdError, BundleTooLargeError, AtomicReadyWalletRejectedUpgradeError, AtomicityNotSupportedError, WalletConnectSessionSettlementError, UnknownRpcError;
var init_rpc = __esm({
  "node_modules/viem/_esm/errors/rpc.js"() {
    "use strict";
    init_base();
    init_request();
    unknownErrorCode = -1;
    RpcError = class extends BaseError2 {
      constructor(cause, { code, docsPath: docsPath8, metaMessages, name, shortMessage }) {
        super(shortMessage, {
          cause,
          docsPath: docsPath8,
          metaMessages: metaMessages || cause?.metaMessages,
          name: name || "RpcError"
        });
        Object.defineProperty(this, "code", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.name = name || cause.name;
        this.code = cause instanceof RpcRequestError ? cause.code : code ?? unknownErrorCode;
      }
    };
    ProviderRpcError = class extends RpcError {
      constructor(cause, options) {
        super(cause, options);
        Object.defineProperty(this, "data", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.data = options.data;
      }
    };
    ParseRpcError = class _ParseRpcError extends RpcError {
      constructor(cause) {
        super(cause, {
          code: _ParseRpcError.code,
          name: "ParseRpcError",
          shortMessage: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."
        });
      }
    };
    Object.defineProperty(ParseRpcError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: -32700
    });
    InvalidRequestRpcError = class _InvalidRequestRpcError extends RpcError {
      constructor(cause) {
        super(cause, {
          code: _InvalidRequestRpcError.code,
          name: "InvalidRequestRpcError",
          shortMessage: "JSON is not a valid request object."
        });
      }
    };
    Object.defineProperty(InvalidRequestRpcError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: -32600
    });
    MethodNotFoundRpcError = class _MethodNotFoundRpcError extends RpcError {
      constructor(cause, { method } = {}) {
        super(cause, {
          code: _MethodNotFoundRpcError.code,
          name: "MethodNotFoundRpcError",
          shortMessage: `The method${method ? ` "${method}"` : ""} does not exist / is not available.`
        });
      }
    };
    Object.defineProperty(MethodNotFoundRpcError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: -32601
    });
    InvalidParamsRpcError = class _InvalidParamsRpcError extends RpcError {
      constructor(cause) {
        super(cause, {
          code: _InvalidParamsRpcError.code,
          name: "InvalidParamsRpcError",
          shortMessage: [
            "Invalid parameters were provided to the RPC method.",
            "Double check you have provided the correct parameters."
          ].join("\n")
        });
      }
    };
    Object.defineProperty(InvalidParamsRpcError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: -32602
    });
    InternalRpcError = class _InternalRpcError extends RpcError {
      constructor(cause) {
        super(cause, {
          code: _InternalRpcError.code,
          name: "InternalRpcError",
          shortMessage: "An internal error was received."
        });
      }
    };
    Object.defineProperty(InternalRpcError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: -32603
    });
    InvalidInputRpcError = class _InvalidInputRpcError extends RpcError {
      constructor(cause) {
        super(cause, {
          code: _InvalidInputRpcError.code,
          name: "InvalidInputRpcError",
          shortMessage: [
            "Missing or invalid parameters.",
            "Double check you have provided the correct parameters."
          ].join("\n")
        });
      }
    };
    Object.defineProperty(InvalidInputRpcError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: -32e3
    });
    ResourceNotFoundRpcError = class _ResourceNotFoundRpcError extends RpcError {
      constructor(cause) {
        super(cause, {
          code: _ResourceNotFoundRpcError.code,
          name: "ResourceNotFoundRpcError",
          shortMessage: "Requested resource not found."
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "ResourceNotFoundRpcError"
        });
      }
    };
    Object.defineProperty(ResourceNotFoundRpcError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: -32001
    });
    ResourceUnavailableRpcError = class _ResourceUnavailableRpcError extends RpcError {
      constructor(cause) {
        super(cause, {
          code: _ResourceUnavailableRpcError.code,
          name: "ResourceUnavailableRpcError",
          shortMessage: "Requested resource not available."
        });
      }
    };
    Object.defineProperty(ResourceUnavailableRpcError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: -32002
    });
    TransactionRejectedRpcError = class _TransactionRejectedRpcError extends RpcError {
      constructor(cause) {
        super(cause, {
          code: _TransactionRejectedRpcError.code,
          name: "TransactionRejectedRpcError",
          shortMessage: "Transaction creation failed."
        });
      }
    };
    Object.defineProperty(TransactionRejectedRpcError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: -32003
    });
    MethodNotSupportedRpcError = class _MethodNotSupportedRpcError extends RpcError {
      constructor(cause, { method } = {}) {
        super(cause, {
          code: _MethodNotSupportedRpcError.code,
          name: "MethodNotSupportedRpcError",
          shortMessage: `Method${method ? ` "${method}"` : ""} is not supported.`
        });
      }
    };
    Object.defineProperty(MethodNotSupportedRpcError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: -32004
    });
    LimitExceededRpcError = class _LimitExceededRpcError extends RpcError {
      constructor(cause) {
        super(cause, {
          code: _LimitExceededRpcError.code,
          name: "LimitExceededRpcError",
          shortMessage: "Request exceeds defined limit."
        });
      }
    };
    Object.defineProperty(LimitExceededRpcError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: -32005
    });
    JsonRpcVersionUnsupportedError = class _JsonRpcVersionUnsupportedError extends RpcError {
      constructor(cause) {
        super(cause, {
          code: _JsonRpcVersionUnsupportedError.code,
          name: "JsonRpcVersionUnsupportedError",
          shortMessage: "Version of JSON-RPC protocol is not supported."
        });
      }
    };
    Object.defineProperty(JsonRpcVersionUnsupportedError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: -32006
    });
    UserRejectedRequestError = class _UserRejectedRequestError extends ProviderRpcError {
      constructor(cause) {
        super(cause, {
          code: _UserRejectedRequestError.code,
          name: "UserRejectedRequestError",
          shortMessage: "User rejected the request."
        });
      }
    };
    Object.defineProperty(UserRejectedRequestError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 4001
    });
    UnauthorizedProviderError = class _UnauthorizedProviderError extends ProviderRpcError {
      constructor(cause) {
        super(cause, {
          code: _UnauthorizedProviderError.code,
          name: "UnauthorizedProviderError",
          shortMessage: "The requested method and/or account has not been authorized by the user."
        });
      }
    };
    Object.defineProperty(UnauthorizedProviderError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 4100
    });
    UnsupportedProviderMethodError = class _UnsupportedProviderMethodError extends ProviderRpcError {
      constructor(cause, { method } = {}) {
        super(cause, {
          code: _UnsupportedProviderMethodError.code,
          name: "UnsupportedProviderMethodError",
          shortMessage: `The Provider does not support the requested method${method ? ` " ${method}"` : ""}.`
        });
      }
    };
    Object.defineProperty(UnsupportedProviderMethodError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 4200
    });
    ProviderDisconnectedError = class _ProviderDisconnectedError extends ProviderRpcError {
      constructor(cause) {
        super(cause, {
          code: _ProviderDisconnectedError.code,
          name: "ProviderDisconnectedError",
          shortMessage: "The Provider is disconnected from all chains."
        });
      }
    };
    Object.defineProperty(ProviderDisconnectedError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 4900
    });
    ChainDisconnectedError = class _ChainDisconnectedError extends ProviderRpcError {
      constructor(cause) {
        super(cause, {
          code: _ChainDisconnectedError.code,
          name: "ChainDisconnectedError",
          shortMessage: "The Provider is not connected to the requested chain."
        });
      }
    };
    Object.defineProperty(ChainDisconnectedError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 4901
    });
    SwitchChainError = class _SwitchChainError extends ProviderRpcError {
      constructor(cause) {
        super(cause, {
          code: _SwitchChainError.code,
          name: "SwitchChainError",
          shortMessage: "An error occurred when attempting to switch chain."
        });
      }
    };
    Object.defineProperty(SwitchChainError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 4902
    });
    UnsupportedNonOptionalCapabilityError = class _UnsupportedNonOptionalCapabilityError extends ProviderRpcError {
      constructor(cause) {
        super(cause, {
          code: _UnsupportedNonOptionalCapabilityError.code,
          name: "UnsupportedNonOptionalCapabilityError",
          shortMessage: "This Wallet does not support a capability that was not marked as optional."
        });
      }
    };
    Object.defineProperty(UnsupportedNonOptionalCapabilityError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 5700
    });
    UnsupportedChainIdError = class _UnsupportedChainIdError extends ProviderRpcError {
      constructor(cause) {
        super(cause, {
          code: _UnsupportedChainIdError.code,
          name: "UnsupportedChainIdError",
          shortMessage: "This Wallet does not support the requested chain ID."
        });
      }
    };
    Object.defineProperty(UnsupportedChainIdError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 5710
    });
    DuplicateIdError = class _DuplicateIdError extends ProviderRpcError {
      constructor(cause) {
        super(cause, {
          code: _DuplicateIdError.code,
          name: "DuplicateIdError",
          shortMessage: "There is already a bundle submitted with this ID."
        });
      }
    };
    Object.defineProperty(DuplicateIdError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 5720
    });
    UnknownBundleIdError = class _UnknownBundleIdError extends ProviderRpcError {
      constructor(cause) {
        super(cause, {
          code: _UnknownBundleIdError.code,
          name: "UnknownBundleIdError",
          shortMessage: "This bundle id is unknown / has not been submitted"
        });
      }
    };
    Object.defineProperty(UnknownBundleIdError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 5730
    });
    BundleTooLargeError = class _BundleTooLargeError extends ProviderRpcError {
      constructor(cause) {
        super(cause, {
          code: _BundleTooLargeError.code,
          name: "BundleTooLargeError",
          shortMessage: "The call bundle is too large for the Wallet to process."
        });
      }
    };
    Object.defineProperty(BundleTooLargeError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 5740
    });
    AtomicReadyWalletRejectedUpgradeError = class _AtomicReadyWalletRejectedUpgradeError extends ProviderRpcError {
      constructor(cause) {
        super(cause, {
          code: _AtomicReadyWalletRejectedUpgradeError.code,
          name: "AtomicReadyWalletRejectedUpgradeError",
          shortMessage: "The Wallet can support atomicity after an upgrade, but the user rejected the upgrade."
        });
      }
    };
    Object.defineProperty(AtomicReadyWalletRejectedUpgradeError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 5750
    });
    AtomicityNotSupportedError = class _AtomicityNotSupportedError extends ProviderRpcError {
      constructor(cause) {
        super(cause, {
          code: _AtomicityNotSupportedError.code,
          name: "AtomicityNotSupportedError",
          shortMessage: "The wallet does not support atomic execution but the request requires it."
        });
      }
    };
    Object.defineProperty(AtomicityNotSupportedError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 5760
    });
    WalletConnectSessionSettlementError = class _WalletConnectSessionSettlementError extends ProviderRpcError {
      constructor(cause) {
        super(cause, {
          code: _WalletConnectSessionSettlementError.code,
          name: "WalletConnectSessionSettlementError",
          shortMessage: "WalletConnect session settlement failed."
        });
      }
    };
    Object.defineProperty(WalletConnectSessionSettlementError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 7e3
    });
    UnknownRpcError = class extends RpcError {
      constructor(cause) {
        super(cause, {
          name: "UnknownRpcError",
          shortMessage: "An unknown RPC error occurred."
        });
      }
    };
  }
});

// node_modules/viem/_esm/utils/errors/getContractError.js
function getContractError(err, { abi: abi2, address: address2, args, docsPath: docsPath8, functionName, sender }) {
  const error = err instanceof RawContractError ? err : err instanceof BaseError2 ? err.walk((err2) => "data" in err2) || err.walk() : {};
  const { code, data, details, message, shortMessage } = error;
  const cause = (() => {
    if (err instanceof AbiDecodingZeroDataError)
      return new ContractFunctionZeroDataError({ functionName, cause: err });
    if ([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) && (data || details || message || shortMessage) || code === InvalidInputRpcError.code && details === "execution reverted" && data) {
      return new ContractFunctionRevertedError({
        abi: abi2,
        data: typeof data === "object" ? data.data : data,
        functionName,
        message: error instanceof RpcRequestError ? details : shortMessage ?? message,
        cause: err
      });
    }
    return err;
  })();
  return new ContractFunctionExecutionError(cause, {
    abi: abi2,
    args,
    contractAddress: address2,
    docsPath: docsPath8,
    functionName,
    sender
  });
}
var EXECUTION_REVERTED_ERROR_CODE;
var init_getContractError = __esm({
  "node_modules/viem/_esm/utils/errors/getContractError.js"() {
    "use strict";
    init_abi();
    init_base();
    init_contract();
    init_request();
    init_rpc();
    EXECUTION_REVERTED_ERROR_CODE = 3;
  }
});

// node_modules/viem/_esm/accounts/utils/publicKeyToAddress.js
function publicKeyToAddress(publicKey) {
  const address2 = keccak256(`0x${publicKey.substring(4)}`).substring(26);
  return checksumAddress(`0x${address2}`);
}
var init_publicKeyToAddress = __esm({
  "node_modules/viem/_esm/accounts/utils/publicKeyToAddress.js"() {
    "use strict";
    init_getAddress();
    init_keccak256();
  }
});

// node_modules/viem/node_modules/@noble/hashes/esm/_md.js
function setBigUint64(view, byteOffset, value, isLE3) {
  if (typeof view.setBigUint64 === "function")
    return view.setBigUint64(byteOffset, value, isLE3);
  const _32n5 = BigInt(32);
  const _u32_max = BigInt(4294967295);
  const wh = Number(value >> _32n5 & _u32_max);
  const wl = Number(value & _u32_max);
  const h = isLE3 ? 4 : 0;
  const l2 = isLE3 ? 0 : 4;
  view.setUint32(byteOffset + h, wh, isLE3);
  view.setUint32(byteOffset + l2, wl, isLE3);
}
function Chi(a, b, c) {
  return a & b ^ ~a & c;
}
function Maj(a, b, c) {
  return a & b ^ a & c ^ b & c;
}
var HashMD, SHA256_IV;
var init_md = __esm({
  "node_modules/viem/node_modules/@noble/hashes/esm/_md.js"() {
    "use strict";
    init_utils2();
    HashMD = class extends Hash {
      constructor(blockLen, outputLen, padOffset, isLE3) {
        super();
        this.finished = false;
        this.length = 0;
        this.pos = 0;
        this.destroyed = false;
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE3;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView(this.buffer);
      }
      update(data) {
        aexists(this);
        data = toBytes2(data);
        abytes(data);
        const { view, buffer: buffer2, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len; ) {
          const take = Math.min(blockLen - this.pos, len - pos);
          if (take === blockLen) {
            const dataView = createView(data);
            for (; blockLen <= len - pos; pos += blockLen)
              this.process(dataView, pos);
            continue;
          }
          buffer2.set(data.subarray(pos, pos + take), this.pos);
          this.pos += take;
          pos += take;
          if (this.pos === blockLen) {
            this.process(view, 0);
            this.pos = 0;
          }
        }
        this.length += data.length;
        this.roundClean();
        return this;
      }
      digestInto(out) {
        aexists(this);
        aoutput(out, this);
        this.finished = true;
        const { buffer: buffer2, view, blockLen, isLE: isLE3 } = this;
        let { pos } = this;
        buffer2[pos++] = 128;
        clean(this.buffer.subarray(pos));
        if (this.padOffset > blockLen - pos) {
          this.process(view, 0);
          pos = 0;
        }
        for (let i = pos; i < blockLen; i++)
          buffer2[i] = 0;
        setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE3);
        this.process(view, 0);
        const oview = createView(out);
        const len = this.outputLen;
        if (len % 4)
          throw new Error("_sha2: outputLen should be aligned to 32bit");
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
          throw new Error("_sha2: outputLen bigger than state");
        for (let i = 0; i < outLen; i++)
          oview.setUint32(4 * i, state[i], isLE3);
      }
      digest() {
        const { buffer: buffer2, outputLen } = this;
        this.digestInto(buffer2);
        const res = buffer2.slice(0, outputLen);
        this.destroy();
        return res;
      }
      _cloneInto(to) {
        to || (to = new this.constructor());
        to.set(...this.get());
        const { blockLen, buffer: buffer2, length, finished: finished2, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished2;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
          to.buffer.set(buffer2);
        return to;
      }
      clone() {
        return this._cloneInto();
      }
    };
    SHA256_IV = /* @__PURE__ */ Uint32Array.from([
      1779033703,
      3144134277,
      1013904242,
      2773480762,
      1359893119,
      2600822924,
      528734635,
      1541459225
    ]);
  }
});

// node_modules/viem/node_modules/@noble/hashes/esm/sha2.js
var SHA256_K, SHA256_W, SHA256, sha256;
var init_sha2 = __esm({
  "node_modules/viem/node_modules/@noble/hashes/esm/sha2.js"() {
    "use strict";
    init_md();
    init_utils2();
    SHA256_K = /* @__PURE__ */ Uint32Array.from([
      1116352408,
      1899447441,
      3049323471,
      3921009573,
      961987163,
      1508970993,
      2453635748,
      2870763221,
      3624381080,
      310598401,
      607225278,
      1426881987,
      1925078388,
      2162078206,
      2614888103,
      3248222580,
      3835390401,
      4022224774,
      264347078,
      604807628,
      770255983,
      1249150122,
      1555081692,
      1996064986,
      2554220882,
      2821834349,
      2952996808,
      3210313671,
      3336571891,
      3584528711,
      113926993,
      338241895,
      666307205,
      773529912,
      1294757372,
      1396182291,
      1695183700,
      1986661051,
      2177026350,
      2456956037,
      2730485921,
      2820302411,
      3259730800,
      3345764771,
      3516065817,
      3600352804,
      4094571909,
      275423344,
      430227734,
      506948616,
      659060556,
      883997877,
      958139571,
      1322822218,
      1537002063,
      1747873779,
      1955562222,
      2024104815,
      2227730452,
      2361852424,
      2428436474,
      2756734187,
      3204031479,
      3329325298
    ]);
    SHA256_W = /* @__PURE__ */ new Uint32Array(64);
    SHA256 = class extends HashMD {
      constructor(outputLen = 32) {
        super(64, outputLen, 8, false);
        this.A = SHA256_IV[0] | 0;
        this.B = SHA256_IV[1] | 0;
        this.C = SHA256_IV[2] | 0;
        this.D = SHA256_IV[3] | 0;
        this.E = SHA256_IV[4] | 0;
        this.F = SHA256_IV[5] | 0;
        this.G = SHA256_IV[6] | 0;
        this.H = SHA256_IV[7] | 0;
      }
      get() {
        const { A, B, C, D: D2, E, F, G, H } = this;
        return [A, B, C, D2, E, F, G, H];
      }
      // prettier-ignore
      set(A, B, C, D2, E, F, G, H) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D2 | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G | 0;
        this.H = H | 0;
      }
      process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
          SHA256_W[i] = view.getUint32(offset, false);
        for (let i = 16; i < 64; i++) {
          const W15 = SHA256_W[i - 15];
          const W2 = SHA256_W[i - 2];
          const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
          const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
          SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
        }
        let { A, B, C, D: D2, E, F, G, H } = this;
        for (let i = 0; i < 64; i++) {
          const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
          const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
          const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
          const T2 = sigma0 + Maj(A, B, C) | 0;
          H = G;
          G = F;
          F = E;
          E = D2 + T1 | 0;
          D2 = C;
          C = B;
          B = A;
          A = T1 + T2 | 0;
        }
        A = A + this.A | 0;
        B = B + this.B | 0;
        C = C + this.C | 0;
        D2 = D2 + this.D | 0;
        E = E + this.E | 0;
        F = F + this.F | 0;
        G = G + this.G | 0;
        H = H + this.H | 0;
        this.set(A, B, C, D2, E, F, G, H);
      }
      roundClean() {
        clean(SHA256_W);
      }
      destroy() {
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean(this.buffer);
      }
    };
    sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
  }
});

// node_modules/viem/node_modules/@noble/hashes/esm/hmac.js
var HMAC, hmac;
var init_hmac = __esm({
  "node_modules/viem/node_modules/@noble/hashes/esm/hmac.js"() {
    "use strict";
    init_utils2();
    HMAC = class extends Hash {
      constructor(hash3, _key) {
        super();
        this.finished = false;
        this.destroyed = false;
        ahash(hash3);
        const key = toBytes2(_key);
        this.iHash = hash3.create();
        if (typeof this.iHash.update !== "function")
          throw new Error("Expected instance of class which extends utils.Hash");
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad4 = new Uint8Array(blockLen);
        pad4.set(key.length > blockLen ? hash3.create().update(key).digest() : key);
        for (let i = 0; i < pad4.length; i++)
          pad4[i] ^= 54;
        this.iHash.update(pad4);
        this.oHash = hash3.create();
        for (let i = 0; i < pad4.length; i++)
          pad4[i] ^= 54 ^ 92;
        this.oHash.update(pad4);
        clean(pad4);
      }
      update(buf) {
        aexists(this);
        this.iHash.update(buf);
        return this;
      }
      digestInto(out) {
        aexists(this);
        abytes(out, this.outputLen);
        this.finished = true;
        this.iHash.digestInto(out);
        this.oHash.update(out);
        this.oHash.digestInto(out);
        this.destroy();
      }
      digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
      }
      _cloneInto(to) {
        to || (to = Object.create(Object.getPrototypeOf(this), {}));
        const { oHash, iHash, finished: finished2, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished2;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
      }
      clone() {
        return this._cloneInto();
      }
      destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
      }
    };
    hmac = (hash3, key, message) => new HMAC(hash3, key).update(message).digest();
    hmac.create = (hash3, key) => new HMAC(hash3, key);
  }
});

// node_modules/viem/node_modules/@noble/curves/esm/abstract/utils.js
function isBytes2(a) {
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
function abytes2(item) {
  if (!isBytes2(item))
    throw new Error("Uint8Array expected");
}
function abool(title, value) {
  if (typeof value !== "boolean")
    throw new Error(title + " boolean expected, got " + value);
}
function numberToHexUnpadded(num2) {
  const hex = num2.toString(16);
  return hex.length & 1 ? "0" + hex : hex;
}
function hexToNumber2(hex) {
  if (typeof hex !== "string")
    throw new Error("hex string expected, got " + typeof hex);
  return hex === "" ? _0n2 : BigInt("0x" + hex);
}
function bytesToHex2(bytes) {
  abytes2(bytes);
  if (hasHexBuiltin)
    return bytes.toHex();
  let hex = "";
  for (let i = 0; i < bytes.length; i++) {
    hex += hexes2[bytes[i]];
  }
  return hex;
}
function asciiToBase16(ch) {
  if (ch >= asciis._0 && ch <= asciis._9)
    return ch - asciis._0;
  if (ch >= asciis.A && ch <= asciis.F)
    return ch - (asciis.A - 10);
  if (ch >= asciis.a && ch <= asciis.f)
    return ch - (asciis.a - 10);
  return;
}
function hexToBytes2(hex) {
  if (typeof hex !== "string")
    throw new Error("hex string expected, got " + typeof hex);
  if (hasHexBuiltin)
    return Uint8Array.fromHex(hex);
  const hl = hex.length;
  const al = hl / 2;
  if (hl % 2)
    throw new Error("hex string expected, got unpadded hex of length " + hl);
  const array = new Uint8Array(al);
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
    const n1 = asciiToBase16(hex.charCodeAt(hi));
    const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
    if (n1 === void 0 || n2 === void 0) {
      const char = hex[hi] + hex[hi + 1];
      throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
    }
    array[ai] = n1 * 16 + n2;
  }
  return array;
}
function bytesToNumberBE(bytes) {
  return hexToNumber2(bytesToHex2(bytes));
}
function bytesToNumberLE(bytes) {
  abytes2(bytes);
  return hexToNumber2(bytesToHex2(Uint8Array.from(bytes).reverse()));
}
function numberToBytesBE(n, len) {
  return hexToBytes2(n.toString(16).padStart(len * 2, "0"));
}
function numberToBytesLE(n, len) {
  return numberToBytesBE(n, len).reverse();
}
function ensureBytes(title, hex, expectedLength) {
  let res;
  if (typeof hex === "string") {
    try {
      res = hexToBytes2(hex);
    } catch (e7) {
      throw new Error(title + " must be hex string or Uint8Array, cause: " + e7);
    }
  } else if (isBytes2(hex)) {
    res = Uint8Array.from(hex);
  } else {
    throw new Error(title + " must be hex string or Uint8Array");
  }
  const len = res.length;
  if (typeof expectedLength === "number" && len !== expectedLength)
    throw new Error(title + " of length " + expectedLength + " expected, got " + len);
  return res;
}
function concatBytes3(...arrays) {
  let sum = 0;
  for (let i = 0; i < arrays.length; i++) {
    const a = arrays[i];
    abytes2(a);
    sum += a.length;
  }
  const res = new Uint8Array(sum);
  for (let i = 0, pad4 = 0; i < arrays.length; i++) {
    const a = arrays[i];
    res.set(a, pad4);
    pad4 += a.length;
  }
  return res;
}
function utf8ToBytes2(str) {
  if (typeof str !== "string")
    throw new Error("string expected");
  return new Uint8Array(new TextEncoder().encode(str));
}
function inRange(n, min, max) {
  return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
function aInRange(title, n, min, max) {
  if (!inRange(n, min, max))
    throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
}
function bitLen(n) {
  let len;
  for (len = 0; n > _0n2; n >>= _1n2, len += 1)
    ;
  return len;
}
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
  if (typeof hashLen !== "number" || hashLen < 2)
    throw new Error("hashLen must be a number");
  if (typeof qByteLen !== "number" || qByteLen < 2)
    throw new Error("qByteLen must be a number");
  if (typeof hmacFn !== "function")
    throw new Error("hmacFn must be a function");
  let v = u8n(hashLen);
  let k = u8n(hashLen);
  let i = 0;
  const reset = () => {
    v.fill(1);
    k.fill(0);
    i = 0;
  };
  const h = (...b) => hmacFn(k, v, ...b);
  const reseed = (seed = u8n(0)) => {
    k = h(u8fr([0]), seed);
    v = h();
    if (seed.length === 0)
      return;
    k = h(u8fr([1]), seed);
    v = h();
  };
  const gen3 = () => {
    if (i++ >= 1e3)
      throw new Error("drbg: tried 1000 values");
    let len = 0;
    const out = [];
    while (len < qByteLen) {
      v = h();
      const sl = v.slice();
      out.push(sl);
      len += v.length;
    }
    return concatBytes3(...out);
  };
  const genUntil = (seed, pred) => {
    reset();
    reseed(seed);
    let res = void 0;
    while (!(res = pred(gen3())))
      reseed();
    reset();
    return res;
  };
  return genUntil;
}
function validateObject(object, validators, optValidators = {}) {
  const checkField = (fieldName, type, isOptional) => {
    const checkVal = validatorFns[type];
    if (typeof checkVal !== "function")
      throw new Error("invalid validator function");
    const val = object[fieldName];
    if (isOptional && val === void 0)
      return;
    if (!checkVal(val, object)) {
      throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val);
    }
  };
  for (const [fieldName, type] of Object.entries(validators))
    checkField(fieldName, type, false);
  for (const [fieldName, type] of Object.entries(optValidators))
    checkField(fieldName, type, true);
  return object;
}
function memoized(fn) {
  const map = /* @__PURE__ */ new WeakMap();
  return (arg, ...args) => {
    const val = map.get(arg);
    if (val !== void 0)
      return val;
    const computed = fn(arg, ...args);
    map.set(arg, computed);
    return computed;
  };
}
var _0n2, _1n2, hasHexBuiltin, hexes2, asciis, isPosBig, bitMask, u8n, u8fr, validatorFns;
var init_utils4 = __esm({
  "node_modules/viem/node_modules/@noble/curves/esm/abstract/utils.js"() {
    "use strict";
    _0n2 = /* @__PURE__ */ BigInt(0);
    _1n2 = /* @__PURE__ */ BigInt(1);
    hasHexBuiltin = // @ts-ignore
    typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function";
    hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
    asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
    isPosBig = (n) => typeof n === "bigint" && _0n2 <= n;
    bitMask = (n) => (_1n2 << BigInt(n)) - _1n2;
    u8n = (len) => new Uint8Array(len);
    u8fr = (arr) => Uint8Array.from(arr);
    validatorFns = {
      bigint: (val) => typeof val === "bigint",
      function: (val) => typeof val === "function",
      boolean: (val) => typeof val === "boolean",
      string: (val) => typeof val === "string",
      stringOrUint8Array: (val) => typeof val === "string" || isBytes2(val),
      isSafeInteger: (val) => Number.isSafeInteger(val),
      array: (val) => Array.isArray(val),
      field: (val, object) => object.Fp.isValid(val),
      hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
    };
  }
});

// node_modules/viem/node_modules/@noble/curves/esm/abstract/modular.js
function mod(a, b) {
  const result = a % b;
  return result >= _0n3 ? result : b + result;
}
function pow2(x, power, modulo2) {
  let res = x;
  while (power-- > _0n3) {
    res *= res;
    res %= modulo2;
  }
  return res;
}
function invert(number, modulo2) {
  if (number === _0n3)
    throw new Error("invert: expected non-zero number");
  if (modulo2 <= _0n3)
    throw new Error("invert: expected positive modulus, got " + modulo2);
  let a = mod(number, modulo2);
  let b = modulo2;
  let x = _0n3, y = _1n3, u = _1n3, v = _0n3;
  while (a !== _0n3) {
    const q = b / a;
    const r = b % a;
    const m = x - u * q;
    const n = y - v * q;
    b = a, a = r, x = u, y = v, u = m, v = n;
  }
  const gcd2 = b;
  if (gcd2 !== _1n3)
    throw new Error("invert: does not exist");
  return mod(x, modulo2);
}
function sqrt3mod4(Fp, n) {
  const p1div4 = (Fp.ORDER + _1n3) / _4n;
  const root = Fp.pow(n, p1div4);
  if (!Fp.eql(Fp.sqr(root), n))
    throw new Error("Cannot find square root");
  return root;
}
function sqrt5mod8(Fp, n) {
  const p5div8 = (Fp.ORDER - _5n) / _8n;
  const n2 = Fp.mul(n, _2n2);
  const v = Fp.pow(n2, p5div8);
  const nv = Fp.mul(n, v);
  const i = Fp.mul(Fp.mul(nv, _2n2), v);
  const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
  if (!Fp.eql(Fp.sqr(root), n))
    throw new Error("Cannot find square root");
  return root;
}
function tonelliShanks(P2) {
  if (P2 < BigInt(3))
    throw new Error("sqrt is not defined for small field");
  let Q = P2 - _1n3;
  let S = 0;
  while (Q % _2n2 === _0n3) {
    Q /= _2n2;
    S++;
  }
  let Z = _2n2;
  const _Fp = Field(P2);
  while (FpLegendre(_Fp, Z) === 1) {
    if (Z++ > 1e3)
      throw new Error("Cannot find square root: probably non-prime P");
  }
  if (S === 1)
    return sqrt3mod4;
  let cc = _Fp.pow(Z, Q);
  const Q1div2 = (Q + _1n3) / _2n2;
  return function tonelliSlow(Fp, n) {
    if (Fp.is0(n))
      return n;
    if (FpLegendre(Fp, n) !== 1)
      throw new Error("Cannot find square root");
    let M = S;
    let c = Fp.mul(Fp.ONE, cc);
    let t = Fp.pow(n, Q);
    let R = Fp.pow(n, Q1div2);
    while (!Fp.eql(t, Fp.ONE)) {
      if (Fp.is0(t))
        return Fp.ZERO;
      let i = 1;
      let t_tmp = Fp.sqr(t);
      while (!Fp.eql(t_tmp, Fp.ONE)) {
        i++;
        t_tmp = Fp.sqr(t_tmp);
        if (i === M)
          throw new Error("Cannot find square root");
      }
      const exponent = _1n3 << BigInt(M - i - 1);
      const b = Fp.pow(c, exponent);
      M = i;
      c = Fp.sqr(b);
      t = Fp.mul(t, c);
      R = Fp.mul(R, b);
    }
    return R;
  };
}
function FpSqrt(P2) {
  if (P2 % _4n === _3n)
    return sqrt3mod4;
  if (P2 % _8n === _5n)
    return sqrt5mod8;
  return tonelliShanks(P2);
}
function validateField(field) {
  const initial = {
    ORDER: "bigint",
    MASK: "bigint",
    BYTES: "isSafeInteger",
    BITS: "isSafeInteger"
  };
  const opts = FIELD_FIELDS.reduce((map, val) => {
    map[val] = "function";
    return map;
  }, initial);
  return validateObject(field, opts);
}
function FpPow(Fp, num2, power) {
  if (power < _0n3)
    throw new Error("invalid exponent, negatives unsupported");
  if (power === _0n3)
    return Fp.ONE;
  if (power === _1n3)
    return num2;
  let p = Fp.ONE;
  let d = num2;
  while (power > _0n3) {
    if (power & _1n3)
      p = Fp.mul(p, d);
    d = Fp.sqr(d);
    power >>= _1n3;
  }
  return p;
}
function FpInvertBatch(Fp, nums, passZero = false) {
  const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
  const multipliedAcc = nums.reduce((acc, num2, i) => {
    if (Fp.is0(num2))
      return acc;
    inverted[i] = acc;
    return Fp.mul(acc, num2);
  }, Fp.ONE);
  const invertedAcc = Fp.inv(multipliedAcc);
  nums.reduceRight((acc, num2, i) => {
    if (Fp.is0(num2))
      return acc;
    inverted[i] = Fp.mul(acc, inverted[i]);
    return Fp.mul(acc, num2);
  }, invertedAcc);
  return inverted;
}
function FpLegendre(Fp, n) {
  const p1mod2 = (Fp.ORDER - _1n3) / _2n2;
  const powered = Fp.pow(n, p1mod2);
  const yes = Fp.eql(powered, Fp.ONE);
  const zero = Fp.eql(powered, Fp.ZERO);
  const no = Fp.eql(powered, Fp.neg(Fp.ONE));
  if (!yes && !zero && !no)
    throw new Error("invalid Legendre symbol result");
  return yes ? 1 : zero ? 0 : -1;
}
function nLength(n, nBitLength) {
  if (nBitLength !== void 0)
    anumber(nBitLength);
  const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
  const nByteLength = Math.ceil(_nBitLength / 8);
  return { nBitLength: _nBitLength, nByteLength };
}
function Field(ORDER, bitLen4, isLE3 = false, redef = {}) {
  if (ORDER <= _0n3)
    throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
  const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen4);
  if (BYTES > 2048)
    throw new Error("invalid field: expected ORDER of <= 2048 bytes");
  let sqrtP;
  const f = Object.freeze({
    ORDER,
    isLE: isLE3,
    BITS,
    BYTES,
    MASK: bitMask(BITS),
    ZERO: _0n3,
    ONE: _1n3,
    create: (num2) => mod(num2, ORDER),
    isValid: (num2) => {
      if (typeof num2 !== "bigint")
        throw new Error("invalid field element: expected bigint, got " + typeof num2);
      return _0n3 <= num2 && num2 < ORDER;
    },
    is0: (num2) => num2 === _0n3,
    isOdd: (num2) => (num2 & _1n3) === _1n3,
    neg: (num2) => mod(-num2, ORDER),
    eql: (lhs, rhs) => lhs === rhs,
    sqr: (num2) => mod(num2 * num2, ORDER),
    add: (lhs, rhs) => mod(lhs + rhs, ORDER),
    sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
    mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
    pow: (num2, power) => FpPow(f, num2, power),
    div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
    // Same as above, but doesn't normalize
    sqrN: (num2) => num2 * num2,
    addN: (lhs, rhs) => lhs + rhs,
    subN: (lhs, rhs) => lhs - rhs,
    mulN: (lhs, rhs) => lhs * rhs,
    inv: (num2) => invert(num2, ORDER),
    sqrt: redef.sqrt || ((n) => {
      if (!sqrtP)
        sqrtP = FpSqrt(ORDER);
      return sqrtP(f, n);
    }),
    toBytes: (num2) => isLE3 ? numberToBytesLE(num2, BYTES) : numberToBytesBE(num2, BYTES),
    fromBytes: (bytes) => {
      if (bytes.length !== BYTES)
        throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
      return isLE3 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
    },
    // TODO: we don't need it here, move out to separate fn
    invertBatch: (lst) => FpInvertBatch(f, lst),
    // We can't move this out because Fp6, Fp12 implement it
    // and it's unclear what to return in there.
    cmov: (a, b, c) => c ? b : a
  });
  return Object.freeze(f);
}
function getFieldBytesLength(fieldOrder) {
  if (typeof fieldOrder !== "bigint")
    throw new Error("field order must be bigint");
  const bitLength = fieldOrder.toString(2).length;
  return Math.ceil(bitLength / 8);
}
function getMinHashLength(fieldOrder) {
  const length = getFieldBytesLength(fieldOrder);
  return length + Math.ceil(length / 2);
}
function mapHashToField(key, fieldOrder, isLE3 = false) {
  const len = key.length;
  const fieldLen = getFieldBytesLength(fieldOrder);
  const minLen = getMinHashLength(fieldOrder);
  if (len < 16 || len < minLen || len > 1024)
    throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
  const num2 = isLE3 ? bytesToNumberLE(key) : bytesToNumberBE(key);
  const reduced = mod(num2, fieldOrder - _1n3) + _1n3;
  return isLE3 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
var _0n3, _1n3, _2n2, _3n, _4n, _5n, _8n, FIELD_FIELDS;
var init_modular = __esm({
  "node_modules/viem/node_modules/@noble/curves/esm/abstract/modular.js"() {
    "use strict";
    init_utils2();
    init_utils4();
    _0n3 = BigInt(0);
    _1n3 = BigInt(1);
    _2n2 = /* @__PURE__ */ BigInt(2);
    _3n = /* @__PURE__ */ BigInt(3);
    _4n = /* @__PURE__ */ BigInt(4);
    _5n = /* @__PURE__ */ BigInt(5);
    _8n = /* @__PURE__ */ BigInt(8);
    FIELD_FIELDS = [
      "create",
      "isValid",
      "is0",
      "neg",
      "inv",
      "sqrt",
      "sqr",
      "eql",
      "add",
      "sub",
      "mul",
      "pow",
      "div",
      "addN",
      "subN",
      "mulN",
      "sqrN"
    ];
  }
});

// node_modules/viem/node_modules/@noble/curves/esm/abstract/curve.js
function constTimeNegate(condition, item) {
  const neg = item.negate();
  return condition ? neg : item;
}
function validateW(W, bits) {
  if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
    throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
}
function calcWOpts(W, scalarBits) {
  validateW(W, scalarBits);
  const windows = Math.ceil(scalarBits / W) + 1;
  const windowSize = 2 ** (W - 1);
  const maxNumber = 2 ** W;
  const mask = bitMask(W);
  const shiftBy = BigInt(W);
  return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets(n, window, wOpts) {
  const { windowSize, mask, maxNumber, shiftBy } = wOpts;
  let wbits = Number(n & mask);
  let nextN = n >> shiftBy;
  if (wbits > windowSize) {
    wbits -= maxNumber;
    nextN += _1n4;
  }
  const offsetStart = window * windowSize;
  const offset = offsetStart + Math.abs(wbits) - 1;
  const isZero = wbits === 0;
  const isNeg = wbits < 0;
  const isNegF = window % 2 !== 0;
  const offsetF = offsetStart;
  return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
function validateMSMPoints(points, c) {
  if (!Array.isArray(points))
    throw new Error("array expected");
  points.forEach((p, i) => {
    if (!(p instanceof c))
      throw new Error("invalid point at index " + i);
  });
}
function validateMSMScalars(scalars, field) {
  if (!Array.isArray(scalars))
    throw new Error("array of scalars expected");
  scalars.forEach((s3, i) => {
    if (!field.isValid(s3))
      throw new Error("invalid scalar at index " + i);
  });
}
function getW(P2) {
  return pointWindowSizes.get(P2) || 1;
}
function wNAF(c, bits) {
  return {
    constTimeNegate,
    hasPrecomputes(elm) {
      return getW(elm) !== 1;
    },
    // non-const time multiplication ladder
    unsafeLadder(elm, n, p = c.ZERO) {
      let d = elm;
      while (n > _0n4) {
        if (n & _1n4)
          p = p.add(d);
        d = d.double();
        n >>= _1n4;
      }
      return p;
    },
    /**
     * Creates a wNAF precomputation window. Used for caching.
     * Default window size is set by `utils.precompute()` and is equal to 8.
     * Number of precomputed points depends on the curve size:
     * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
     * - 𝑊 is the window size
     * - 𝑛 is the bitlength of the curve order.
     * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
     * @param elm Point instance
     * @param W window size
     * @returns precomputed point tables flattened to a single array
     */
    precomputeWindow(elm, W) {
      const { windows, windowSize } = calcWOpts(W, bits);
      const points = [];
      let p = elm;
      let base2 = p;
      for (let window = 0; window < windows; window++) {
        base2 = p;
        points.push(base2);
        for (let i = 1; i < windowSize; i++) {
          base2 = base2.add(p);
          points.push(base2);
        }
        p = base2.double();
      }
      return points;
    },
    /**
     * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
     * @param W window size
     * @param precomputes precomputed tables
     * @param n scalar (we don't check here, but should be less than curve order)
     * @returns real and fake (for const-time) points
     */
    wNAF(W, precomputes, n) {
      let p = c.ZERO;
      let f = c.BASE;
      const wo = calcWOpts(W, bits);
      for (let window = 0; window < wo.windows; window++) {
        const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
        n = nextN;
        if (isZero) {
          f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));
        } else {
          p = p.add(constTimeNegate(isNeg, precomputes[offset]));
        }
      }
      return { p, f };
    },
    /**
     * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
     * @param W window size
     * @param precomputes precomputed tables
     * @param n scalar (we don't check here, but should be less than curve order)
     * @param acc accumulator point to add result of multiplication
     * @returns point
     */
    wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
      const wo = calcWOpts(W, bits);
      for (let window = 0; window < wo.windows; window++) {
        if (n === _0n4)
          break;
        const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
        n = nextN;
        if (isZero) {
          continue;
        } else {
          const item = precomputes[offset];
          acc = acc.add(isNeg ? item.negate() : item);
        }
      }
      return acc;
    },
    getPrecomputes(W, P2, transform2) {
      let comp = pointPrecomputes.get(P2);
      if (!comp) {
        comp = this.precomputeWindow(P2, W);
        if (W !== 1)
          pointPrecomputes.set(P2, transform2(comp));
      }
      return comp;
    },
    wNAFCached(P2, n, transform2) {
      const W = getW(P2);
      return this.wNAF(W, this.getPrecomputes(W, P2, transform2), n);
    },
    wNAFCachedUnsafe(P2, n, transform2, prev) {
      const W = getW(P2);
      if (W === 1)
        return this.unsafeLadder(P2, n, prev);
      return this.wNAFUnsafe(W, this.getPrecomputes(W, P2, transform2), n, prev);
    },
    // We calculate precomputes for elliptic curve point multiplication
    // using windowed method. This specifies window size and
    // stores precomputed values. Usually only base point would be precomputed.
    setWindowSize(P2, W) {
      validateW(W, bits);
      pointWindowSizes.set(P2, W);
      pointPrecomputes.delete(P2);
    }
  };
}
function pippenger(c, fieldN, points, scalars) {
  validateMSMPoints(points, c);
  validateMSMScalars(scalars, fieldN);
  const plength = points.length;
  const slength = scalars.length;
  if (plength !== slength)
    throw new Error("arrays of points and scalars must have equal length");
  const zero = c.ZERO;
  const wbits = bitLen(BigInt(plength));
  let windowSize = 1;
  if (wbits > 12)
    windowSize = wbits - 3;
  else if (wbits > 4)
    windowSize = wbits - 2;
  else if (wbits > 0)
    windowSize = 2;
  const MASK = bitMask(windowSize);
  const buckets = new Array(Number(MASK) + 1).fill(zero);
  const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
  let sum = zero;
  for (let i = lastBits; i >= 0; i -= windowSize) {
    buckets.fill(zero);
    for (let j = 0; j < slength; j++) {
      const scalar = scalars[j];
      const wbits2 = Number(scalar >> BigInt(i) & MASK);
      buckets[wbits2] = buckets[wbits2].add(points[j]);
    }
    let resI = zero;
    for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
      sumI = sumI.add(buckets[j]);
      resI = resI.add(sumI);
    }
    sum = sum.add(resI);
    if (i !== 0)
      for (let j = 0; j < windowSize; j++)
        sum = sum.double();
  }
  return sum;
}
function validateBasic(curve) {
  validateField(curve.Fp);
  validateObject(curve, {
    n: "bigint",
    h: "bigint",
    Gx: "field",
    Gy: "field"
  }, {
    nBitLength: "isSafeInteger",
    nByteLength: "isSafeInteger"
  });
  return Object.freeze({
    ...nLength(curve.n, curve.nBitLength),
    ...curve,
    ...{ p: curve.Fp.ORDER }
  });
}
var _0n4, _1n4, pointPrecomputes, pointWindowSizes;
var init_curve = __esm({
  "node_modules/viem/node_modules/@noble/curves/esm/abstract/curve.js"() {
    "use strict";
    init_modular();
    init_utils4();
    _0n4 = BigInt(0);
    _1n4 = BigInt(1);
    pointPrecomputes = /* @__PURE__ */ new WeakMap();
    pointWindowSizes = /* @__PURE__ */ new WeakMap();
  }
});

// node_modules/viem/node_modules/@noble/curves/esm/abstract/weierstrass.js
function validateSigVerOpts(opts) {
  if (opts.lowS !== void 0)
    abool("lowS", opts.lowS);
  if (opts.prehash !== void 0)
    abool("prehash", opts.prehash);
}
function validatePointOpts(curve) {
  const opts = validateBasic(curve);
  validateObject(opts, {
    a: "field",
    b: "field"
  }, {
    allowInfinityPoint: "boolean",
    allowedPrivateKeyLengths: "array",
    clearCofactor: "function",
    fromBytes: "function",
    isTorsionFree: "function",
    toBytes: "function",
    wrapPrivateKey: "boolean"
  });
  const { endo, Fp, a } = opts;
  if (endo) {
    if (!Fp.eql(a, Fp.ZERO)) {
      throw new Error("invalid endo: CURVE.a must be 0");
    }
    if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") {
      throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');
    }
  }
  return Object.freeze({ ...opts });
}
function numToSizedHex(num2, size5) {
  return bytesToHex2(numberToBytesBE(num2, size5));
}
function weierstrassPoints(opts) {
  const CURVE = validatePointOpts(opts);
  const { Fp } = CURVE;
  const Fn2 = Field(CURVE.n, CURVE.nBitLength);
  const toBytes6 = CURVE.toBytes || ((_c, point, _isCompressed) => {
    const a = point.toAffine();
    return concatBytes3(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y));
  });
  const fromBytes4 = CURVE.fromBytes || ((bytes) => {
    const tail = bytes.subarray(1);
    const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
    const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
    return { x, y };
  });
  function weierstrassEquation(x) {
    const { a, b } = CURVE;
    const x2 = Fp.sqr(x);
    const x3 = Fp.mul(x2, x);
    return Fp.add(Fp.add(x3, Fp.mul(x, a)), b);
  }
  function isValidXY(x, y) {
    const left = Fp.sqr(y);
    const right = weierstrassEquation(x);
    return Fp.eql(left, right);
  }
  if (!isValidXY(CURVE.Gx, CURVE.Gy))
    throw new Error("bad curve params: generator point");
  const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2);
  const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
  if (Fp.is0(Fp.add(_4a3, _27b2)))
    throw new Error("bad curve params: a or b");
  function isWithinCurveOrder(num2) {
    return inRange(num2, _1n5, CURVE.n);
  }
  function normPrivateKeyToScalar(key) {
    const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;
    if (lengths && typeof key !== "bigint") {
      if (isBytes2(key))
        key = bytesToHex2(key);
      if (typeof key !== "string" || !lengths.includes(key.length))
        throw new Error("invalid private key");
      key = key.padStart(nByteLength * 2, "0");
    }
    let num2;
    try {
      num2 = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength));
    } catch (error) {
      throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key);
    }
    if (wrapPrivateKey)
      num2 = mod(num2, N);
    aInRange("private key", num2, _1n5, N);
    return num2;
  }
  function aprjpoint(other) {
    if (!(other instanceof Point3))
      throw new Error("ProjectivePoint expected");
  }
  const toAffineMemo = memoized((p, iz) => {
    const { px: x, py: y, pz: z } = p;
    if (Fp.eql(z, Fp.ONE))
      return { x, y };
    const is0 = p.is0();
    if (iz == null)
      iz = is0 ? Fp.ONE : Fp.inv(z);
    const ax = Fp.mul(x, iz);
    const ay = Fp.mul(y, iz);
    const zz = Fp.mul(z, iz);
    if (is0)
      return { x: Fp.ZERO, y: Fp.ZERO };
    if (!Fp.eql(zz, Fp.ONE))
      throw new Error("invZ was invalid");
    return { x: ax, y: ay };
  });
  const assertValidMemo = memoized((p) => {
    if (p.is0()) {
      if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
        return;
      throw new Error("bad point: ZERO");
    }
    const { x, y } = p.toAffine();
    if (!Fp.isValid(x) || !Fp.isValid(y))
      throw new Error("bad point: x or y not FE");
    if (!isValidXY(x, y))
      throw new Error("bad point: equation left != right");
    if (!p.isTorsionFree())
      throw new Error("bad point: not in prime-order subgroup");
    return true;
  });
  class Point3 {
    constructor(px, py, pz) {
      if (px == null || !Fp.isValid(px))
        throw new Error("x required");
      if (py == null || !Fp.isValid(py) || Fp.is0(py))
        throw new Error("y required");
      if (pz == null || !Fp.isValid(pz))
        throw new Error("z required");
      this.px = px;
      this.py = py;
      this.pz = pz;
      Object.freeze(this);
    }
    // Does not validate if the point is on-curve.
    // Use fromHex instead, or call assertValidity() later.
    static fromAffine(p) {
      const { x, y } = p || {};
      if (!p || !Fp.isValid(x) || !Fp.isValid(y))
        throw new Error("invalid affine point");
      if (p instanceof Point3)
        throw new Error("projective point not allowed");
      const is0 = (i) => Fp.eql(i, Fp.ZERO);
      if (is0(x) && is0(y))
        return Point3.ZERO;
      return new Point3(x, y, Fp.ONE);
    }
    get x() {
      return this.toAffine().x;
    }
    get y() {
      return this.toAffine().y;
    }
    /**
     * Takes a bunch of Projective Points but executes only one
     * inversion on all of them. Inversion is very slow operation,
     * so this improves performance massively.
     * Optimization: converts a list of projective points to a list of identical points with Z=1.
     */
    static normalizeZ(points) {
      const toInv = FpInvertBatch(Fp, points.map((p) => p.pz));
      return points.map((p, i) => p.toAffine(toInv[i])).map(Point3.fromAffine);
    }
    /**
     * Converts hash string or Uint8Array to Point.
     * @param hex short/long ECDSA hex
     */
    static fromHex(hex) {
      const P2 = Point3.fromAffine(fromBytes4(ensureBytes("pointHex", hex)));
      P2.assertValidity();
      return P2;
    }
    // Multiplies generator point by privateKey.
    static fromPrivateKey(privateKey) {
      return Point3.BASE.multiply(normPrivateKeyToScalar(privateKey));
    }
    // Multiscalar Multiplication
    static msm(points, scalars) {
      return pippenger(Point3, Fn2, points, scalars);
    }
    // "Private method", don't use it directly
    _setWindowSize(windowSize) {
      wnaf.setWindowSize(this, windowSize);
    }
    // A point on curve is valid if it conforms to equation.
    assertValidity() {
      assertValidMemo(this);
    }
    hasEvenY() {
      const { y } = this.toAffine();
      if (Fp.isOdd)
        return !Fp.isOdd(y);
      throw new Error("Field doesn't support isOdd");
    }
    /**
     * Compare one point to another.
     */
    equals(other) {
      aprjpoint(other);
      const { px: X1, py: Y1, pz: Z1 } = this;
      const { px: X2, py: Y2, pz: Z2 } = other;
      const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
      const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
      return U1 && U2;
    }
    /**
     * Flips point to one corresponding to (x, -y) in Affine coordinates.
     */
    negate() {
      return new Point3(this.px, Fp.neg(this.py), this.pz);
    }
    // Renes-Costello-Batina exception-free doubling formula.
    // There is 30% faster Jacobian formula, but it is not complete.
    // https://eprint.iacr.org/2015/1060, algorithm 3
    // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
    double() {
      const { a, b } = CURVE;
      const b3 = Fp.mul(b, _3n2);
      const { px: X1, py: Y1, pz: Z1 } = this;
      let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
      let t0 = Fp.mul(X1, X1);
      let t1 = Fp.mul(Y1, Y1);
      let t2 = Fp.mul(Z1, Z1);
      let t3 = Fp.mul(X1, Y1);
      t3 = Fp.add(t3, t3);
      Z3 = Fp.mul(X1, Z1);
      Z3 = Fp.add(Z3, Z3);
      X3 = Fp.mul(a, Z3);
      Y3 = Fp.mul(b3, t2);
      Y3 = Fp.add(X3, Y3);
      X3 = Fp.sub(t1, Y3);
      Y3 = Fp.add(t1, Y3);
      Y3 = Fp.mul(X3, Y3);
      X3 = Fp.mul(t3, X3);
      Z3 = Fp.mul(b3, Z3);
      t2 = Fp.mul(a, t2);
      t3 = Fp.sub(t0, t2);
      t3 = Fp.mul(a, t3);
      t3 = Fp.add(t3, Z3);
      Z3 = Fp.add(t0, t0);
      t0 = Fp.add(Z3, t0);
      t0 = Fp.add(t0, t2);
      t0 = Fp.mul(t0, t3);
      Y3 = Fp.add(Y3, t0);
      t2 = Fp.mul(Y1, Z1);
      t2 = Fp.add(t2, t2);
      t0 = Fp.mul(t2, t3);
      X3 = Fp.sub(X3, t0);
      Z3 = Fp.mul(t2, t1);
      Z3 = Fp.add(Z3, Z3);
      Z3 = Fp.add(Z3, Z3);
      return new Point3(X3, Y3, Z3);
    }
    // Renes-Costello-Batina exception-free addition formula.
    // There is 30% faster Jacobian formula, but it is not complete.
    // https://eprint.iacr.org/2015/1060, algorithm 1
    // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
    add(other) {
      aprjpoint(other);
      const { px: X1, py: Y1, pz: Z1 } = this;
      const { px: X2, py: Y2, pz: Z2 } = other;
      let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
      const a = CURVE.a;
      const b3 = Fp.mul(CURVE.b, _3n2);
      let t0 = Fp.mul(X1, X2);
      let t1 = Fp.mul(Y1, Y2);
      let t2 = Fp.mul(Z1, Z2);
      let t3 = Fp.add(X1, Y1);
      let t4 = Fp.add(X2, Y2);
      t3 = Fp.mul(t3, t4);
      t4 = Fp.add(t0, t1);
      t3 = Fp.sub(t3, t4);
      t4 = Fp.add(X1, Z1);
      let t5 = Fp.add(X2, Z2);
      t4 = Fp.mul(t4, t5);
      t5 = Fp.add(t0, t2);
      t4 = Fp.sub(t4, t5);
      t5 = Fp.add(Y1, Z1);
      X3 = Fp.add(Y2, Z2);
      t5 = Fp.mul(t5, X3);
      X3 = Fp.add(t1, t2);
      t5 = Fp.sub(t5, X3);
      Z3 = Fp.mul(a, t4);
      X3 = Fp.mul(b3, t2);
      Z3 = Fp.add(X3, Z3);
      X3 = Fp.sub(t1, Z3);
      Z3 = Fp.add(t1, Z3);
      Y3 = Fp.mul(X3, Z3);
      t1 = Fp.add(t0, t0);
      t1 = Fp.add(t1, t0);
      t2 = Fp.mul(a, t2);
      t4 = Fp.mul(b3, t4);
      t1 = Fp.add(t1, t2);
      t2 = Fp.sub(t0, t2);
      t2 = Fp.mul(a, t2);
      t4 = Fp.add(t4, t2);
      t0 = Fp.mul(t1, t4);
      Y3 = Fp.add(Y3, t0);
      t0 = Fp.mul(t5, t4);
      X3 = Fp.mul(t3, X3);
      X3 = Fp.sub(X3, t0);
      t0 = Fp.mul(t3, t1);
      Z3 = Fp.mul(t5, Z3);
      Z3 = Fp.add(Z3, t0);
      return new Point3(X3, Y3, Z3);
    }
    subtract(other) {
      return this.add(other.negate());
    }
    is0() {
      return this.equals(Point3.ZERO);
    }
    wNAF(n) {
      return wnaf.wNAFCached(this, n, Point3.normalizeZ);
    }
    /**
     * Non-constant-time multiplication. Uses double-and-add algorithm.
     * It's faster, but should only be used when you don't care about
     * an exposed private key e.g. sig verification, which works over *public* keys.
     */
    multiplyUnsafe(sc) {
      const { endo: endo2, n: N } = CURVE;
      aInRange("scalar", sc, _0n5, N);
      const I = Point3.ZERO;
      if (sc === _0n5)
        return I;
      if (this.is0() || sc === _1n5)
        return this;
      if (!endo2 || wnaf.hasPrecomputes(this))
        return wnaf.wNAFCachedUnsafe(this, sc, Point3.normalizeZ);
      let { k1neg, k1, k2neg, k2 } = endo2.splitScalar(sc);
      let k1p = I;
      let k2p = I;
      let d = this;
      while (k1 > _0n5 || k2 > _0n5) {
        if (k1 & _1n5)
          k1p = k1p.add(d);
        if (k2 & _1n5)
          k2p = k2p.add(d);
        d = d.double();
        k1 >>= _1n5;
        k2 >>= _1n5;
      }
      if (k1neg)
        k1p = k1p.negate();
      if (k2neg)
        k2p = k2p.negate();
      k2p = new Point3(Fp.mul(k2p.px, endo2.beta), k2p.py, k2p.pz);
      return k1p.add(k2p);
    }
    /**
     * Constant time multiplication.
     * Uses wNAF method. Windowed method may be 10% faster,
     * but takes 2x longer to generate and consumes 2x memory.
     * Uses precomputes when available.
     * Uses endomorphism for Koblitz curves.
     * @param scalar by which the point would be multiplied
     * @returns New point
     */
    multiply(scalar) {
      const { endo: endo2, n: N } = CURVE;
      aInRange("scalar", scalar, _1n5, N);
      let point, fake;
      if (endo2) {
        const { k1neg, k1, k2neg, k2 } = endo2.splitScalar(scalar);
        let { p: k1p, f: f1p } = this.wNAF(k1);
        let { p: k2p, f: f2p } = this.wNAF(k2);
        k1p = wnaf.constTimeNegate(k1neg, k1p);
        k2p = wnaf.constTimeNegate(k2neg, k2p);
        k2p = new Point3(Fp.mul(k2p.px, endo2.beta), k2p.py, k2p.pz);
        point = k1p.add(k2p);
        fake = f1p.add(f2p);
      } else {
        const { p, f } = this.wNAF(scalar);
        point = p;
        fake = f;
      }
      return Point3.normalizeZ([point, fake])[0];
    }
    /**
     * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
     * Not using Strauss-Shamir trick: precomputation tables are faster.
     * The trick could be useful if both P and Q are not G (not in our case).
     * @returns non-zero affine point
     */
    multiplyAndAddUnsafe(Q, a, b) {
      const G = Point3.BASE;
      const mul = (P2, a2) => a2 === _0n5 || a2 === _1n5 || !P2.equals(G) ? P2.multiplyUnsafe(a2) : P2.multiply(a2);
      const sum = mul(this, a).add(mul(Q, b));
      return sum.is0() ? void 0 : sum;
    }
    // Converts Projective point to affine (x, y) coordinates.
    // Can accept precomputed Z^-1 - for example, from invertBatch.
    // (x, y, z) ∋ (x=x/z, y=y/z)
    toAffine(iz) {
      return toAffineMemo(this, iz);
    }
    isTorsionFree() {
      const { h: cofactor, isTorsionFree } = CURVE;
      if (cofactor === _1n5)
        return true;
      if (isTorsionFree)
        return isTorsionFree(Point3, this);
      throw new Error("isTorsionFree() has not been declared for the elliptic curve");
    }
    clearCofactor() {
      const { h: cofactor, clearCofactor } = CURVE;
      if (cofactor === _1n5)
        return this;
      if (clearCofactor)
        return clearCofactor(Point3, this);
      return this.multiplyUnsafe(CURVE.h);
    }
    toRawBytes(isCompressed = true) {
      abool("isCompressed", isCompressed);
      this.assertValidity();
      return toBytes6(Point3, this, isCompressed);
    }
    toHex(isCompressed = true) {
      abool("isCompressed", isCompressed);
      return bytesToHex2(this.toRawBytes(isCompressed));
    }
  }
  Point3.BASE = new Point3(CURVE.Gx, CURVE.Gy, Fp.ONE);
  Point3.ZERO = new Point3(Fp.ZERO, Fp.ONE, Fp.ZERO);
  const { endo, nBitLength } = CURVE;
  const wnaf = wNAF(Point3, endo ? Math.ceil(nBitLength / 2) : nBitLength);
  return {
    CURVE,
    ProjectivePoint: Point3,
    normPrivateKeyToScalar,
    weierstrassEquation,
    isWithinCurveOrder
  };
}
function validateOpts(curve) {
  const opts = validateBasic(curve);
  validateObject(opts, {
    hash: "hash",
    hmac: "function",
    randomBytes: "function"
  }, {
    bits2int: "function",
    bits2int_modN: "function",
    lowS: "boolean"
  });
  return Object.freeze({ lowS: true, ...opts });
}
function weierstrass(curveDef) {
  const CURVE = validateOpts(curveDef);
  const { Fp, n: CURVE_ORDER, nByteLength, nBitLength } = CURVE;
  const compressedLen = Fp.BYTES + 1;
  const uncompressedLen = 2 * Fp.BYTES + 1;
  function modN2(a) {
    return mod(a, CURVE_ORDER);
  }
  function invN(a) {
    return invert(a, CURVE_ORDER);
  }
  const { ProjectivePoint: Point3, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({
    ...CURVE,
    toBytes(_c, point, isCompressed) {
      const a = point.toAffine();
      const x = Fp.toBytes(a.x);
      const cat = concatBytes3;
      abool("isCompressed", isCompressed);
      if (isCompressed) {
        return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
      } else {
        return cat(Uint8Array.from([4]), x, Fp.toBytes(a.y));
      }
    },
    fromBytes(bytes) {
      const len = bytes.length;
      const head = bytes[0];
      const tail = bytes.subarray(1);
      if (len === compressedLen && (head === 2 || head === 3)) {
        const x = bytesToNumberBE(tail);
        if (!inRange(x, _1n5, Fp.ORDER))
          throw new Error("Point is not on curve");
        const y2 = weierstrassEquation(x);
        let y;
        try {
          y = Fp.sqrt(y2);
        } catch (sqrtError) {
          const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : "";
          throw new Error("Point is not on curve" + suffix);
        }
        const isYOdd = (y & _1n5) === _1n5;
        const isHeadOdd = (head & 1) === 1;
        if (isHeadOdd !== isYOdd)
          y = Fp.neg(y);
        return { x, y };
      } else if (len === uncompressedLen && head === 4) {
        const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
        const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
        return { x, y };
      } else {
        const cl = compressedLen;
        const ul = uncompressedLen;
        throw new Error("invalid Point, expected length of " + cl + ", or uncompressed " + ul + ", got " + len);
      }
    }
  });
  function isBiggerThanHalfOrder(number) {
    const HALF = CURVE_ORDER >> _1n5;
    return number > HALF;
  }
  function normalizeS(s3) {
    return isBiggerThanHalfOrder(s3) ? modN2(-s3) : s3;
  }
  const slcNum = (b, from14, to) => bytesToNumberBE(b.slice(from14, to));
  class Signature {
    constructor(r, s3, recovery) {
      aInRange("r", r, _1n5, CURVE_ORDER);
      aInRange("s", s3, _1n5, CURVE_ORDER);
      this.r = r;
      this.s = s3;
      if (recovery != null)
        this.recovery = recovery;
      Object.freeze(this);
    }
    // pair (bytes of r, bytes of s)
    static fromCompact(hex) {
      const l2 = nByteLength;
      hex = ensureBytes("compactSignature", hex, l2 * 2);
      return new Signature(slcNum(hex, 0, l2), slcNum(hex, l2, 2 * l2));
    }
    // DER encoded ECDSA signature
    // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
    static fromDER(hex) {
      const { r, s: s3 } = DER.toSig(ensureBytes("DER", hex));
      return new Signature(r, s3);
    }
    /**
     * @todo remove
     * @deprecated
     */
    assertValidity() {
    }
    addRecoveryBit(recovery) {
      return new Signature(this.r, this.s, recovery);
    }
    recoverPublicKey(msgHash) {
      const { r, s: s3, recovery: rec } = this;
      const h = bits2int_modN(ensureBytes("msgHash", msgHash));
      if (rec == null || ![0, 1, 2, 3].includes(rec))
        throw new Error("recovery id invalid");
      const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
      if (radj >= Fp.ORDER)
        throw new Error("recovery id 2 or 3 invalid");
      const prefix = (rec & 1) === 0 ? "02" : "03";
      const R = Point3.fromHex(prefix + numToSizedHex(radj, Fp.BYTES));
      const ir = invN(radj);
      const u1 = modN2(-h * ir);
      const u2 = modN2(s3 * ir);
      const Q = Point3.BASE.multiplyAndAddUnsafe(R, u1, u2);
      if (!Q)
        throw new Error("point at infinify");
      Q.assertValidity();
      return Q;
    }
    // Signatures should be low-s, to prevent malleability.
    hasHighS() {
      return isBiggerThanHalfOrder(this.s);
    }
    normalizeS() {
      return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this;
    }
    // DER-encoded
    toDERRawBytes() {
      return hexToBytes2(this.toDERHex());
    }
    toDERHex() {
      return DER.hexFromSig(this);
    }
    // padded bytes of r, then padded bytes of s
    toCompactRawBytes() {
      return hexToBytes2(this.toCompactHex());
    }
    toCompactHex() {
      const l2 = nByteLength;
      return numToSizedHex(this.r, l2) + numToSizedHex(this.s, l2);
    }
  }
  const utils2 = {
    isValidPrivateKey(privateKey) {
      try {
        normPrivateKeyToScalar(privateKey);
        return true;
      } catch (error) {
        return false;
      }
    },
    normPrivateKeyToScalar,
    /**
     * Produces cryptographically secure private key from random of size
     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
     */
    randomPrivateKey: () => {
      const length = getMinHashLength(CURVE.n);
      return mapHashToField(CURVE.randomBytes(length), CURVE.n);
    },
    /**
     * Creates precompute table for an arbitrary EC point. Makes point "cached".
     * Allows to massively speed-up `point.multiply(scalar)`.
     * @returns cached point
     * @example
     * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
     * fast.multiply(privKey); // much faster ECDH now
     */
    precompute(windowSize = 8, point = Point3.BASE) {
      point._setWindowSize(windowSize);
      point.multiply(BigInt(3));
      return point;
    }
  };
  function getPublicKey(privateKey, isCompressed = true) {
    return Point3.fromPrivateKey(privateKey).toRawBytes(isCompressed);
  }
  function isProbPub(item) {
    if (typeof item === "bigint")
      return false;
    if (item instanceof Point3)
      return true;
    const arr = ensureBytes("key", item);
    const len = arr.length;
    const fpl = Fp.BYTES;
    const compLen = fpl + 1;
    const uncompLen = 2 * fpl + 1;
    if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {
      return void 0;
    } else {
      return len === compLen || len === uncompLen;
    }
  }
  function getSharedSecret(privateA, publicB, isCompressed = true) {
    if (isProbPub(privateA) === true)
      throw new Error("first arg must be private key");
    if (isProbPub(publicB) === false)
      throw new Error("second arg must be public key");
    const b = Point3.fromHex(publicB);
    return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
  }
  const bits2int = CURVE.bits2int || function(bytes) {
    if (bytes.length > 8192)
      throw new Error("input is too large");
    const num2 = bytesToNumberBE(bytes);
    const delta = bytes.length * 8 - nBitLength;
    return delta > 0 ? num2 >> BigInt(delta) : num2;
  };
  const bits2int_modN = CURVE.bits2int_modN || function(bytes) {
    return modN2(bits2int(bytes));
  };
  const ORDER_MASK = bitMask(nBitLength);
  function int2octets(num2) {
    aInRange("num < 2^" + nBitLength, num2, _0n5, ORDER_MASK);
    return numberToBytesBE(num2, nByteLength);
  }
  function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
    if (["recovered", "canonical"].some((k) => k in opts))
      throw new Error("sign() legacy options not supported");
    const { hash: hash3, randomBytes: randomBytes8 } = CURVE;
    let { lowS, prehash, extraEntropy: ent } = opts;
    if (lowS == null)
      lowS = true;
    msgHash = ensureBytes("msgHash", msgHash);
    validateSigVerOpts(opts);
    if (prehash)
      msgHash = ensureBytes("prehashed msgHash", hash3(msgHash));
    const h1int = bits2int_modN(msgHash);
    const d = normPrivateKeyToScalar(privateKey);
    const seedArgs = [int2octets(d), int2octets(h1int)];
    if (ent != null && ent !== false) {
      const e7 = ent === true ? randomBytes8(Fp.BYTES) : ent;
      seedArgs.push(ensureBytes("extraEntropy", e7));
    }
    const seed = concatBytes3(...seedArgs);
    const m = h1int;
    function k2sig(kBytes) {
      const k = bits2int(kBytes);
      if (!isWithinCurveOrder(k))
        return;
      const ik = invN(k);
      const q = Point3.BASE.multiply(k).toAffine();
      const r = modN2(q.x);
      if (r === _0n5)
        return;
      const s3 = modN2(ik * modN2(m + r * d));
      if (s3 === _0n5)
        return;
      let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n5);
      let normS = s3;
      if (lowS && isBiggerThanHalfOrder(s3)) {
        normS = normalizeS(s3);
        recovery ^= 1;
      }
      return new Signature(r, normS, recovery);
    }
    return { seed, k2sig };
  }
  const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
  const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
  function sign2(msgHash, privKey, opts = defaultSigOpts) {
    const { seed, k2sig } = prepSig(msgHash, privKey, opts);
    const C = CURVE;
    const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
    return drbg(seed, k2sig);
  }
  Point3.BASE._setWindowSize(8);
  function verify(signature2, msgHash, publicKey, opts = defaultVerOpts) {
    const sg = signature2;
    msgHash = ensureBytes("msgHash", msgHash);
    publicKey = ensureBytes("publicKey", publicKey);
    const { lowS, prehash, format } = opts;
    validateSigVerOpts(opts);
    if ("strict" in opts)
      throw new Error("options.strict was renamed to lowS");
    if (format !== void 0 && format !== "compact" && format !== "der")
      throw new Error("format must be compact or der");
    const isHex2 = typeof sg === "string" || isBytes2(sg);
    const isObj = !isHex2 && !format && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint";
    if (!isHex2 && !isObj)
      throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
    let _sig = void 0;
    let P2;
    try {
      if (isObj)
        _sig = new Signature(sg.r, sg.s);
      if (isHex2) {
        try {
          if (format !== "compact")
            _sig = Signature.fromDER(sg);
        } catch (derError) {
          if (!(derError instanceof DER.Err))
            throw derError;
        }
        if (!_sig && format !== "der")
          _sig = Signature.fromCompact(sg);
      }
      P2 = Point3.fromHex(publicKey);
    } catch (error) {
      return false;
    }
    if (!_sig)
      return false;
    if (lowS && _sig.hasHighS())
      return false;
    if (prehash)
      msgHash = CURVE.hash(msgHash);
    const { r, s: s3 } = _sig;
    const h = bits2int_modN(msgHash);
    const is = invN(s3);
    const u1 = modN2(h * is);
    const u2 = modN2(r * is);
    const R = Point3.BASE.multiplyAndAddUnsafe(P2, u1, u2)?.toAffine();
    if (!R)
      return false;
    const v = modN2(R.x);
    return v === r;
  }
  return {
    CURVE,
    getPublicKey,
    getSharedSecret,
    sign: sign2,
    verify,
    ProjectivePoint: Point3,
    Signature,
    utils: utils2
  };
}
function SWUFpSqrtRatio(Fp, Z) {
  const q = Fp.ORDER;
  let l2 = _0n5;
  for (let o3 = q - _1n5; o3 % _2n3 === _0n5; o3 /= _2n3)
    l2 += _1n5;
  const c1 = l2;
  const _2n_pow_c1_1 = _2n3 << c1 - _1n5 - _1n5;
  const _2n_pow_c1 = _2n_pow_c1_1 * _2n3;
  const c2 = (q - _1n5) / _2n_pow_c1;
  const c3 = (c2 - _1n5) / _2n3;
  const c4 = _2n_pow_c1 - _1n5;
  const c5 = _2n_pow_c1_1;
  const c6 = Fp.pow(Z, c2);
  const c7 = Fp.pow(Z, (c2 + _1n5) / _2n3);
  let sqrtRatio = (u, v) => {
    let tv1 = c6;
    let tv2 = Fp.pow(v, c4);
    let tv3 = Fp.sqr(tv2);
    tv3 = Fp.mul(tv3, v);
    let tv5 = Fp.mul(u, tv3);
    tv5 = Fp.pow(tv5, c3);
    tv5 = Fp.mul(tv5, tv2);
    tv2 = Fp.mul(tv5, v);
    tv3 = Fp.mul(tv5, u);
    let tv4 = Fp.mul(tv3, tv2);
    tv5 = Fp.pow(tv4, c5);
    let isQR = Fp.eql(tv5, Fp.ONE);
    tv2 = Fp.mul(tv3, c7);
    tv5 = Fp.mul(tv4, tv1);
    tv3 = Fp.cmov(tv2, tv3, isQR);
    tv4 = Fp.cmov(tv5, tv4, isQR);
    for (let i = c1; i > _1n5; i--) {
      let tv52 = i - _2n3;
      tv52 = _2n3 << tv52 - _1n5;
      let tvv5 = Fp.pow(tv4, tv52);
      const e1 = Fp.eql(tvv5, Fp.ONE);
      tv2 = Fp.mul(tv3, tv1);
      tv1 = Fp.mul(tv1, tv1);
      tvv5 = Fp.mul(tv4, tv1);
      tv3 = Fp.cmov(tv2, tv3, e1);
      tv4 = Fp.cmov(tvv5, tv4, e1);
    }
    return { isValid: isQR, value: tv3 };
  };
  if (Fp.ORDER % _4n2 === _3n2) {
    const c12 = (Fp.ORDER - _3n2) / _4n2;
    const c22 = Fp.sqrt(Fp.neg(Z));
    sqrtRatio = (u, v) => {
      let tv1 = Fp.sqr(v);
      const tv2 = Fp.mul(u, v);
      tv1 = Fp.mul(tv1, tv2);
      let y1 = Fp.pow(tv1, c12);
      y1 = Fp.mul(y1, tv2);
      const y2 = Fp.mul(y1, c22);
      const tv3 = Fp.mul(Fp.sqr(y1), v);
      const isQR = Fp.eql(tv3, u);
      let y = Fp.cmov(y2, y1, isQR);
      return { isValid: isQR, value: y };
    };
  }
  return sqrtRatio;
}
function mapToCurveSimpleSWU(Fp, opts) {
  validateField(Fp);
  if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))
    throw new Error("mapToCurveSimpleSWU: invalid opts");
  const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);
  if (!Fp.isOdd)
    throw new Error("Fp.isOdd is not implemented!");
  return (u) => {
    let tv1, tv2, tv3, tv4, tv5, tv6, x, y;
    tv1 = Fp.sqr(u);
    tv1 = Fp.mul(tv1, opts.Z);
    tv2 = Fp.sqr(tv1);
    tv2 = Fp.add(tv2, tv1);
    tv3 = Fp.add(tv2, Fp.ONE);
    tv3 = Fp.mul(tv3, opts.B);
    tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO));
    tv4 = Fp.mul(tv4, opts.A);
    tv2 = Fp.sqr(tv3);
    tv6 = Fp.sqr(tv4);
    tv5 = Fp.mul(tv6, opts.A);
    tv2 = Fp.add(tv2, tv5);
    tv2 = Fp.mul(tv2, tv3);
    tv6 = Fp.mul(tv6, tv4);
    tv5 = Fp.mul(tv6, opts.B);
    tv2 = Fp.add(tv2, tv5);
    x = Fp.mul(tv1, tv3);
    const { isValid: isValid2, value } = sqrtRatio(tv2, tv6);
    y = Fp.mul(tv1, u);
    y = Fp.mul(y, value);
    x = Fp.cmov(x, tv3, isValid2);
    y = Fp.cmov(y, value, isValid2);
    const e1 = Fp.isOdd(u) === Fp.isOdd(y);
    y = Fp.cmov(Fp.neg(y), y, e1);
    const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];
    x = Fp.mul(x, tv4_inv);
    return { x, y };
  };
}
var DERErr, DER, _0n5, _1n5, _2n3, _3n2, _4n2;
var init_weierstrass = __esm({
  "node_modules/viem/node_modules/@noble/curves/esm/abstract/weierstrass.js"() {
    "use strict";
    init_curve();
    init_modular();
    init_utils4();
    DERErr = class extends Error {
      constructor(m = "") {
        super(m);
      }
    };
    DER = {
      // asn.1 DER encoding utils
      Err: DERErr,
      // Basic building block is TLV (Tag-Length-Value)
      _tlv: {
        encode: (tag, data) => {
          const { Err: E } = DER;
          if (tag < 0 || tag > 256)
            throw new E("tlv.encode: wrong tag");
          if (data.length & 1)
            throw new E("tlv.encode: unpadded data");
          const dataLen = data.length / 2;
          const len = numberToHexUnpadded(dataLen);
          if (len.length / 2 & 128)
            throw new E("tlv.encode: long form length too big");
          const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
          const t = numberToHexUnpadded(tag);
          return t + lenLen + len + data;
        },
        // v - value, l - left bytes (unparsed)
        decode(tag, data) {
          const { Err: E } = DER;
          let pos = 0;
          if (tag < 0 || tag > 256)
            throw new E("tlv.encode: wrong tag");
          if (data.length < 2 || data[pos++] !== tag)
            throw new E("tlv.decode: wrong tlv");
          const first = data[pos++];
          const isLong = !!(first & 128);
          let length = 0;
          if (!isLong)
            length = first;
          else {
            const lenLen = first & 127;
            if (!lenLen)
              throw new E("tlv.decode(long): indefinite length not supported");
            if (lenLen > 4)
              throw new E("tlv.decode(long): byte length is too big");
            const lengthBytes = data.subarray(pos, pos + lenLen);
            if (lengthBytes.length !== lenLen)
              throw new E("tlv.decode: length bytes not complete");
            if (lengthBytes[0] === 0)
              throw new E("tlv.decode(long): zero leftmost byte");
            for (const b of lengthBytes)
              length = length << 8 | b;
            pos += lenLen;
            if (length < 128)
              throw new E("tlv.decode(long): not minimal encoding");
          }
          const v = data.subarray(pos, pos + length);
          if (v.length !== length)
            throw new E("tlv.decode: wrong value length");
          return { v, l: data.subarray(pos + length) };
        }
      },
      // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
      // since we always use positive integers here. It must always be empty:
      // - add zero byte if exists
      // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
      _int: {
        encode(num2) {
          const { Err: E } = DER;
          if (num2 < _0n5)
            throw new E("integer: negative integers are not allowed");
          let hex = numberToHexUnpadded(num2);
          if (Number.parseInt(hex[0], 16) & 8)
            hex = "00" + hex;
          if (hex.length & 1)
            throw new E("unexpected DER parsing assertion: unpadded hex");
          return hex;
        },
        decode(data) {
          const { Err: E } = DER;
          if (data[0] & 128)
            throw new E("invalid signature integer: negative");
          if (data[0] === 0 && !(data[1] & 128))
            throw new E("invalid signature integer: unnecessary leading zero");
          return bytesToNumberBE(data);
        }
      },
      toSig(hex) {
        const { Err: E, _int: int, _tlv: tlv } = DER;
        const data = ensureBytes("signature", hex);
        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
        if (seqLeftBytes.length)
          throw new E("invalid signature: left bytes after parsing");
        const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
        const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
        if (sLeftBytes.length)
          throw new E("invalid signature: left bytes after parsing");
        return { r: int.decode(rBytes), s: int.decode(sBytes) };
      },
      hexFromSig(sig) {
        const { _tlv: tlv, _int: int } = DER;
        const rs = tlv.encode(2, int.encode(sig.r));
        const ss = tlv.encode(2, int.encode(sig.s));
        const seq = rs + ss;
        return tlv.encode(48, seq);
      }
    };
    _0n5 = BigInt(0);
    _1n5 = BigInt(1);
    _2n3 = BigInt(2);
    _3n2 = BigInt(3);
    _4n2 = BigInt(4);
  }
});

// node_modules/viem/node_modules/@noble/curves/esm/_shortw_utils.js
function getHash(hash3) {
  return {
    hash: hash3,
    hmac: (key, ...msgs) => hmac(hash3, key, concatBytes(...msgs)),
    randomBytes
  };
}
function createCurve(curveDef, defHash) {
  const create2 = (hash3) => weierstrass({ ...curveDef, ...getHash(hash3) });
  return { ...create2(defHash), create: create2 };
}
var init_shortw_utils = __esm({
  "node_modules/viem/node_modules/@noble/curves/esm/_shortw_utils.js"() {
    "use strict";
    init_hmac();
    init_utils2();
    init_weierstrass();
  }
});

// node_modules/viem/node_modules/@noble/curves/esm/abstract/hash-to-curve.js
function i2osp(value, length) {
  anum(value);
  anum(length);
  if (value < 0 || value >= 1 << 8 * length)
    throw new Error("invalid I2OSP input: " + value);
  const res = Array.from({ length }).fill(0);
  for (let i = length - 1; i >= 0; i--) {
    res[i] = value & 255;
    value >>>= 8;
  }
  return new Uint8Array(res);
}
function strxor(a, b) {
  const arr = new Uint8Array(a.length);
  for (let i = 0; i < a.length; i++) {
    arr[i] = a[i] ^ b[i];
  }
  return arr;
}
function anum(item) {
  if (!Number.isSafeInteger(item))
    throw new Error("number expected");
}
function expand_message_xmd(msg, DST, lenInBytes, H) {
  abytes2(msg);
  abytes2(DST);
  anum(lenInBytes);
  if (DST.length > 255)
    DST = H(concatBytes3(utf8ToBytes2("H2C-OVERSIZE-DST-"), DST));
  const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
  const ell = Math.ceil(lenInBytes / b_in_bytes);
  if (lenInBytes > 65535 || ell > 255)
    throw new Error("expand_message_xmd: invalid lenInBytes");
  const DST_prime = concatBytes3(DST, i2osp(DST.length, 1));
  const Z_pad = i2osp(0, r_in_bytes);
  const l_i_b_str = i2osp(lenInBytes, 2);
  const b = new Array(ell);
  const b_0 = H(concatBytes3(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
  b[0] = H(concatBytes3(b_0, i2osp(1, 1), DST_prime));
  for (let i = 1; i <= ell; i++) {
    const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
    b[i] = H(concatBytes3(...args));
  }
  const pseudo_random_bytes = concatBytes3(...b);
  return pseudo_random_bytes.slice(0, lenInBytes);
}
function expand_message_xof(msg, DST, lenInBytes, k, H) {
  abytes2(msg);
  abytes2(DST);
  anum(lenInBytes);
  if (DST.length > 255) {
    const dkLen = Math.ceil(2 * k / 8);
    DST = H.create({ dkLen }).update(utf8ToBytes2("H2C-OVERSIZE-DST-")).update(DST).digest();
  }
  if (lenInBytes > 65535 || DST.length > 255)
    throw new Error("expand_message_xof: invalid lenInBytes");
  return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest();
}
function hash_to_field(msg, count, options) {
  validateObject(options, {
    DST: "stringOrUint8Array",
    p: "bigint",
    m: "isSafeInteger",
    k: "isSafeInteger",
    hash: "hash"
  });
  const { p, k, m, hash: hash3, expand, DST: _DST } = options;
  abytes2(msg);
  anum(count);
  const DST = typeof _DST === "string" ? utf8ToBytes2(_DST) : _DST;
  const log2p = p.toString(2).length;
  const L = Math.ceil((log2p + k) / 8);
  const len_in_bytes = count * m * L;
  let prb;
  if (expand === "xmd") {
    prb = expand_message_xmd(msg, DST, len_in_bytes, hash3);
  } else if (expand === "xof") {
    prb = expand_message_xof(msg, DST, len_in_bytes, k, hash3);
  } else if (expand === "_internal_pass") {
    prb = msg;
  } else {
    throw new Error('expand must be "xmd" or "xof"');
  }
  const u = new Array(count);
  for (let i = 0; i < count; i++) {
    const e7 = new Array(m);
    for (let j = 0; j < m; j++) {
      const elm_offset = L * (j + i * m);
      const tv = prb.subarray(elm_offset, elm_offset + L);
      e7[j] = mod(os2ip(tv), p);
    }
    u[i] = e7;
  }
  return u;
}
function isogenyMap(field, map) {
  const coeff = map.map((i) => Array.from(i).reverse());
  return (x, y) => {
    const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
    const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
    x = field.mul(xn, xd_inv);
    y = field.mul(y, field.mul(yn, yd_inv));
    return { x, y };
  };
}
function createHasher2(Point3, mapToCurve, defaults) {
  if (typeof mapToCurve !== "function")
    throw new Error("mapToCurve() must be defined");
  function map(num2) {
    return Point3.fromAffine(mapToCurve(num2));
  }
  function clear(initial) {
    const P2 = initial.clearCofactor();
    if (P2.equals(Point3.ZERO))
      return Point3.ZERO;
    P2.assertValidity();
    return P2;
  }
  return {
    defaults,
    // Encodes byte string to elliptic curve.
    // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3
    hashToCurve(msg, options) {
      const u = hash_to_field(msg, 2, { ...defaults, DST: defaults.DST, ...options });
      const u0 = map(u[0]);
      const u1 = map(u[1]);
      return clear(u0.add(u1));
    },
    // Encodes byte string to elliptic curve.
    // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3
    encodeToCurve(msg, options) {
      const u = hash_to_field(msg, 1, { ...defaults, DST: defaults.encodeDST, ...options });
      return clear(map(u[0]));
    },
    // Same as encodeToCurve, but without hash
    mapToCurve(scalars) {
      if (!Array.isArray(scalars))
        throw new Error("expected array of bigints");
      for (const i of scalars)
        if (typeof i !== "bigint")
          throw new Error("expected array of bigints");
      return clear(map(scalars));
    }
  };
}
var os2ip;
var init_hash_to_curve = __esm({
  "node_modules/viem/node_modules/@noble/curves/esm/abstract/hash-to-curve.js"() {
    "use strict";
    init_modular();
    init_utils4();
    os2ip = bytesToNumberBE;
  }
});

// node_modules/viem/node_modules/@noble/curves/esm/secp256k1.js
var secp256k1_exports = {};
__export(secp256k1_exports, {
  encodeToCurve: () => encodeToCurve,
  hashToCurve: () => hashToCurve,
  schnorr: () => schnorr,
  secp256k1: () => secp256k1,
  secp256k1_hasher: () => secp256k1_hasher
});
function sqrtMod(y) {
  const P2 = secp256k1P;
  const _3n7 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
  const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
  const b2 = y * y * y % P2;
  const b3 = b2 * b2 * y % P2;
  const b6 = pow2(b3, _3n7, P2) * b3 % P2;
  const b9 = pow2(b6, _3n7, P2) * b3 % P2;
  const b11 = pow2(b9, _2n4, P2) * b2 % P2;
  const b22 = pow2(b11, _11n, P2) * b11 % P2;
  const b44 = pow2(b22, _22n, P2) * b22 % P2;
  const b88 = pow2(b44, _44n, P2) * b44 % P2;
  const b176 = pow2(b88, _88n, P2) * b88 % P2;
  const b220 = pow2(b176, _44n, P2) * b44 % P2;
  const b223 = pow2(b220, _3n7, P2) * b3 % P2;
  const t1 = pow2(b223, _23n, P2) * b22 % P2;
  const t2 = pow2(t1, _6n, P2) * b2 % P2;
  const root = pow2(t2, _2n4, P2);
  if (!Fpk1.eql(Fpk1.sqr(root), y))
    throw new Error("Cannot find square root");
  return root;
}
function taggedHash(tag, ...messages) {
  let tagP = TAGGED_HASH_PREFIXES[tag];
  if (tagP === void 0) {
    const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));
    tagP = concatBytes3(tagH, tagH);
    TAGGED_HASH_PREFIXES[tag] = tagP;
  }
  return sha256(concatBytes3(tagP, ...messages));
}
function schnorrGetExtPubKey(priv) {
  let d_ = secp256k1.utils.normPrivateKeyToScalar(priv);
  let p = Point.fromPrivateKey(d_);
  const scalar = p.hasEvenY() ? d_ : modN(-d_);
  return { scalar, bytes: pointToBytes(p) };
}
function lift_x(x) {
  aInRange("x", x, _1n6, secp256k1P);
  const xx = modP(x * x);
  const c = modP(xx * x + BigInt(7));
  let y = sqrtMod(c);
  if (y % _2n4 !== _0n6)
    y = modP(-y);
  const p = new Point(x, y, _1n6);
  p.assertValidity();
  return p;
}
function challenge(...args) {
  return modN(num(taggedHash("BIP0340/challenge", ...args)));
}
function schnorrGetPublicKey(privateKey) {
  return schnorrGetExtPubKey(privateKey).bytes;
}
function schnorrSign(message, privateKey, auxRand = randomBytes(32)) {
  const m = ensureBytes("message", message);
  const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey);
  const a = ensureBytes("auxRand", auxRand, 32);
  const t = numTo32b(d ^ num(taggedHash("BIP0340/aux", a)));
  const rand = taggedHash("BIP0340/nonce", t, px, m);
  const k_ = modN(num(rand));
  if (k_ === _0n6)
    throw new Error("sign failed: k is zero");
  const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_);
  const e7 = challenge(rx, px, m);
  const sig = new Uint8Array(64);
  sig.set(rx, 0);
  sig.set(numTo32b(modN(k + e7 * d)), 32);
  if (!schnorrVerify(sig, m, px))
    throw new Error("sign: Invalid signature produced");
  return sig;
}
function schnorrVerify(signature2, message, publicKey) {
  const sig = ensureBytes("signature", signature2, 64);
  const m = ensureBytes("message", message);
  const pub = ensureBytes("publicKey", publicKey, 32);
  try {
    const P2 = lift_x(num(pub));
    const r = num(sig.subarray(0, 32));
    if (!inRange(r, _1n6, secp256k1P))
      return false;
    const s3 = num(sig.subarray(32, 64));
    if (!inRange(s3, _1n6, secp256k1N))
      return false;
    const e7 = challenge(numTo32b(r), pointToBytes(P2), m);
    const R = GmulAdd(P2, s3, modN(-e7));
    if (!R || !R.hasEvenY() || R.toAffine().x !== r)
      return false;
    return true;
  } catch (error) {
    return false;
  }
}
var secp256k1P, secp256k1N, _0n6, _1n6, _2n4, divNearest, Fpk1, secp256k1, TAGGED_HASH_PREFIXES, pointToBytes, numTo32b, modP, modN, Point, GmulAdd, num, schnorr, isoMap, mapSWU, secp256k1_hasher, hashToCurve, encodeToCurve;
var init_secp256k1 = __esm({
  "node_modules/viem/node_modules/@noble/curves/esm/secp256k1.js"() {
    "use strict";
    init_sha2();
    init_utils2();
    init_shortw_utils();
    init_hash_to_curve();
    init_modular();
    init_utils4();
    init_weierstrass();
    secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f");
    secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
    _0n6 = BigInt(0);
    _1n6 = BigInt(1);
    _2n4 = BigInt(2);
    divNearest = (a, b) => (a + b / _2n4) / b;
    Fpk1 = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod });
    secp256k1 = createCurve({
      a: _0n6,
      b: BigInt(7),
      Fp: Fpk1,
      n: secp256k1N,
      Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),
      Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),
      h: BigInt(1),
      lowS: true,
      // Allow only low-S signatures by default in sign() and verify()
      endo: {
        // Endomorphism, see above
        beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
        splitScalar: (k) => {
          const n = secp256k1N;
          const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15");
          const b1 = -_1n6 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3");
          const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");
          const b2 = a1;
          const POW_2_128 = BigInt("0x100000000000000000000000000000000");
          const c1 = divNearest(b2 * k, n);
          const c2 = divNearest(-b1 * k, n);
          let k1 = mod(k - c1 * a1 - c2 * a2, n);
          let k2 = mod(-c1 * b1 - c2 * b2, n);
          const k1neg = k1 > POW_2_128;
          const k2neg = k2 > POW_2_128;
          if (k1neg)
            k1 = n - k1;
          if (k2neg)
            k2 = n - k2;
          if (k1 > POW_2_128 || k2 > POW_2_128) {
            throw new Error("splitScalar: Endomorphism failed, k=" + k);
          }
          return { k1neg, k1, k2neg, k2 };
        }
      }
    }, sha256);
    TAGGED_HASH_PREFIXES = {};
    pointToBytes = (point) => point.toRawBytes(true).slice(1);
    numTo32b = (n) => numberToBytesBE(n, 32);
    modP = (x) => mod(x, secp256k1P);
    modN = (x) => mod(x, secp256k1N);
    Point = /* @__PURE__ */ (() => secp256k1.ProjectivePoint)();
    GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);
    num = bytesToNumberBE;
    schnorr = /* @__PURE__ */ (() => ({
      getPublicKey: schnorrGetPublicKey,
      sign: schnorrSign,
      verify: schnorrVerify,
      utils: {
        randomPrivateKey: secp256k1.utils.randomPrivateKey,
        lift_x,
        pointToBytes,
        numberToBytesBE,
        bytesToNumberBE,
        taggedHash,
        mod
      }
    }))();
    isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [
      // xNum
      [
        "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7",
        "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581",
        "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262",
        "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"
      ],
      // xDen
      [
        "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b",
        "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14",
        "0x0000000000000000000000000000000000000000000000000000000000000001"
        // LAST 1
      ],
      // yNum
      [
        "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c",
        "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3",
        "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931",
        "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"
      ],
      // yDen
      [
        "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b",
        "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573",
        "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f",
        "0x0000000000000000000000000000000000000000000000000000000000000001"
        // LAST 1
      ]
    ].map((i) => i.map((j) => BigInt(j)))))();
    mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, {
      A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),
      B: BigInt("1771"),
      Z: Fpk1.create(BigInt("-11"))
    }))();
    secp256k1_hasher = /* @__PURE__ */ (() => createHasher2(secp256k1.ProjectivePoint, (scalars) => {
      const { x, y } = mapSWU(Fpk1.create(scalars[0]));
      return isoMap(x, y);
    }, {
      DST: "secp256k1_XMD:SHA-256_SSWU_RO_",
      encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_",
      p: Fpk1.ORDER,
      m: 1,
      k: 128,
      expand: "xmd",
      hash: sha256
    }))();
    hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)();
    encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)();
  }
});

// node_modules/viem/_esm/utils/signature/recoverPublicKey.js
async function recoverPublicKey({ hash: hash3, signature: signature2 }) {
  const hashHex = isHex(hash3) ? hash3 : toHex(hash3);
  const { secp256k1: secp256k14 } = await Promise.resolve().then(() => (init_secp256k1(), secp256k1_exports));
  const signature_ = (() => {
    if (typeof signature2 === "object" && "r" in signature2 && "s" in signature2) {
      const { r, s: s3, v, yParity } = signature2;
      const yParityOrV2 = Number(yParity ?? v);
      const recoveryBit2 = toRecoveryBit(yParityOrV2);
      return new secp256k14.Signature(hexToBigInt(r), hexToBigInt(s3)).addRecoveryBit(recoveryBit2);
    }
    const signatureHex = isHex(signature2) ? signature2 : toHex(signature2);
    if (size(signatureHex) !== 65)
      throw new Error("invalid signature length");
    const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`);
    const recoveryBit = toRecoveryBit(yParityOrV);
    return secp256k14.Signature.fromCompact(signatureHex.substring(2, 130)).addRecoveryBit(recoveryBit);
  })();
  const publicKey = signature_.recoverPublicKey(hashHex.substring(2)).toHex(false);
  return `0x${publicKey}`;
}
function toRecoveryBit(yParityOrV) {
  if (yParityOrV === 0 || yParityOrV === 1)
    return yParityOrV;
  if (yParityOrV === 27)
    return 0;
  if (yParityOrV === 28)
    return 1;
  throw new Error("Invalid yParityOrV value");
}
var init_recoverPublicKey = __esm({
  "node_modules/viem/_esm/utils/signature/recoverPublicKey.js"() {
    "use strict";
    init_isHex();
    init_size();
    init_fromHex();
    init_toHex();
  }
});

// node_modules/viem/_esm/utils/signature/recoverAddress.js
async function recoverAddress({ hash: hash3, signature: signature2 }) {
  return publicKeyToAddress(await recoverPublicKey({ hash: hash3, signature: signature2 }));
}
var init_recoverAddress = __esm({
  "node_modules/viem/_esm/utils/signature/recoverAddress.js"() {
    "use strict";
    init_publicKeyToAddress();
    init_recoverPublicKey();
  }
});

// node_modules/viem/_esm/utils/encoding/toRlp.js
function toRlp(bytes, to = "hex") {
  const encodable = getEncodable(bytes);
  const cursor = createCursor(new Uint8Array(encodable.length));
  encodable.encode(cursor);
  if (to === "hex")
    return bytesToHex(cursor.bytes);
  return cursor.bytes;
}
function getEncodable(bytes) {
  if (Array.isArray(bytes))
    return getEncodableList(bytes.map((x) => getEncodable(x)));
  return getEncodableBytes(bytes);
}
function getEncodableList(list) {
  const bodyLength = list.reduce((acc, x) => acc + x.length, 0);
  const sizeOfBodyLength = getSizeOfLength(bodyLength);
  const length = (() => {
    if (bodyLength <= 55)
      return 1 + bodyLength;
    return 1 + sizeOfBodyLength + bodyLength;
  })();
  return {
    length,
    encode(cursor) {
      if (bodyLength <= 55) {
        cursor.pushByte(192 + bodyLength);
      } else {
        cursor.pushByte(192 + 55 + sizeOfBodyLength);
        if (sizeOfBodyLength === 1)
          cursor.pushUint8(bodyLength);
        else if (sizeOfBodyLength === 2)
          cursor.pushUint16(bodyLength);
        else if (sizeOfBodyLength === 3)
          cursor.pushUint24(bodyLength);
        else
          cursor.pushUint32(bodyLength);
      }
      for (const { encode: encode4 } of list) {
        encode4(cursor);
      }
    }
  };
}
function getEncodableBytes(bytesOrHex) {
  const bytes = typeof bytesOrHex === "string" ? hexToBytes(bytesOrHex) : bytesOrHex;
  const sizeOfBytesLength = getSizeOfLength(bytes.length);
  const length = (() => {
    if (bytes.length === 1 && bytes[0] < 128)
      return 1;
    if (bytes.length <= 55)
      return 1 + bytes.length;
    return 1 + sizeOfBytesLength + bytes.length;
  })();
  return {
    length,
    encode(cursor) {
      if (bytes.length === 1 && bytes[0] < 128) {
        cursor.pushBytes(bytes);
      } else if (bytes.length <= 55) {
        cursor.pushByte(128 + bytes.length);
        cursor.pushBytes(bytes);
      } else {
        cursor.pushByte(128 + 55 + sizeOfBytesLength);
        if (sizeOfBytesLength === 1)
          cursor.pushUint8(bytes.length);
        else if (sizeOfBytesLength === 2)
          cursor.pushUint16(bytes.length);
        else if (sizeOfBytesLength === 3)
          cursor.pushUint24(bytes.length);
        else
          cursor.pushUint32(bytes.length);
        cursor.pushBytes(bytes);
      }
    }
  };
}
function getSizeOfLength(length) {
  if (length < 2 ** 8)
    return 1;
  if (length < 2 ** 16)
    return 2;
  if (length < 2 ** 24)
    return 3;
  if (length < 2 ** 32)
    return 4;
  throw new BaseError2("Length is too large.");
}
var init_toRlp = __esm({
  "node_modules/viem/_esm/utils/encoding/toRlp.js"() {
    "use strict";
    init_base();
    init_cursor2();
    init_toBytes();
    init_toHex();
  }
});

// node_modules/viem/_esm/utils/authorization/hashAuthorization.js
function hashAuthorization(parameters) {
  const { chainId, nonce, to } = parameters;
  const address2 = parameters.contractAddress ?? parameters.address;
  const hash3 = keccak256(concatHex([
    "0x05",
    toRlp([
      chainId ? numberToHex(chainId) : "0x",
      address2,
      nonce ? numberToHex(nonce) : "0x"
    ])
  ]));
  if (to === "bytes")
    return hexToBytes(hash3);
  return hash3;
}
var init_hashAuthorization = __esm({
  "node_modules/viem/_esm/utils/authorization/hashAuthorization.js"() {
    "use strict";
    init_concat();
    init_toBytes();
    init_toHex();
    init_toRlp();
    init_keccak256();
  }
});

// node_modules/viem/_esm/utils/authorization/recoverAuthorizationAddress.js
async function recoverAuthorizationAddress(parameters) {
  const { authorization, signature: signature2 } = parameters;
  return recoverAddress({
    hash: hashAuthorization(authorization),
    signature: signature2 ?? authorization
  });
}
var init_recoverAuthorizationAddress = __esm({
  "node_modules/viem/_esm/utils/authorization/recoverAuthorizationAddress.js"() {
    "use strict";
    init_recoverAddress();
    init_hashAuthorization();
  }
});

// node_modules/viem/_esm/errors/estimateGas.js
var EstimateGasExecutionError;
var init_estimateGas = __esm({
  "node_modules/viem/_esm/errors/estimateGas.js"() {
    "use strict";
    init_formatEther();
    init_formatGwei();
    init_base();
    init_transaction();
    EstimateGasExecutionError = class extends BaseError2 {
      constructor(cause, { account, docsPath: docsPath8, chain: chain3, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value }) {
        const prettyArgs = prettyPrint({
          from: account?.address,
          to,
          value: typeof value !== "undefined" && `${formatEther(value)} ${chain3?.nativeCurrency?.symbol || "ETH"}`,
          data,
          gas,
          gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
          maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
          maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
          nonce
        });
        super(cause.shortMessage, {
          cause,
          docsPath: docsPath8,
          metaMessages: [
            ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
            "Estimate Gas Arguments:",
            prettyArgs
          ].filter(Boolean),
          name: "EstimateGasExecutionError"
        });
        Object.defineProperty(this, "cause", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.cause = cause;
      }
    };
  }
});

// node_modules/viem/_esm/errors/node.js
var ExecutionRevertedError, FeeCapTooHighError, FeeCapTooLowError, NonceTooHighError, NonceTooLowError, NonceMaxValueError, InsufficientFundsError, IntrinsicGasTooHighError, IntrinsicGasTooLowError, TransactionTypeNotSupportedError, TipAboveFeeCapError, UnknownNodeError;
var init_node = __esm({
  "node_modules/viem/_esm/errors/node.js"() {
    "use strict";
    init_formatGwei();
    init_base();
    ExecutionRevertedError = class extends BaseError2 {
      constructor({ cause, message } = {}) {
        const reason = message?.replace("execution reverted: ", "")?.replace("execution reverted", "");
        super(`Execution reverted ${reason ? `with reason: ${reason}` : "for an unknown reason"}.`, {
          cause,
          name: "ExecutionRevertedError"
        });
      }
    };
    Object.defineProperty(ExecutionRevertedError, "code", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: 3
    });
    Object.defineProperty(ExecutionRevertedError, "nodeMessage", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: /execution reverted|gas required exceeds allowance/
    });
    FeeCapTooHighError = class extends BaseError2 {
      constructor({ cause, maxFeePerGas } = {}) {
        super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}) cannot be higher than the maximum allowed value (2^256-1).`, {
          cause,
          name: "FeeCapTooHighError"
        });
      }
    };
    Object.defineProperty(FeeCapTooHighError, "nodeMessage", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: /max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/
    });
    FeeCapTooLowError = class extends BaseError2 {
      constructor({ cause, maxFeePerGas } = {}) {
        super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ""} gwei) cannot be lower than the block base fee.`, {
          cause,
          name: "FeeCapTooLowError"
        });
      }
    };
    Object.defineProperty(FeeCapTooLowError, "nodeMessage", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/
    });
    NonceTooHighError = class extends BaseError2 {
      constructor({ cause, nonce } = {}) {
        super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is higher than the next one expected.`, { cause, name: "NonceTooHighError" });
      }
    };
    Object.defineProperty(NonceTooHighError, "nodeMessage", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: /nonce too high/
    });
    NonceTooLowError = class extends BaseError2 {
      constructor({ cause, nonce } = {}) {
        super([
          `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is lower than the current nonce of the account.`,
          "Try increasing the nonce or find the latest nonce with `getTransactionCount`."
        ].join("\n"), { cause, name: "NonceTooLowError" });
      }
    };
    Object.defineProperty(NonceTooLowError, "nodeMessage", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: /nonce too low|transaction already imported|already known/
    });
    NonceMaxValueError = class extends BaseError2 {
      constructor({ cause, nonce } = {}) {
        super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}exceeds the maximum allowed nonce.`, { cause, name: "NonceMaxValueError" });
      }
    };
    Object.defineProperty(NonceMaxValueError, "nodeMessage", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: /nonce has max value/
    });
    InsufficientFundsError = class extends BaseError2 {
      constructor({ cause } = {}) {
        super([
          "The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."
        ].join("\n"), {
          cause,
          metaMessages: [
            "This error could arise when the account does not have enough funds to:",
            " - pay for the total gas fee,",
            " - pay for the value to send.",
            " ",
            "The cost of the transaction is calculated as `gas * gas fee + value`, where:",
            " - `gas` is the amount of gas needed for transaction to execute,",
            " - `gas fee` is the gas fee,",
            " - `value` is the amount of ether to send to the recipient."
          ],
          name: "InsufficientFundsError"
        });
      }
    };
    Object.defineProperty(InsufficientFundsError, "nodeMessage", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: /insufficient funds|exceeds transaction sender account balance/
    });
    IntrinsicGasTooHighError = class extends BaseError2 {
      constructor({ cause, gas } = {}) {
        super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction exceeds the limit allowed for the block.`, {
          cause,
          name: "IntrinsicGasTooHighError"
        });
      }
    };
    Object.defineProperty(IntrinsicGasTooHighError, "nodeMessage", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: /intrinsic gas too high|gas limit reached/
    });
    IntrinsicGasTooLowError = class extends BaseError2 {
      constructor({ cause, gas } = {}) {
        super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction is too low.`, {
          cause,
          name: "IntrinsicGasTooLowError"
        });
      }
    };
    Object.defineProperty(IntrinsicGasTooLowError, "nodeMessage", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: /intrinsic gas too low/
    });
    TransactionTypeNotSupportedError = class extends BaseError2 {
      constructor({ cause }) {
        super("The transaction type is not supported for this chain.", {
          cause,
          name: "TransactionTypeNotSupportedError"
        });
      }
    };
    Object.defineProperty(TransactionTypeNotSupportedError, "nodeMessage", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: /transaction type not valid/
    });
    TipAboveFeeCapError = class extends BaseError2 {
      constructor({ cause, maxPriorityFeePerGas, maxFeePerGas } = {}) {
        super([
          `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei` : ""}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}).`
        ].join("\n"), {
          cause,
          name: "TipAboveFeeCapError"
        });
      }
    };
    Object.defineProperty(TipAboveFeeCapError, "nodeMessage", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: /max priority fee per gas higher than max fee per gas|tip higher than fee cap/
    });
    UnknownNodeError = class extends BaseError2 {
      constructor({ cause }) {
        super(`An error occurred while executing: ${cause?.shortMessage}`, {
          cause,
          name: "UnknownNodeError"
        });
      }
    };
  }
});

// node_modules/viem/_esm/utils/errors/getNodeError.js
function getNodeError(err, args) {
  const message = (err.details || "").toLowerCase();
  const executionRevertedError = err instanceof BaseError2 ? err.walk((e7) => e7?.code === ExecutionRevertedError.code) : err;
  if (executionRevertedError instanceof BaseError2)
    return new ExecutionRevertedError({
      cause: err,
      message: executionRevertedError.details
    });
  if (ExecutionRevertedError.nodeMessage.test(message))
    return new ExecutionRevertedError({
      cause: err,
      message: err.details
    });
  if (FeeCapTooHighError.nodeMessage.test(message))
    return new FeeCapTooHighError({
      cause: err,
      maxFeePerGas: args?.maxFeePerGas
    });
  if (FeeCapTooLowError.nodeMessage.test(message))
    return new FeeCapTooLowError({
      cause: err,
      maxFeePerGas: args?.maxFeePerGas
    });
  if (NonceTooHighError.nodeMessage.test(message))
    return new NonceTooHighError({ cause: err, nonce: args?.nonce });
  if (NonceTooLowError.nodeMessage.test(message))
    return new NonceTooLowError({ cause: err, nonce: args?.nonce });
  if (NonceMaxValueError.nodeMessage.test(message))
    return new NonceMaxValueError({ cause: err, nonce: args?.nonce });
  if (InsufficientFundsError.nodeMessage.test(message))
    return new InsufficientFundsError({ cause: err });
  if (IntrinsicGasTooHighError.nodeMessage.test(message))
    return new IntrinsicGasTooHighError({ cause: err, gas: args?.gas });
  if (IntrinsicGasTooLowError.nodeMessage.test(message))
    return new IntrinsicGasTooLowError({ cause: err, gas: args?.gas });
  if (TransactionTypeNotSupportedError.nodeMessage.test(message))
    return new TransactionTypeNotSupportedError({ cause: err });
  if (TipAboveFeeCapError.nodeMessage.test(message))
    return new TipAboveFeeCapError({
      cause: err,
      maxFeePerGas: args?.maxFeePerGas,
      maxPriorityFeePerGas: args?.maxPriorityFeePerGas
    });
  return new UnknownNodeError({
    cause: err
  });
}
var init_getNodeError = __esm({
  "node_modules/viem/_esm/utils/errors/getNodeError.js"() {
    "use strict";
    init_base();
    init_node();
  }
});

// node_modules/viem/_esm/utils/errors/getEstimateGasError.js
function getEstimateGasError(err, { docsPath: docsPath8, ...args }) {
  const cause = (() => {
    const cause2 = getNodeError(err, args);
    if (cause2 instanceof UnknownNodeError)
      return err;
    return cause2;
  })();
  return new EstimateGasExecutionError(cause, {
    docsPath: docsPath8,
    ...args
  });
}
var init_getEstimateGasError = __esm({
  "node_modules/viem/_esm/utils/errors/getEstimateGasError.js"() {
    "use strict";
    init_estimateGas();
    init_node();
    init_getNodeError();
  }
});

// node_modules/viem/_esm/utils/formatters/extract.js
function extract(value_, { format }) {
  if (!format)
    return {};
  const value = {};
  function extract_(formatted2) {
    const keys = Object.keys(formatted2);
    for (const key of keys) {
      if (key in value_)
        value[key] = value_[key];
      if (formatted2[key] && typeof formatted2[key] === "object" && !Array.isArray(formatted2[key]))
        extract_(formatted2[key]);
    }
  }
  const formatted = format(value_ || {});
  extract_(formatted);
  return value;
}
var init_extract = __esm({
  "node_modules/viem/_esm/utils/formatters/extract.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/utils/formatters/formatter.js
function defineFormatter(type, format) {
  return ({ exclude, format: overrides }) => {
    return {
      exclude,
      format: (args, action) => {
        const formatted = format(args, action);
        if (exclude) {
          for (const key of exclude) {
            delete formatted[key];
          }
        }
        return {
          ...formatted,
          ...overrides(args, action)
        };
      },
      type
    };
  };
}
var init_formatter = __esm({
  "node_modules/viem/_esm/utils/formatters/formatter.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/utils/formatters/transactionRequest.js
function formatTransactionRequest(request, _) {
  const rpcRequest = {};
  if (typeof request.authorizationList !== "undefined")
    rpcRequest.authorizationList = formatAuthorizationList(request.authorizationList);
  if (typeof request.accessList !== "undefined")
    rpcRequest.accessList = request.accessList;
  if (typeof request.blobVersionedHashes !== "undefined")
    rpcRequest.blobVersionedHashes = request.blobVersionedHashes;
  if (typeof request.blobs !== "undefined") {
    if (typeof request.blobs[0] !== "string")
      rpcRequest.blobs = request.blobs.map((x) => bytesToHex(x));
    else
      rpcRequest.blobs = request.blobs;
  }
  if (typeof request.data !== "undefined")
    rpcRequest.data = request.data;
  if (request.account)
    rpcRequest.from = request.account.address;
  if (typeof request.from !== "undefined")
    rpcRequest.from = request.from;
  if (typeof request.gas !== "undefined")
    rpcRequest.gas = numberToHex(request.gas);
  if (typeof request.gasPrice !== "undefined")
    rpcRequest.gasPrice = numberToHex(request.gasPrice);
  if (typeof request.maxFeePerBlobGas !== "undefined")
    rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas);
  if (typeof request.maxFeePerGas !== "undefined")
    rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas);
  if (typeof request.maxPriorityFeePerGas !== "undefined")
    rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas);
  if (typeof request.nonce !== "undefined")
    rpcRequest.nonce = numberToHex(request.nonce);
  if (typeof request.to !== "undefined")
    rpcRequest.to = request.to;
  if (typeof request.type !== "undefined")
    rpcRequest.type = rpcTransactionType[request.type];
  if (typeof request.value !== "undefined")
    rpcRequest.value = numberToHex(request.value);
  return rpcRequest;
}
function formatAuthorizationList(authorizationList) {
  return authorizationList.map((authorization) => ({
    address: authorization.address,
    r: authorization.r ? numberToHex(BigInt(authorization.r)) : authorization.r,
    s: authorization.s ? numberToHex(BigInt(authorization.s)) : authorization.s,
    chainId: numberToHex(authorization.chainId),
    nonce: numberToHex(authorization.nonce),
    ...typeof authorization.yParity !== "undefined" ? { yParity: numberToHex(authorization.yParity) } : {},
    ...typeof authorization.v !== "undefined" && typeof authorization.yParity === "undefined" ? { v: numberToHex(authorization.v) } : {}
  }));
}
var rpcTransactionType;
var init_transactionRequest = __esm({
  "node_modules/viem/_esm/utils/formatters/transactionRequest.js"() {
    "use strict";
    init_toHex();
    rpcTransactionType = {
      legacy: "0x0",
      eip2930: "0x1",
      eip1559: "0x2",
      eip4844: "0x3",
      eip7702: "0x4"
    };
  }
});

// node_modules/viem/_esm/utils/stateOverride.js
function serializeStateMapping(stateMapping) {
  if (!stateMapping || stateMapping.length === 0)
    return void 0;
  return stateMapping.reduce((acc, { slot, value }) => {
    if (slot.length !== 66)
      throw new InvalidBytesLengthError({
        size: slot.length,
        targetSize: 66,
        type: "hex"
      });
    if (value.length !== 66)
      throw new InvalidBytesLengthError({
        size: value.length,
        targetSize: 66,
        type: "hex"
      });
    acc[slot] = value;
    return acc;
  }, {});
}
function serializeAccountStateOverride(parameters) {
  const { balance, nonce, state, stateDiff, code } = parameters;
  const rpcAccountStateOverride = {};
  if (code !== void 0)
    rpcAccountStateOverride.code = code;
  if (balance !== void 0)
    rpcAccountStateOverride.balance = numberToHex(balance);
  if (nonce !== void 0)
    rpcAccountStateOverride.nonce = numberToHex(nonce);
  if (state !== void 0)
    rpcAccountStateOverride.state = serializeStateMapping(state);
  if (stateDiff !== void 0) {
    if (rpcAccountStateOverride.state)
      throw new StateAssignmentConflictError();
    rpcAccountStateOverride.stateDiff = serializeStateMapping(stateDiff);
  }
  return rpcAccountStateOverride;
}
function serializeStateOverride(parameters) {
  if (!parameters)
    return void 0;
  const rpcStateOverride = {};
  for (const { address: address2, ...accountState } of parameters) {
    if (!isAddress(address2, { strict: false }))
      throw new InvalidAddressError({ address: address2 });
    if (rpcStateOverride[address2])
      throw new AccountStateConflictError({ address: address2 });
    rpcStateOverride[address2] = serializeAccountStateOverride(accountState);
  }
  return rpcStateOverride;
}
var init_stateOverride2 = __esm({
  "node_modules/viem/_esm/utils/stateOverride.js"() {
    "use strict";
    init_address();
    init_data();
    init_stateOverride();
    init_isAddress();
    init_toHex();
  }
});

// node_modules/viem/_esm/constants/number.js
var maxInt8, maxInt16, maxInt24, maxInt32, maxInt40, maxInt48, maxInt56, maxInt64, maxInt72, maxInt80, maxInt88, maxInt96, maxInt104, maxInt112, maxInt120, maxInt128, maxInt136, maxInt144, maxInt152, maxInt160, maxInt168, maxInt176, maxInt184, maxInt192, maxInt200, maxInt208, maxInt216, maxInt224, maxInt232, maxInt240, maxInt248, maxInt256, minInt8, minInt16, minInt24, minInt32, minInt40, minInt48, minInt56, minInt64, minInt72, minInt80, minInt88, minInt96, minInt104, minInt112, minInt120, minInt128, minInt136, minInt144, minInt152, minInt160, minInt168, minInt176, minInt184, minInt192, minInt200, minInt208, minInt216, minInt224, minInt232, minInt240, minInt248, minInt256, maxUint8, maxUint16, maxUint24, maxUint32, maxUint40, maxUint48, maxUint56, maxUint64, maxUint72, maxUint80, maxUint88, maxUint96, maxUint104, maxUint112, maxUint120, maxUint128, maxUint136, maxUint144, maxUint152, maxUint160, maxUint168, maxUint176, maxUint184, maxUint192, maxUint200, maxUint208, maxUint216, maxUint224, maxUint232, maxUint240, maxUint248, maxUint256;
var init_number = __esm({
  "node_modules/viem/_esm/constants/number.js"() {
    "use strict";
    maxInt8 = 2n ** (8n - 1n) - 1n;
    maxInt16 = 2n ** (16n - 1n) - 1n;
    maxInt24 = 2n ** (24n - 1n) - 1n;
    maxInt32 = 2n ** (32n - 1n) - 1n;
    maxInt40 = 2n ** (40n - 1n) - 1n;
    maxInt48 = 2n ** (48n - 1n) - 1n;
    maxInt56 = 2n ** (56n - 1n) - 1n;
    maxInt64 = 2n ** (64n - 1n) - 1n;
    maxInt72 = 2n ** (72n - 1n) - 1n;
    maxInt80 = 2n ** (80n - 1n) - 1n;
    maxInt88 = 2n ** (88n - 1n) - 1n;
    maxInt96 = 2n ** (96n - 1n) - 1n;
    maxInt104 = 2n ** (104n - 1n) - 1n;
    maxInt112 = 2n ** (112n - 1n) - 1n;
    maxInt120 = 2n ** (120n - 1n) - 1n;
    maxInt128 = 2n ** (128n - 1n) - 1n;
    maxInt136 = 2n ** (136n - 1n) - 1n;
    maxInt144 = 2n ** (144n - 1n) - 1n;
    maxInt152 = 2n ** (152n - 1n) - 1n;
    maxInt160 = 2n ** (160n - 1n) - 1n;
    maxInt168 = 2n ** (168n - 1n) - 1n;
    maxInt176 = 2n ** (176n - 1n) - 1n;
    maxInt184 = 2n ** (184n - 1n) - 1n;
    maxInt192 = 2n ** (192n - 1n) - 1n;
    maxInt200 = 2n ** (200n - 1n) - 1n;
    maxInt208 = 2n ** (208n - 1n) - 1n;
    maxInt216 = 2n ** (216n - 1n) - 1n;
    maxInt224 = 2n ** (224n - 1n) - 1n;
    maxInt232 = 2n ** (232n - 1n) - 1n;
    maxInt240 = 2n ** (240n - 1n) - 1n;
    maxInt248 = 2n ** (248n - 1n) - 1n;
    maxInt256 = 2n ** (256n - 1n) - 1n;
    minInt8 = -(2n ** (8n - 1n));
    minInt16 = -(2n ** (16n - 1n));
    minInt24 = -(2n ** (24n - 1n));
    minInt32 = -(2n ** (32n - 1n));
    minInt40 = -(2n ** (40n - 1n));
    minInt48 = -(2n ** (48n - 1n));
    minInt56 = -(2n ** (56n - 1n));
    minInt64 = -(2n ** (64n - 1n));
    minInt72 = -(2n ** (72n - 1n));
    minInt80 = -(2n ** (80n - 1n));
    minInt88 = -(2n ** (88n - 1n));
    minInt96 = -(2n ** (96n - 1n));
    minInt104 = -(2n ** (104n - 1n));
    minInt112 = -(2n ** (112n - 1n));
    minInt120 = -(2n ** (120n - 1n));
    minInt128 = -(2n ** (128n - 1n));
    minInt136 = -(2n ** (136n - 1n));
    minInt144 = -(2n ** (144n - 1n));
    minInt152 = -(2n ** (152n - 1n));
    minInt160 = -(2n ** (160n - 1n));
    minInt168 = -(2n ** (168n - 1n));
    minInt176 = -(2n ** (176n - 1n));
    minInt184 = -(2n ** (184n - 1n));
    minInt192 = -(2n ** (192n - 1n));
    minInt200 = -(2n ** (200n - 1n));
    minInt208 = -(2n ** (208n - 1n));
    minInt216 = -(2n ** (216n - 1n));
    minInt224 = -(2n ** (224n - 1n));
    minInt232 = -(2n ** (232n - 1n));
    minInt240 = -(2n ** (240n - 1n));
    minInt248 = -(2n ** (248n - 1n));
    minInt256 = -(2n ** (256n - 1n));
    maxUint8 = 2n ** 8n - 1n;
    maxUint16 = 2n ** 16n - 1n;
    maxUint24 = 2n ** 24n - 1n;
    maxUint32 = 2n ** 32n - 1n;
    maxUint40 = 2n ** 40n - 1n;
    maxUint48 = 2n ** 48n - 1n;
    maxUint56 = 2n ** 56n - 1n;
    maxUint64 = 2n ** 64n - 1n;
    maxUint72 = 2n ** 72n - 1n;
    maxUint80 = 2n ** 80n - 1n;
    maxUint88 = 2n ** 88n - 1n;
    maxUint96 = 2n ** 96n - 1n;
    maxUint104 = 2n ** 104n - 1n;
    maxUint112 = 2n ** 112n - 1n;
    maxUint120 = 2n ** 120n - 1n;
    maxUint128 = 2n ** 128n - 1n;
    maxUint136 = 2n ** 136n - 1n;
    maxUint144 = 2n ** 144n - 1n;
    maxUint152 = 2n ** 152n - 1n;
    maxUint160 = 2n ** 160n - 1n;
    maxUint168 = 2n ** 168n - 1n;
    maxUint176 = 2n ** 176n - 1n;
    maxUint184 = 2n ** 184n - 1n;
    maxUint192 = 2n ** 192n - 1n;
    maxUint200 = 2n ** 200n - 1n;
    maxUint208 = 2n ** 208n - 1n;
    maxUint216 = 2n ** 216n - 1n;
    maxUint224 = 2n ** 224n - 1n;
    maxUint232 = 2n ** 232n - 1n;
    maxUint240 = 2n ** 240n - 1n;
    maxUint248 = 2n ** 248n - 1n;
    maxUint256 = 2n ** 256n - 1n;
  }
});

// node_modules/viem/_esm/utils/transaction/assertRequest.js
function assertRequest(args) {
  const { account: account_, maxFeePerGas, maxPriorityFeePerGas, to } = args;
  const account = account_ ? parseAccount(account_) : void 0;
  if (account && !isAddress(account.address))
    throw new InvalidAddressError({ address: account.address });
  if (to && !isAddress(to))
    throw new InvalidAddressError({ address: to });
  if (maxFeePerGas && maxFeePerGas > maxUint256)
    throw new FeeCapTooHighError({ maxFeePerGas });
  if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas)
    throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });
}
var init_assertRequest = __esm({
  "node_modules/viem/_esm/utils/transaction/assertRequest.js"() {
    "use strict";
    init_parseAccount();
    init_number();
    init_address();
    init_node();
    init_isAddress();
  }
});

// node_modules/viem/_esm/errors/fee.js
var BaseFeeScalarError, Eip1559FeesNotSupportedError, MaxFeePerGasTooLowError;
var init_fee = __esm({
  "node_modules/viem/_esm/errors/fee.js"() {
    "use strict";
    init_formatGwei();
    init_base();
    BaseFeeScalarError = class extends BaseError2 {
      constructor() {
        super("`baseFeeMultiplier` must be greater than 1.", {
          name: "BaseFeeScalarError"
        });
      }
    };
    Eip1559FeesNotSupportedError = class extends BaseError2 {
      constructor() {
        super("Chain does not support EIP-1559 fees.", {
          name: "Eip1559FeesNotSupportedError"
        });
      }
    };
    MaxFeePerGasTooLowError = class extends BaseError2 {
      constructor({ maxPriorityFeePerGas }) {
        super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${formatGwei(maxPriorityFeePerGas)} gwei).`, { name: "MaxFeePerGasTooLowError" });
      }
    };
  }
});

// node_modules/viem/_esm/errors/block.js
var BlockNotFoundError;
var init_block = __esm({
  "node_modules/viem/_esm/errors/block.js"() {
    "use strict";
    init_base();
    BlockNotFoundError = class extends BaseError2 {
      constructor({ blockHash, blockNumber }) {
        let identifier = "Block";
        if (blockHash)
          identifier = `Block at hash "${blockHash}"`;
        if (blockNumber)
          identifier = `Block at number "${blockNumber}"`;
        super(`${identifier} could not be found.`, { name: "BlockNotFoundError" });
      }
    };
  }
});

// node_modules/viem/_esm/utils/formatters/transaction.js
function formatTransaction(transaction, _) {
  const transaction_ = {
    ...transaction,
    blockHash: transaction.blockHash ? transaction.blockHash : null,
    blockNumber: transaction.blockNumber ? BigInt(transaction.blockNumber) : null,
    ...transaction.blockTimestamp != null && {
      blockTimestamp: BigInt(transaction.blockTimestamp)
    },
    chainId: transaction.chainId ? hexToNumber(transaction.chainId) : void 0,
    gas: transaction.gas ? BigInt(transaction.gas) : void 0,
    gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : void 0,
    maxFeePerBlobGas: transaction.maxFeePerBlobGas ? BigInt(transaction.maxFeePerBlobGas) : void 0,
    maxFeePerGas: transaction.maxFeePerGas ? BigInt(transaction.maxFeePerGas) : void 0,
    maxPriorityFeePerGas: transaction.maxPriorityFeePerGas ? BigInt(transaction.maxPriorityFeePerGas) : void 0,
    nonce: transaction.nonce ? hexToNumber(transaction.nonce) : void 0,
    to: transaction.to ? transaction.to : null,
    transactionIndex: transaction.transactionIndex ? Number(transaction.transactionIndex) : null,
    type: transaction.type ? transactionType[transaction.type] : void 0,
    typeHex: transaction.type ? transaction.type : void 0,
    value: transaction.value ? BigInt(transaction.value) : void 0,
    v: transaction.v ? BigInt(transaction.v) : void 0
  };
  if (transaction.authorizationList)
    transaction_.authorizationList = formatAuthorizationList2(transaction.authorizationList);
  transaction_.yParity = (() => {
    if (transaction.yParity)
      return Number(transaction.yParity);
    if (typeof transaction_.v === "bigint") {
      if (transaction_.v === 0n || transaction_.v === 27n)
        return 0;
      if (transaction_.v === 1n || transaction_.v === 28n)
        return 1;
      if (transaction_.v >= 35n)
        return transaction_.v % 2n === 0n ? 1 : 0;
    }
    return void 0;
  })();
  if (transaction_.type === "legacy") {
    delete transaction_.accessList;
    delete transaction_.maxFeePerBlobGas;
    delete transaction_.maxFeePerGas;
    delete transaction_.maxPriorityFeePerGas;
    delete transaction_.yParity;
  }
  if (transaction_.type === "eip2930") {
    delete transaction_.maxFeePerBlobGas;
    delete transaction_.maxFeePerGas;
    delete transaction_.maxPriorityFeePerGas;
  }
  if (transaction_.type === "eip1559")
    delete transaction_.maxFeePerBlobGas;
  return transaction_;
}
function formatAuthorizationList2(authorizationList) {
  return authorizationList.map((authorization) => ({
    address: authorization.address,
    chainId: Number(authorization.chainId),
    nonce: Number(authorization.nonce),
    r: authorization.r,
    s: authorization.s,
    yParity: Number(authorization.yParity)
  }));
}
var transactionType, defineTransaction;
var init_transaction2 = __esm({
  "node_modules/viem/_esm/utils/formatters/transaction.js"() {
    "use strict";
    init_fromHex();
    init_formatter();
    transactionType = {
      "0x0": "legacy",
      "0x1": "eip2930",
      "0x2": "eip1559",
      "0x3": "eip4844",
      "0x4": "eip7702"
    };
    defineTransaction = /* @__PURE__ */ defineFormatter("transaction", formatTransaction);
  }
});

// node_modules/viem/_esm/utils/formatters/block.js
function formatBlock(block, _) {
  const transactions = (block.transactions ?? []).map((transaction) => {
    if (typeof transaction === "string")
      return transaction;
    return formatTransaction(transaction);
  });
  return {
    ...block,
    baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null,
    blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : void 0,
    difficulty: block.difficulty ? BigInt(block.difficulty) : void 0,
    excessBlobGas: block.excessBlobGas ? BigInt(block.excessBlobGas) : void 0,
    gasLimit: block.gasLimit ? BigInt(block.gasLimit) : void 0,
    gasUsed: block.gasUsed ? BigInt(block.gasUsed) : void 0,
    hash: block.hash ? block.hash : null,
    logsBloom: block.logsBloom ? block.logsBloom : null,
    nonce: block.nonce ? block.nonce : null,
    number: block.number ? BigInt(block.number) : null,
    size: block.size ? BigInt(block.size) : void 0,
    timestamp: block.timestamp ? BigInt(block.timestamp) : void 0,
    transactions,
    totalDifficulty: block.totalDifficulty ? BigInt(block.totalDifficulty) : null
  };
}
var defineBlock;
var init_block2 = __esm({
  "node_modules/viem/_esm/utils/formatters/block.js"() {
    "use strict";
    init_formatter();
    init_transaction2();
    defineBlock = /* @__PURE__ */ defineFormatter("block", formatBlock);
  }
});

// node_modules/viem/_esm/actions/public/getBlock.js
async function getBlock(client, { blockHash, blockNumber, blockTag = client.experimental_blockTag ?? "latest", includeTransactions: includeTransactions_ } = {}) {
  const includeTransactions = includeTransactions_ ?? false;
  const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
  let block = null;
  if (blockHash) {
    block = await client.request({
      method: "eth_getBlockByHash",
      params: [blockHash, includeTransactions]
    }, { dedupe: true });
  } else {
    block = await client.request({
      method: "eth_getBlockByNumber",
      params: [blockNumberHex || blockTag, includeTransactions]
    }, { dedupe: Boolean(blockNumberHex) });
  }
  if (!block)
    throw new BlockNotFoundError({ blockHash, blockNumber });
  const format = client.chain?.formatters?.block?.format || formatBlock;
  return format(block, "getBlock");
}
var init_getBlock = __esm({
  "node_modules/viem/_esm/actions/public/getBlock.js"() {
    "use strict";
    init_block();
    init_toHex();
    init_block2();
  }
});

// node_modules/viem/_esm/actions/public/getGasPrice.js
async function getGasPrice(client) {
  const gasPrice = await client.request({
    method: "eth_gasPrice"
  });
  return BigInt(gasPrice);
}
var init_getGasPrice = __esm({
  "node_modules/viem/_esm/actions/public/getGasPrice.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/actions/public/estimateMaxPriorityFeePerGas.js
async function estimateMaxPriorityFeePerGas(client, args) {
  return internal_estimateMaxPriorityFeePerGas(client, args);
}
async function internal_estimateMaxPriorityFeePerGas(client, args) {
  const { block: block_, chain: chain3 = client.chain, request } = args || {};
  try {
    const maxPriorityFeePerGas = chain3?.fees?.maxPriorityFeePerGas ?? chain3?.fees?.defaultPriorityFee;
    if (typeof maxPriorityFeePerGas === "function") {
      const block = block_ || await getAction(client, getBlock, "getBlock")({});
      const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({
        block,
        client,
        request
      });
      if (maxPriorityFeePerGas_ === null)
        throw new Error();
      return maxPriorityFeePerGas_;
    }
    if (typeof maxPriorityFeePerGas !== "undefined")
      return maxPriorityFeePerGas;
    const maxPriorityFeePerGasHex = await client.request({
      method: "eth_maxPriorityFeePerGas"
    });
    return hexToBigInt(maxPriorityFeePerGasHex);
  } catch {
    const [block, gasPrice] = await Promise.all([
      block_ ? Promise.resolve(block_) : getAction(client, getBlock, "getBlock")({}),
      getAction(client, getGasPrice, "getGasPrice")({})
    ]);
    if (typeof block.baseFeePerGas !== "bigint")
      throw new Eip1559FeesNotSupportedError();
    const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas;
    if (maxPriorityFeePerGas < 0n)
      return 0n;
    return maxPriorityFeePerGas;
  }
}
var init_estimateMaxPriorityFeePerGas = __esm({
  "node_modules/viem/_esm/actions/public/estimateMaxPriorityFeePerGas.js"() {
    "use strict";
    init_fee();
    init_fromHex();
    init_getAction();
    init_getBlock();
    init_getGasPrice();
  }
});

// node_modules/viem/_esm/actions/public/estimateFeesPerGas.js
async function estimateFeesPerGas(client, args) {
  return internal_estimateFeesPerGas(client, args);
}
async function internal_estimateFeesPerGas(client, args) {
  const { block: block_, chain: chain3 = client.chain, request, type = "eip1559" } = args || {};
  const baseFeeMultiplier = await (async () => {
    if (typeof chain3?.fees?.baseFeeMultiplier === "function")
      return chain3.fees.baseFeeMultiplier({
        block: block_,
        client,
        request
      });
    return chain3?.fees?.baseFeeMultiplier ?? 1.2;
  })();
  if (baseFeeMultiplier < 1)
    throw new BaseFeeScalarError();
  const decimals = baseFeeMultiplier.toString().split(".")[1]?.length ?? 0;
  const denominator = 10 ** decimals;
  const multiply = (base2) => base2 * BigInt(Math.ceil(baseFeeMultiplier * denominator)) / BigInt(denominator);
  const block = block_ ? block_ : await getAction(client, getBlock, "getBlock")({});
  if (typeof chain3?.fees?.estimateFeesPerGas === "function") {
    const fees = await chain3.fees.estimateFeesPerGas({
      block: block_,
      client,
      multiply,
      request,
      type
    });
    if (fees !== null)
      return fees;
  }
  if (type === "eip1559") {
    if (typeof block.baseFeePerGas !== "bigint")
      throw new Eip1559FeesNotSupportedError();
    const maxPriorityFeePerGas = typeof request?.maxPriorityFeePerGas === "bigint" ? request.maxPriorityFeePerGas : await internal_estimateMaxPriorityFeePerGas(client, {
      block,
      chain: chain3,
      request
    });
    const baseFeePerGas = multiply(block.baseFeePerGas);
    const maxFeePerGas = request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas;
    return {
      maxFeePerGas,
      maxPriorityFeePerGas
    };
  }
  const gasPrice = request?.gasPrice ?? multiply(await getAction(client, getGasPrice, "getGasPrice")({}));
  return {
    gasPrice
  };
}
var init_estimateFeesPerGas = __esm({
  "node_modules/viem/_esm/actions/public/estimateFeesPerGas.js"() {
    "use strict";
    init_fee();
    init_getAction();
    init_estimateMaxPriorityFeePerGas();
    init_getBlock();
    init_getGasPrice();
  }
});

// node_modules/viem/_esm/actions/public/getTransactionCount.js
async function getTransactionCount(client, { address: address2, blockTag = "latest", blockNumber }) {
  const count = await client.request({
    method: "eth_getTransactionCount",
    params: [
      address2,
      typeof blockNumber === "bigint" ? numberToHex(blockNumber) : blockTag
    ]
  }, {
    dedupe: Boolean(blockNumber)
  });
  return hexToNumber(count);
}
var init_getTransactionCount = __esm({
  "node_modules/viem/_esm/actions/public/getTransactionCount.js"() {
    "use strict";
    init_fromHex();
    init_toHex();
  }
});

// node_modules/viem/_esm/utils/blob/blobsToCommitments.js
function blobsToCommitments(parameters) {
  const { kzg } = parameters;
  const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes");
  const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs;
  const commitments = [];
  for (const blob of blobs)
    commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob)));
  return to === "bytes" ? commitments : commitments.map((x) => bytesToHex(x));
}
var init_blobsToCommitments = __esm({
  "node_modules/viem/_esm/utils/blob/blobsToCommitments.js"() {
    "use strict";
    init_toBytes();
    init_toHex();
  }
});

// node_modules/viem/_esm/utils/blob/blobsToProofs.js
function blobsToProofs(parameters) {
  const { kzg } = parameters;
  const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes");
  const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs;
  const commitments = typeof parameters.commitments[0] === "string" ? parameters.commitments.map((x) => hexToBytes(x)) : parameters.commitments;
  const proofs = [];
  for (let i = 0; i < blobs.length; i++) {
    const blob = blobs[i];
    const commitment = commitments[i];
    proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment)));
  }
  return to === "bytes" ? proofs : proofs.map((x) => bytesToHex(x));
}
var init_blobsToProofs = __esm({
  "node_modules/viem/_esm/utils/blob/blobsToProofs.js"() {
    "use strict";
    init_toBytes();
    init_toHex();
  }
});

// node_modules/viem/node_modules/@noble/hashes/esm/sha256.js
var sha2562;
var init_sha256 = __esm({
  "node_modules/viem/node_modules/@noble/hashes/esm/sha256.js"() {
    "use strict";
    init_sha2();
    sha2562 = sha256;
  }
});

// node_modules/viem/_esm/utils/hash/sha256.js
function sha2563(value, to_) {
  const to = to_ || "hex";
  const bytes = sha2562(isHex(value, { strict: false }) ? toBytes(value) : value);
  if (to === "bytes")
    return bytes;
  return toHex(bytes);
}
var init_sha2562 = __esm({
  "node_modules/viem/_esm/utils/hash/sha256.js"() {
    "use strict";
    init_sha256();
    init_isHex();
    init_toBytes();
    init_toHex();
  }
});

// node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js
function commitmentToVersionedHash(parameters) {
  const { commitment, version: version4 = 1 } = parameters;
  const to = parameters.to ?? (typeof commitment === "string" ? "hex" : "bytes");
  const versionedHash = sha2563(commitment, "bytes");
  versionedHash.set([version4], 0);
  return to === "bytes" ? versionedHash : bytesToHex(versionedHash);
}
var init_commitmentToVersionedHash = __esm({
  "node_modules/viem/_esm/utils/blob/commitmentToVersionedHash.js"() {
    "use strict";
    init_toHex();
    init_sha2562();
  }
});

// node_modules/viem/_esm/utils/blob/commitmentsToVersionedHashes.js
function commitmentsToVersionedHashes(parameters) {
  const { commitments, version: version4 } = parameters;
  const to = parameters.to ?? (typeof commitments[0] === "string" ? "hex" : "bytes");
  const hashes = [];
  for (const commitment of commitments) {
    hashes.push(commitmentToVersionedHash({
      commitment,
      to,
      version: version4
    }));
  }
  return hashes;
}
var init_commitmentsToVersionedHashes = __esm({
  "node_modules/viem/_esm/utils/blob/commitmentsToVersionedHashes.js"() {
    "use strict";
    init_commitmentToVersionedHash();
  }
});

// node_modules/viem/_esm/constants/blob.js
var blobsPerTransaction, bytesPerFieldElement, fieldElementsPerBlob, bytesPerBlob, maxBytesPerTransaction;
var init_blob = __esm({
  "node_modules/viem/_esm/constants/blob.js"() {
    "use strict";
    blobsPerTransaction = 6;
    bytesPerFieldElement = 32;
    fieldElementsPerBlob = 4096;
    bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob;
    maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction - // terminator byte (0x80).
    1 - // zero byte (0x00) appended to each field element.
    1 * fieldElementsPerBlob * blobsPerTransaction;
  }
});

// node_modules/viem/_esm/constants/kzg.js
var versionedHashVersionKzg;
var init_kzg = __esm({
  "node_modules/viem/_esm/constants/kzg.js"() {
    "use strict";
    versionedHashVersionKzg = 1;
  }
});

// node_modules/viem/_esm/errors/blob.js
var BlobSizeTooLargeError, EmptyBlobError, InvalidVersionedHashSizeError, InvalidVersionedHashVersionError;
var init_blob2 = __esm({
  "node_modules/viem/_esm/errors/blob.js"() {
    "use strict";
    init_kzg();
    init_base();
    BlobSizeTooLargeError = class extends BaseError2 {
      constructor({ maxSize, size: size5 }) {
        super("Blob size is too large.", {
          metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size5} bytes`],
          name: "BlobSizeTooLargeError"
        });
      }
    };
    EmptyBlobError = class extends BaseError2 {
      constructor() {
        super("Blob data must not be empty.", { name: "EmptyBlobError" });
      }
    };
    InvalidVersionedHashSizeError = class extends BaseError2 {
      constructor({ hash: hash3, size: size5 }) {
        super(`Versioned hash "${hash3}" size is invalid.`, {
          metaMessages: ["Expected: 32", `Received: ${size5}`],
          name: "InvalidVersionedHashSizeError"
        });
      }
    };
    InvalidVersionedHashVersionError = class extends BaseError2 {
      constructor({ hash: hash3, version: version4 }) {
        super(`Versioned hash "${hash3}" version is invalid.`, {
          metaMessages: [
            `Expected: ${versionedHashVersionKzg}`,
            `Received: ${version4}`
          ],
          name: "InvalidVersionedHashVersionError"
        });
      }
    };
  }
});

// node_modules/viem/_esm/utils/blob/toBlobs.js
function toBlobs(parameters) {
  const to = parameters.to ?? (typeof parameters.data === "string" ? "hex" : "bytes");
  const data = typeof parameters.data === "string" ? hexToBytes(parameters.data) : parameters.data;
  const size_ = size(data);
  if (!size_)
    throw new EmptyBlobError();
  if (size_ > maxBytesPerTransaction)
    throw new BlobSizeTooLargeError({
      maxSize: maxBytesPerTransaction,
      size: size_
    });
  const blobs = [];
  let active = true;
  let position = 0;
  while (active) {
    const blob = createCursor(new Uint8Array(bytesPerBlob));
    let size5 = 0;
    while (size5 < fieldElementsPerBlob) {
      const bytes = data.slice(position, position + (bytesPerFieldElement - 1));
      blob.pushByte(0);
      blob.pushBytes(bytes);
      if (bytes.length < 31) {
        blob.pushByte(128);
        active = false;
        break;
      }
      size5++;
      position += 31;
    }
    blobs.push(blob);
  }
  return to === "bytes" ? blobs.map((x) => x.bytes) : blobs.map((x) => bytesToHex(x.bytes));
}
var init_toBlobs = __esm({
  "node_modules/viem/_esm/utils/blob/toBlobs.js"() {
    "use strict";
    init_blob();
    init_blob2();
    init_cursor2();
    init_size();
    init_toBytes();
    init_toHex();
  }
});

// node_modules/viem/_esm/utils/blob/toBlobSidecars.js
function toBlobSidecars(parameters) {
  const { data, kzg, to } = parameters;
  const blobs = parameters.blobs ?? toBlobs({ data, to });
  const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg, to });
  const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg, to });
  const sidecars = [];
  for (let i = 0; i < blobs.length; i++)
    sidecars.push({
      blob: blobs[i],
      commitment: commitments[i],
      proof: proofs[i]
    });
  return sidecars;
}
var init_toBlobSidecars = __esm({
  "node_modules/viem/_esm/utils/blob/toBlobSidecars.js"() {
    "use strict";
    init_blobsToCommitments();
    init_blobsToProofs();
    init_toBlobs();
  }
});

// node_modules/viem/_esm/utils/transaction/getTransactionType.js
function getTransactionType(transaction) {
  if (transaction.type)
    return transaction.type;
  if (typeof transaction.authorizationList !== "undefined")
    return "eip7702";
  if (typeof transaction.blobs !== "undefined" || typeof transaction.blobVersionedHashes !== "undefined" || typeof transaction.maxFeePerBlobGas !== "undefined" || typeof transaction.sidecars !== "undefined")
    return "eip4844";
  if (typeof transaction.maxFeePerGas !== "undefined" || typeof transaction.maxPriorityFeePerGas !== "undefined") {
    return "eip1559";
  }
  if (typeof transaction.gasPrice !== "undefined") {
    if (typeof transaction.accessList !== "undefined")
      return "eip2930";
    return "legacy";
  }
  throw new InvalidSerializableTransactionError({ transaction });
}
var init_getTransactionType = __esm({
  "node_modules/viem/_esm/utils/transaction/getTransactionType.js"() {
    "use strict";
    init_transaction();
  }
});

// node_modules/viem/_esm/utils/errors/getTransactionError.js
function getTransactionError(err, { docsPath: docsPath8, ...args }) {
  const cause = (() => {
    const cause2 = getNodeError(err, args);
    if (cause2 instanceof UnknownNodeError)
      return err;
    return cause2;
  })();
  return new TransactionExecutionError(cause, {
    docsPath: docsPath8,
    ...args
  });
}
var init_getTransactionError = __esm({
  "node_modules/viem/_esm/utils/errors/getTransactionError.js"() {
    "use strict";
    init_node();
    init_transaction();
    init_getNodeError();
  }
});

// node_modules/viem/_esm/actions/public/getChainId.js
async function getChainId(client) {
  const chainIdHex = await client.request({
    method: "eth_chainId"
  }, { dedupe: true });
  return hexToNumber(chainIdHex);
}
var init_getChainId = __esm({
  "node_modules/viem/_esm/actions/public/getChainId.js"() {
    "use strict";
    init_fromHex();
  }
});

// node_modules/viem/_esm/actions/public/fillTransaction.js
async function fillTransaction(client, parameters) {
  const { account = client.account, accessList, authorizationList, chain: chain3 = client.chain, blobVersionedHashes, blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce: nonce_, nonceManager, to, type, value, ...rest } = parameters;
  const nonce = await (async () => {
    if (!account)
      return nonce_;
    if (!nonceManager)
      return nonce_;
    if (typeof nonce_ !== "undefined")
      return nonce_;
    const account_ = parseAccount(account);
    const chainId = chain3 ? chain3.id : await getAction(client, getChainId, "getChainId")({});
    return await nonceManager.consume({
      address: account_.address,
      chainId,
      client
    });
  })();
  assertRequest(parameters);
  const chainFormat = chain3?.formatters?.transactionRequest?.format;
  const format = chainFormat || formatTransactionRequest;
  const request = format({
    // Pick out extra data that might exist on the chain's transaction request type.
    ...extract(rest, { format: chainFormat }),
    account: account ? parseAccount(account) : void 0,
    accessList,
    authorizationList,
    blobs,
    blobVersionedHashes,
    data,
    gas,
    gasPrice,
    maxFeePerBlobGas,
    maxFeePerGas,
    maxPriorityFeePerGas,
    nonce,
    to,
    type,
    value
  }, "fillTransaction");
  try {
    const response = await client.request({
      method: "eth_fillTransaction",
      params: [request]
    });
    const format2 = chain3?.formatters?.transaction?.format || formatTransaction;
    const transaction = format2(response.tx);
    delete transaction.blockHash;
    delete transaction.blockNumber;
    delete transaction.r;
    delete transaction.s;
    delete transaction.transactionIndex;
    delete transaction.v;
    delete transaction.yParity;
    transaction.data = transaction.input;
    if (transaction.gas)
      transaction.gas = parameters.gas ?? transaction.gas;
    if (transaction.gasPrice)
      transaction.gasPrice = parameters.gasPrice ?? transaction.gasPrice;
    if (transaction.maxFeePerBlobGas)
      transaction.maxFeePerBlobGas = parameters.maxFeePerBlobGas ?? transaction.maxFeePerBlobGas;
    if (transaction.maxFeePerGas)
      transaction.maxFeePerGas = parameters.maxFeePerGas ?? transaction.maxFeePerGas;
    if (transaction.maxPriorityFeePerGas)
      transaction.maxPriorityFeePerGas = parameters.maxPriorityFeePerGas ?? transaction.maxPriorityFeePerGas;
    if (typeof transaction.nonce !== "undefined")
      transaction.nonce = parameters.nonce ?? transaction.nonce;
    const feeMultiplier = await (async () => {
      if (typeof chain3?.fees?.baseFeeMultiplier === "function") {
        const block = await getAction(client, getBlock, "getBlock")({});
        return chain3.fees.baseFeeMultiplier({
          block,
          client,
          request: parameters
        });
      }
      return chain3?.fees?.baseFeeMultiplier ?? 1.2;
    })();
    if (feeMultiplier < 1)
      throw new BaseFeeScalarError();
    const decimals = feeMultiplier.toString().split(".")[1]?.length ?? 0;
    const denominator = 10 ** decimals;
    const multiplyFee = (base2) => base2 * BigInt(Math.ceil(feeMultiplier * denominator)) / BigInt(denominator);
    if (!transaction.feePayerSignature) {
      if (transaction.maxFeePerGas && !parameters.maxFeePerGas)
        transaction.maxFeePerGas = multiplyFee(transaction.maxFeePerGas);
      if (transaction.gasPrice && !parameters.gasPrice)
        transaction.gasPrice = multiplyFee(transaction.gasPrice);
    }
    return {
      raw: response.raw,
      transaction: {
        from: request.from,
        ...transaction
      },
      ...response.capabilities ? { capabilities: response.capabilities } : {}
    };
  } catch (err) {
    throw getTransactionError(err, {
      ...parameters,
      chain: client.chain
    });
  }
}
var init_fillTransaction = __esm({
  "node_modules/viem/_esm/actions/public/fillTransaction.js"() {
    "use strict";
    init_parseAccount();
    init_fee();
    init_getTransactionError();
    init_extract();
    init_transaction2();
    init_transactionRequest();
    init_getAction();
    init_assertRequest();
    init_getBlock();
    init_getChainId();
  }
});

// node_modules/viem/_esm/actions/wallet/prepareTransactionRequest.js
async function prepareTransactionRequest(client, args) {
  let request = args;
  request.account ??= client.account;
  request.parameters ??= defaultParameters;
  const { account: account_, chain: chain3 = client.chain, nonceManager, parameters } = request;
  const prepareTransactionRequest2 = (() => {
    if (typeof chain3?.prepareTransactionRequest === "function")
      return {
        fn: chain3.prepareTransactionRequest,
        runAt: ["beforeFillTransaction"]
      };
    if (Array.isArray(chain3?.prepareTransactionRequest))
      return {
        fn: chain3.prepareTransactionRequest[0],
        runAt: chain3.prepareTransactionRequest[1].runAt
      };
    return void 0;
  })();
  let chainId;
  async function getChainId2() {
    if (chainId)
      return chainId;
    if (typeof request.chainId !== "undefined")
      return request.chainId;
    if (chain3)
      return chain3.id;
    const chainId_ = await getAction(client, getChainId, "getChainId")({});
    chainId = chainId_;
    return chainId;
  }
  const account = account_ ? parseAccount(account_) : account_;
  let nonce = request.nonce;
  if (parameters.includes("nonce") && typeof nonce === "undefined" && account && nonceManager) {
    const chainId2 = await getChainId2();
    nonce = await nonceManager.consume({
      address: account.address,
      chainId: chainId2,
      client
    });
  }
  if (prepareTransactionRequest2?.fn && prepareTransactionRequest2.runAt?.includes("beforeFillTransaction")) {
    request = await prepareTransactionRequest2.fn({ ...request, chain: chain3 }, {
      phase: "beforeFillTransaction"
    });
    nonce ??= request.nonce;
  }
  const attemptFill = (() => {
    if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && request.kzg && request.blobs)
      return false;
    if (supportsFillTransaction.get(client.uid) === false)
      return false;
    const shouldAttempt = ["fees", "gas"].some((parameter) => parameters.includes(parameter));
    if (!shouldAttempt)
      return false;
    if (parameters.includes("chainId") && typeof request.chainId !== "number")
      return true;
    if (parameters.includes("nonce") && typeof nonce !== "number")
      return true;
    if (parameters.includes("fees") && typeof request.gasPrice !== "bigint" && (typeof request.maxFeePerGas !== "bigint" || typeof request.maxPriorityFeePerGas !== "bigint"))
      return true;
    if (parameters.includes("gas") && typeof request.gas !== "bigint")
      return true;
    return false;
  })();
  const fillResult = attemptFill ? await getAction(client, fillTransaction, "fillTransaction")({ ...request, nonce }).then((result) => {
    const { chainId: chainId2, from: from14, gas: gas2, gasPrice, nonce: nonce2, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, type: type2, ...rest } = result.transaction;
    supportsFillTransaction.set(client.uid, true);
    return {
      ...request,
      ...from14 ? { from: from14 } : {},
      ...type2 && !request.type ? { type: type2 } : {},
      ...typeof chainId2 !== "undefined" ? { chainId: chainId2 } : {},
      ...typeof gas2 !== "undefined" ? { gas: gas2 } : {},
      ...typeof gasPrice !== "undefined" ? { gasPrice } : {},
      ...typeof nonce2 !== "undefined" ? { nonce: nonce2 } : {},
      ...typeof maxFeePerBlobGas !== "undefined" && request.type !== "legacy" && request.type !== "eip2930" ? { maxFeePerBlobGas } : {},
      ...typeof maxFeePerGas !== "undefined" && request.type !== "legacy" && request.type !== "eip2930" ? { maxFeePerGas } : {},
      ...typeof maxPriorityFeePerGas !== "undefined" && request.type !== "legacy" && request.type !== "eip2930" ? { maxPriorityFeePerGas } : {},
      ..."nonceKey" in rest && typeof rest.nonceKey !== "undefined" ? { nonceKey: rest.nonceKey } : {},
      ..."keyAuthorization" in rest && typeof rest.keyAuthorization !== "undefined" && rest.keyAuthorization !== null && !("keyAuthorization" in request) ? { keyAuthorization: rest.keyAuthorization } : {},
      ..."feePayerSignature" in rest && typeof rest.feePayerSignature !== "undefined" && rest.feePayerSignature !== null ? { feePayerSignature: rest.feePayerSignature } : {},
      ..."feeToken" in rest && typeof rest.feeToken !== "undefined" && rest.feeToken !== null && !("feeToken" in request) ? { feeToken: rest.feeToken } : {},
      ...result.capabilities ? { _capabilities: result.capabilities } : {}
    };
  }).catch((e7) => {
    const error = e7;
    if (error.name !== "TransactionExecutionError")
      return request;
    const executionReverted = error.walk?.((e8) => {
      const error2 = e8;
      return error2.name === "ExecutionRevertedError";
    });
    if (executionReverted)
      throw e7;
    const unsupported = error.walk?.((e8) => {
      const error2 = e8;
      return error2.name === "MethodNotFoundRpcError" || error2.name === "MethodNotSupportedRpcError" || error2.message?.includes("eth_fillTransaction is not available");
    });
    if (unsupported)
      supportsFillTransaction.set(client.uid, false);
    return request;
  }) : request;
  nonce ??= fillResult.nonce;
  request = {
    ...fillResult,
    ...account ? { from: account?.address } : {},
    ...typeof nonce !== "undefined" ? { nonce } : {}
  };
  const { blobs, gas, kzg, type } = request;
  if (prepareTransactionRequest2?.fn && prepareTransactionRequest2.runAt?.includes("beforeFillParameters")) {
    request = await prepareTransactionRequest2.fn({ ...request, chain: chain3 }, {
      phase: "beforeFillParameters"
    });
  }
  let block;
  async function getBlock2() {
    if (block)
      return block;
    block = await getAction(client, getBlock, "getBlock")({ blockTag: "latest" });
    return block;
  }
  if (parameters.includes("nonce") && typeof nonce === "undefined" && account && !nonceManager)
    request.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({
      address: account.address,
      blockTag: "pending"
    });
  if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && blobs && kzg) {
    const commitments = blobsToCommitments({ blobs, kzg });
    if (parameters.includes("blobVersionedHashes")) {
      const versionedHashes = commitmentsToVersionedHashes({
        commitments,
        to: "hex"
      });
      request.blobVersionedHashes = versionedHashes;
    }
    if (parameters.includes("sidecars")) {
      const proofs = blobsToProofs({ blobs, commitments, kzg });
      const sidecars = toBlobSidecars({
        blobs,
        commitments,
        proofs,
        to: "hex"
      });
      request.sidecars = sidecars;
    }
  }
  if (parameters.includes("chainId"))
    request.chainId = await getChainId2();
  if ((parameters.includes("fees") || parameters.includes("type")) && typeof type === "undefined") {
    try {
      request.type = getTransactionType(request);
    } catch {
      let isEip1559Network = eip1559NetworkCache.get(client.uid);
      if (typeof isEip1559Network === "undefined") {
        const block2 = await getBlock2();
        isEip1559Network = typeof block2?.baseFeePerGas === "bigint";
        eip1559NetworkCache.set(client.uid, isEip1559Network);
      }
      request.type = isEip1559Network ? "eip1559" : "legacy";
    }
  }
  if (parameters.includes("fees")) {
    if (request.type !== "legacy" && request.type !== "eip2930") {
      if (typeof request.maxFeePerGas === "undefined" || typeof request.maxPriorityFeePerGas === "undefined") {
        const block2 = await getBlock2();
        const { maxFeePerGas, maxPriorityFeePerGas } = await internal_estimateFeesPerGas(client, {
          block: block2,
          chain: chain3,
          request
        });
        if (typeof request.maxPriorityFeePerGas === "undefined" && request.maxFeePerGas && request.maxFeePerGas < maxPriorityFeePerGas)
          throw new MaxFeePerGasTooLowError({
            maxPriorityFeePerGas
          });
        request.maxPriorityFeePerGas = maxPriorityFeePerGas;
        request.maxFeePerGas = maxFeePerGas;
      }
    } else {
      if (typeof request.maxFeePerGas !== "undefined" || typeof request.maxPriorityFeePerGas !== "undefined")
        throw new Eip1559FeesNotSupportedError();
      if (typeof request.gasPrice === "undefined") {
        const block2 = await getBlock2();
        const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(client, {
          block: block2,
          chain: chain3,
          request,
          type: "legacy"
        });
        request.gasPrice = gasPrice_;
      }
    }
  }
  if (parameters.includes("gas") && typeof gas === "undefined")
    request.gas = await getAction(client, estimateGas, "estimateGas")({
      ...request,
      account,
      prepare: account?.type === "local" ? [] : ["blobVersionedHashes"]
    });
  if (prepareTransactionRequest2?.fn && prepareTransactionRequest2.runAt?.includes("afterFillParameters"))
    request = await prepareTransactionRequest2.fn({ ...request, chain: chain3 }, {
      phase: "afterFillParameters"
    });
  assertRequest(request);
  delete request.parameters;
  return request;
}
var defaultParameters, eip1559NetworkCache, supportsFillTransaction;
var init_prepareTransactionRequest = __esm({
  "node_modules/viem/_esm/actions/wallet/prepareTransactionRequest.js"() {
    "use strict";
    init_parseAccount();
    init_estimateFeesPerGas();
    init_estimateGas2();
    init_getBlock();
    init_getTransactionCount();
    init_fee();
    init_blobsToCommitments();
    init_blobsToProofs();
    init_commitmentsToVersionedHashes();
    init_toBlobSidecars();
    init_getAction();
    init_lru();
    init_assertRequest();
    init_getTransactionType();
    init_fillTransaction();
    init_getChainId();
    defaultParameters = [
      "blobVersionedHashes",
      "chainId",
      "fees",
      "gas",
      "nonce",
      "type"
    ];
    eip1559NetworkCache = /* @__PURE__ */ new Map();
    supportsFillTransaction = /* @__PURE__ */ new LruMap(128);
  }
});

// node_modules/viem/_esm/actions/public/estimateGas.js
async function estimateGas(client, args) {
  const { account: account_ = client.account, prepare = true } = args;
  const account = account_ ? parseAccount(account_) : void 0;
  const parameters = (() => {
    if (Array.isArray(prepare))
      return prepare;
    if (account?.type !== "local")
      return ["blobVersionedHashes"];
    return void 0;
  })();
  try {
    const to = await (async () => {
      if (args.to)
        return args.to;
      if (args.authorizationList && args.authorizationList.length > 0)
        return await recoverAuthorizationAddress({
          authorization: args.authorizationList[0]
        }).catch(() => {
          throw new BaseError2("`to` is required. Could not infer from `authorizationList`");
        });
      return void 0;
    })();
    const { accessList, authorizationList, blobs, blobVersionedHashes, blockNumber, blockTag, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, value, stateOverride, ...rest } = prepare ? await prepareTransactionRequest(client, {
      ...args,
      parameters,
      to
    }) : args;
    if (gas && args.gas !== gas)
      return gas;
    const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : void 0;
    const block = blockNumberHex || blockTag;
    const rpcStateOverride = serializeStateOverride(stateOverride);
    assertRequest(args);
    const chainFormat = client.chain?.formatters?.transactionRequest?.format;
    const format = chainFormat || formatTransactionRequest;
    const request = format({
      // Pick out extra data that might exist on the chain's transaction request type.
      ...extract(rest, { format: chainFormat }),
      account,
      accessList,
      authorizationList,
      blobs,
      blobVersionedHashes,
      data,
      gasPrice,
      maxFeePerBlobGas,
      maxFeePerGas,
      maxPriorityFeePerGas,
      nonce,
      to,
      value
    }, "estimateGas");
    return BigInt(await client.request({
      method: "eth_estimateGas",
      params: rpcStateOverride ? [
        request,
        block ?? client.experimental_blockTag ?? "latest",
        rpcStateOverride
      ] : block ? [request, block] : [request]
    }));
  } catch (err) {
    throw getEstimateGasError(err, {
      ...args,
      account,
      chain: client.chain
    });
  }
}
var init_estimateGas2 = __esm({
  "node_modules/viem/_esm/actions/public/estimateGas.js"() {
    "use strict";
    init_parseAccount();
    init_base();
    init_recoverAuthorizationAddress();
    init_toHex();
    init_getEstimateGasError();
    init_extract();
    init_transactionRequest();
    init_stateOverride2();
    init_assertRequest();
    init_prepareTransactionRequest();
  }
});

// node_modules/viem/_esm/actions/public/estimateContractGas.js
async function estimateContractGas(client, parameters) {
  const { abi: abi2, address: address2, args, functionName, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, ...request } = parameters;
  const data = encodeFunctionData({
    abi: abi2,
    args,
    functionName
  });
  try {
    const gas = await getAction(client, estimateGas, "estimateGas")({
      data: `${data}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`,
      to: address2,
      ...request
    });
    return gas;
  } catch (error) {
    const account = request.account ? parseAccount(request.account) : void 0;
    throw getContractError(error, {
      abi: abi2,
      address: address2,
      args,
      docsPath: "/docs/contract/estimateContractGas",
      functionName,
      sender: account?.address
    });
  }
}
var init_estimateContractGas = __esm({
  "node_modules/viem/_esm/actions/public/estimateContractGas.js"() {
    "use strict";
    init_parseAccount();
    init_encodeFunctionData();
    init_getContractError();
    init_getAction();
    init_estimateGas2();
  }
});

// node_modules/viem/_esm/utils/address/isAddressEqual.js
function isAddressEqual(a, b) {
  if (!isAddress(a, { strict: false }))
    throw new InvalidAddressError({ address: a });
  if (!isAddress(b, { strict: false }))
    throw new InvalidAddressError({ address: b });
  return a.toLowerCase() === b.toLowerCase();
}
var init_isAddressEqual = __esm({
  "node_modules/viem/_esm/utils/address/isAddressEqual.js"() {
    "use strict";
    init_address();
    init_isAddress();
  }
});

// node_modules/viem/_esm/utils/formatters/log.js
function formatLog(log, { args, eventName } = {}) {
  return {
    ...log,
    blockHash: log.blockHash ? log.blockHash : null,
    blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,
    blockTimestamp: log.blockTimestamp ? BigInt(log.blockTimestamp) : log.blockTimestamp === null ? null : void 0,
    logIndex: log.logIndex ? Number(log.logIndex) : null,
    transactionHash: log.transactionHash ? log.transactionHash : null,
    transactionIndex: log.transactionIndex ? Number(log.transactionIndex) : null,
    ...eventName ? { args, eventName } : {}
  };
}
var init_log2 = __esm({
  "node_modules/viem/_esm/utils/formatters/log.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/utils/abi/decodeEventLog.js
function decodeEventLog(parameters) {
  const { abi: abi2, data, strict: strict_, topics } = parameters;
  const strict = strict_ ?? true;
  const [signature2, ...argTopics] = topics;
  if (!signature2)
    throw new AbiEventSignatureEmptyTopicsError({ docsPath: docsPath3 });
  const abiItem = abi2.find((x) => x.type === "event" && signature2 === toEventSelector(formatAbiItem2(x)));
  if (!(abiItem && "name" in abiItem) || abiItem.type !== "event")
    throw new AbiEventSignatureNotFoundError(signature2, { docsPath: docsPath3 });
  const { name, inputs } = abiItem;
  const isUnnamed = inputs?.some((x) => !("name" in x && x.name));
  const args = isUnnamed ? [] : {};
  const indexedInputs = inputs.map((x, i) => [x, i]).filter(([x]) => "indexed" in x && x.indexed);
  const missingIndexedInputs = [];
  for (let i = 0; i < indexedInputs.length; i++) {
    const [param, argIndex] = indexedInputs[i];
    const topic = argTopics[i];
    if (!topic) {
      if (strict)
        throw new DecodeLogTopicsMismatch({
          abiItem,
          param
        });
      missingIndexedInputs.push([param, argIndex]);
      continue;
    }
    args[isUnnamed ? argIndex : param.name || argIndex] = decodeTopic({
      param,
      value: topic
    });
  }
  const nonIndexedInputs = inputs.filter((x) => !("indexed" in x && x.indexed));
  const inputsToDecode = strict ? nonIndexedInputs : [...missingIndexedInputs.map(([param]) => param), ...nonIndexedInputs];
  if (inputsToDecode.length > 0) {
    if (data && data !== "0x") {
      try {
        const decodedData = decodeAbiParameters(inputsToDecode, data);
        if (decodedData) {
          let dataIndex = 0;
          if (!strict) {
            for (const [param, argIndex] of missingIndexedInputs) {
              args[isUnnamed ? argIndex : param.name || argIndex] = decodedData[dataIndex++];
            }
          }
          if (isUnnamed) {
            for (let i = 0; i < inputs.length; i++)
              if (args[i] === void 0 && dataIndex < decodedData.length)
                args[i] = decodedData[dataIndex++];
          } else
            for (let i = 0; i < nonIndexedInputs.length; i++)
              args[nonIndexedInputs[i].name] = decodedData[dataIndex++];
        }
      } catch (err) {
        if (strict) {
          if (err instanceof AbiDecodingDataSizeTooSmallError || err instanceof PositionOutOfBoundsError)
            throw new DecodeLogDataMismatch({
              abiItem,
              data,
              params: inputsToDecode,
              size: size(data)
            });
          throw err;
        }
      }
    } else if (strict) {
      throw new DecodeLogDataMismatch({
        abiItem,
        data: "0x",
        params: inputsToDecode,
        size: 0
      });
    }
  }
  return {
    eventName: name,
    args: Object.values(args).length > 0 ? args : void 0
  };
}
function decodeTopic({ param, value }) {
  if (param.type === "string" || param.type === "bytes" || param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/))
    return value;
  const decodedArg = decodeAbiParameters([param], value) || [];
  return decodedArg[0];
}
var docsPath3;
var init_decodeEventLog = __esm({
  "node_modules/viem/_esm/utils/abi/decodeEventLog.js"() {
    "use strict";
    init_abi();
    init_cursor();
    init_size();
    init_toEventSelector();
    init_decodeAbiParameters();
    init_formatAbiItem2();
    docsPath3 = "/docs/contract/decodeEventLog";
  }
});

// node_modules/viem/_esm/utils/abi/parseEventLogs.js
function parseEventLogs(parameters) {
  const { abi: abi2, args, logs, strict = true } = parameters;
  const eventName = (() => {
    if (!parameters.eventName)
      return void 0;
    if (Array.isArray(parameters.eventName))
      return parameters.eventName;
    return [parameters.eventName];
  })();
  const abiTopics = abi2.filter((abiItem) => abiItem.type === "event").map((abiItem) => ({
    abi: abiItem,
    selector: toEventSelector(abiItem)
  }));
  return logs.map((log) => {
    const formattedLog = typeof log.blockNumber === "string" ? formatLog(log) : log;
    const abiItems = abiTopics.filter((abiTopic) => formattedLog.topics[0] === abiTopic.selector);
    if (abiItems.length === 0)
      return null;
    let event;
    let abiItem;
    for (const item of abiItems) {
      try {
        event = decodeEventLog({
          ...formattedLog,
          abi: [item.abi],
          strict: true
        });
        abiItem = item;
        break;
      } catch {
      }
    }
    if (!event && !strict) {
      abiItem = abiItems[0];
      try {
        event = decodeEventLog({
          data: formattedLog.data,
          topics: formattedLog.topics,
          abi: [abiItem.abi],
          strict: false
        });
      } catch {
        const isUnnamed = abiItem.abi.inputs?.some((x) => !("name" in x && x.name));
        return {
          ...formattedLog,
          args: isUnnamed ? [] : {},
          eventName: abiItem.abi.name
        };
      }
    }
    if (!event || !abiItem)
      return null;
    if (eventName && !eventName.includes(event.eventName))
      return null;
    if (!includesArgs({
      args: event.args,
      inputs: abiItem.abi.inputs,
      matchArgs: args
    }))
      return null;
    return { ...event, ...formattedLog };
  }).filter(Boolean);
}
function includesArgs(parameters) {
  const { args, inputs, matchArgs } = parameters;
  if (!matchArgs)
    return true;
  if (!args)
    return false;
  function isEqual2(input, value, arg) {
    try {
      if (input.type === "address")
        return isAddressEqual(value, arg);
      if (input.type === "string" || input.type === "bytes")
        return keccak256(toBytes(value)) === arg;
      return value === arg;
    } catch {
      return false;
    }
  }
  if (Array.isArray(args) && Array.isArray(matchArgs)) {
    return matchArgs.every((value, index2) => {
      if (value === null || value === void 0)
        return true;
      const input = inputs[index2];
      if (!input)
        return false;
      const value_ = Array.isArray(value) ? value : [value];
      return value_.some((value2) => isEqual2(input, value2, args[index2]));
    });
  }
  if (typeof args === "object" && !Array.isArray(args) && typeof matchArgs === "object" && !Array.isArray(matchArgs))
    return Object.entries(matchArgs).every(([key, value]) => {
      if (value === null || value === void 0)
        return true;
      const input = inputs.find((input2) => input2.name === key);
      if (!input)
        return false;
      const value_ = Array.isArray(value) ? value : [value];
      return value_.some((value2) => isEqual2(input, value2, args[key]));
    });
  return false;
}
var init_parseEventLogs = __esm({
  "node_modules/viem/_esm/utils/abi/parseEventLogs.js"() {
    "use strict";
    init_isAddressEqual();
    init_toBytes();
    init_log2();
    init_keccak256();
    init_toEventSelector();
    init_decodeEventLog();
  }
});

// node_modules/viem/_esm/actions/public/getLogs.js
async function getLogs(client, { address: address2, blockHash, fromBlock, toBlock, event, events: events_, args, strict: strict_ } = {}) {
  const strict = strict_ ?? false;
  const events = events_ ?? (event ? [event] : void 0);
  let topics = [];
  if (events) {
    const encoded = events.flatMap((event2) => encodeEventTopics({
      abi: [event2],
      eventName: event2.name,
      args: events_ ? void 0 : args
    }));
    topics = [encoded];
    if (event)
      topics = topics[0];
  }
  let logs;
  if (blockHash) {
    logs = await client.request({
      method: "eth_getLogs",
      params: [{ address: address2, topics, blockHash }]
    });
  } else {
    logs = await client.request({
      method: "eth_getLogs",
      params: [
        {
          address: address2,
          topics,
          fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock,
          toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock
        }
      ]
    });
  }
  const formattedLogs = logs.map((log) => formatLog(log));
  if (!events)
    return formattedLogs;
  return parseEventLogs({
    abi: events,
    args,
    logs: formattedLogs,
    strict
  });
}
var init_getLogs = __esm({
  "node_modules/viem/_esm/actions/public/getLogs.js"() {
    "use strict";
    init_encodeEventTopics();
    init_parseEventLogs();
    init_toHex();
    init_log2();
  }
});

// node_modules/viem/_esm/actions/public/getContractEvents.js
async function getContractEvents(client, parameters) {
  const { abi: abi2, address: address2, args, blockHash, eventName, fromBlock, toBlock, strict } = parameters;
  const event = eventName ? getAbiItem({ abi: abi2, name: eventName }) : void 0;
  const events = !event ? abi2.filter((x) => x.type === "event") : void 0;
  return getAction(client, getLogs, "getLogs")({
    address: address2,
    args,
    blockHash,
    event,
    events,
    fromBlock,
    toBlock,
    strict
  });
}
var init_getContractEvents = __esm({
  "node_modules/viem/_esm/actions/public/getContractEvents.js"() {
    "use strict";
    init_getAbiItem();
    init_getAction();
    init_getLogs();
  }
});

// node_modules/viem/_esm/utils/abi/decodeFunctionResult.js
function decodeFunctionResult(parameters) {
  const { abi: abi2, args, functionName, data } = parameters;
  let abiItem = abi2[0];
  if (functionName) {
    const item = getAbiItem({ abi: abi2, args, name: functionName });
    if (!item)
      throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath4 });
    abiItem = item;
  }
  if (abiItem.type !== "function")
    throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath4 });
  if (!abiItem.outputs)
    throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath: docsPath4 });
  const values = decodeAbiParameters(abiItem.outputs, data);
  if (values && values.length > 1)
    return values;
  if (values && values.length === 1)
    return values[0];
  return void 0;
}
var docsPath4;
var init_decodeFunctionResult = __esm({
  "node_modules/viem/_esm/utils/abi/decodeFunctionResult.js"() {
    "use strict";
    init_abi();
    init_decodeAbiParameters();
    init_getAbiItem();
    docsPath4 = "/docs/contract/decodeFunctionResult";
  }
});

// node_modules/ox/node_modules/@noble/curves/esm/abstract/utils.js
function isBytes3(a) {
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
function abytes3(item) {
  if (!isBytes3(item))
    throw new Error("Uint8Array expected");
}
function abool2(title, value) {
  if (typeof value !== "boolean")
    throw new Error(title + " boolean expected, got " + value);
}
function numberToHexUnpadded2(num2) {
  const hex = num2.toString(16);
  return hex.length & 1 ? "0" + hex : hex;
}
function hexToNumber3(hex) {
  if (typeof hex !== "string")
    throw new Error("hex string expected, got " + typeof hex);
  return hex === "" ? _0n7 : BigInt("0x" + hex);
}
function bytesToHex3(bytes) {
  abytes3(bytes);
  if (hasHexBuiltin2)
    return bytes.toHex();
  let hex = "";
  for (let i = 0; i < bytes.length; i++) {
    hex += hexes3[bytes[i]];
  }
  return hex;
}
function asciiToBase162(ch) {
  if (ch >= asciis2._0 && ch <= asciis2._9)
    return ch - asciis2._0;
  if (ch >= asciis2.A && ch <= asciis2.F)
    return ch - (asciis2.A - 10);
  if (ch >= asciis2.a && ch <= asciis2.f)
    return ch - (asciis2.a - 10);
  return;
}
function hexToBytes3(hex) {
  if (typeof hex !== "string")
    throw new Error("hex string expected, got " + typeof hex);
  if (hasHexBuiltin2)
    return Uint8Array.fromHex(hex);
  const hl = hex.length;
  const al = hl / 2;
  if (hl % 2)
    throw new Error("hex string expected, got unpadded hex of length " + hl);
  const array = new Uint8Array(al);
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
    const n1 = asciiToBase162(hex.charCodeAt(hi));
    const n2 = asciiToBase162(hex.charCodeAt(hi + 1));
    if (n1 === void 0 || n2 === void 0) {
      const char = hex[hi] + hex[hi + 1];
      throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
    }
    array[ai] = n1 * 16 + n2;
  }
  return array;
}
function bytesToNumberBE2(bytes) {
  return hexToNumber3(bytesToHex3(bytes));
}
function bytesToNumberLE2(bytes) {
  abytes3(bytes);
  return hexToNumber3(bytesToHex3(Uint8Array.from(bytes).reverse()));
}
function numberToBytesBE2(n, len) {
  return hexToBytes3(n.toString(16).padStart(len * 2, "0"));
}
function numberToBytesLE2(n, len) {
  return numberToBytesBE2(n, len).reverse();
}
function ensureBytes2(title, hex, expectedLength) {
  let res;
  if (typeof hex === "string") {
    try {
      res = hexToBytes3(hex);
    } catch (e7) {
      throw new Error(title + " must be hex string or Uint8Array, cause: " + e7);
    }
  } else if (isBytes3(hex)) {
    res = Uint8Array.from(hex);
  } else {
    throw new Error(title + " must be hex string or Uint8Array");
  }
  const len = res.length;
  if (typeof expectedLength === "number" && len !== expectedLength)
    throw new Error(title + " of length " + expectedLength + " expected, got " + len);
  return res;
}
function concatBytes4(...arrays) {
  let sum = 0;
  for (let i = 0; i < arrays.length; i++) {
    const a = arrays[i];
    abytes3(a);
    sum += a.length;
  }
  const res = new Uint8Array(sum);
  for (let i = 0, pad4 = 0; i < arrays.length; i++) {
    const a = arrays[i];
    res.set(a, pad4);
    pad4 += a.length;
  }
  return res;
}
function inRange2(n, min, max) {
  return isPosBig2(n) && isPosBig2(min) && isPosBig2(max) && min <= n && n < max;
}
function aInRange2(title, n, min, max) {
  if (!inRange2(n, min, max))
    throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
}
function bitLen2(n) {
  let len;
  for (len = 0; n > _0n7; n >>= _1n7, len += 1)
    ;
  return len;
}
function createHmacDrbg2(hashLen, qByteLen, hmacFn) {
  if (typeof hashLen !== "number" || hashLen < 2)
    throw new Error("hashLen must be a number");
  if (typeof qByteLen !== "number" || qByteLen < 2)
    throw new Error("qByteLen must be a number");
  if (typeof hmacFn !== "function")
    throw new Error("hmacFn must be a function");
  let v = u8n2(hashLen);
  let k = u8n2(hashLen);
  let i = 0;
  const reset = () => {
    v.fill(1);
    k.fill(0);
    i = 0;
  };
  const h = (...b) => hmacFn(k, v, ...b);
  const reseed = (seed = u8n2(0)) => {
    k = h(u8fr2([0]), seed);
    v = h();
    if (seed.length === 0)
      return;
    k = h(u8fr2([1]), seed);
    v = h();
  };
  const gen3 = () => {
    if (i++ >= 1e3)
      throw new Error("drbg: tried 1000 values");
    let len = 0;
    const out = [];
    while (len < qByteLen) {
      v = h();
      const sl = v.slice();
      out.push(sl);
      len += v.length;
    }
    return concatBytes4(...out);
  };
  const genUntil = (seed, pred) => {
    reset();
    reseed(seed);
    let res = void 0;
    while (!(res = pred(gen3())))
      reseed();
    reset();
    return res;
  };
  return genUntil;
}
function validateObject2(object, validators, optValidators = {}) {
  const checkField = (fieldName, type, isOptional) => {
    const checkVal = validatorFns2[type];
    if (typeof checkVal !== "function")
      throw new Error("invalid validator function");
    const val = object[fieldName];
    if (isOptional && val === void 0)
      return;
    if (!checkVal(val, object)) {
      throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val);
    }
  };
  for (const [fieldName, type] of Object.entries(validators))
    checkField(fieldName, type, false);
  for (const [fieldName, type] of Object.entries(optValidators))
    checkField(fieldName, type, true);
  return object;
}
function memoized2(fn) {
  const map = /* @__PURE__ */ new WeakMap();
  return (arg, ...args) => {
    const val = map.get(arg);
    if (val !== void 0)
      return val;
    const computed = fn(arg, ...args);
    map.set(arg, computed);
    return computed;
  };
}
var _0n7, _1n7, hasHexBuiltin2, hexes3, asciis2, isPosBig2, bitMask2, u8n2, u8fr2, validatorFns2;
var init_utils5 = __esm({
  "node_modules/ox/node_modules/@noble/curves/esm/abstract/utils.js"() {
    "use strict";
    _0n7 = /* @__PURE__ */ BigInt(0);
    _1n7 = /* @__PURE__ */ BigInt(1);
    hasHexBuiltin2 = // @ts-ignore
    typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function";
    hexes3 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
    asciis2 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
    isPosBig2 = (n) => typeof n === "bigint" && _0n7 <= n;
    bitMask2 = (n) => (_1n7 << BigInt(n)) - _1n7;
    u8n2 = (len) => new Uint8Array(len);
    u8fr2 = (arr) => Uint8Array.from(arr);
    validatorFns2 = {
      bigint: (val) => typeof val === "bigint",
      function: (val) => typeof val === "function",
      boolean: (val) => typeof val === "boolean",
      string: (val) => typeof val === "string",
      stringOrUint8Array: (val) => typeof val === "string" || isBytes3(val),
      isSafeInteger: (val) => Number.isSafeInteger(val),
      array: (val) => Array.isArray(val),
      field: (val, object) => object.Fp.isValid(val),
      hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen)
    };
  }
});

// node_modules/ox/_esm/core/version.js
var version3;
var init_version3 = __esm({
  "node_modules/ox/_esm/core/version.js"() {
    "use strict";
    version3 = "0.1.1";
  }
});

// node_modules/ox/_esm/core/internal/errors.js
function getVersion() {
  return version3;
}
var init_errors2 = __esm({
  "node_modules/ox/_esm/core/internal/errors.js"() {
    "use strict";
    init_version3();
  }
});

// node_modules/ox/_esm/core/Errors.js
function walk2(err, fn) {
  if (fn?.(err))
    return err;
  if (err && typeof err === "object" && "cause" in err && err.cause)
    return walk2(err.cause, fn);
  return fn ? null : err;
}
var BaseError3;
var init_Errors = __esm({
  "node_modules/ox/_esm/core/Errors.js"() {
    "use strict";
    init_errors2();
    BaseError3 = class _BaseError extends Error {
      static setStaticOptions(options) {
        _BaseError.prototype.docsOrigin = options.docsOrigin;
        _BaseError.prototype.showVersion = options.showVersion;
        _BaseError.prototype.version = options.version;
      }
      constructor(shortMessage, options = {}) {
        const details = (() => {
          if (options.cause instanceof _BaseError) {
            if (options.cause.details)
              return options.cause.details;
            if (options.cause.shortMessage)
              return options.cause.shortMessage;
          }
          if (options.cause && "details" in options.cause && typeof options.cause.details === "string")
            return options.cause.details;
          if (options.cause?.message)
            return options.cause.message;
          return options.details;
        })();
        const docsPath8 = (() => {
          if (options.cause instanceof _BaseError)
            return options.cause.docsPath || options.docsPath;
          return options.docsPath;
        })();
        const docsBaseUrl = options.docsOrigin ?? _BaseError.prototype.docsOrigin;
        const docs = `${docsBaseUrl}${docsPath8 ?? ""}`;
        const showVersion = Boolean(options.version ?? _BaseError.prototype.showVersion);
        const version4 = options.version ?? _BaseError.prototype.version;
        const message = [
          shortMessage || "An error occurred.",
          ...options.metaMessages ? ["", ...options.metaMessages] : [],
          ...details || docsPath8 || showVersion ? [
            "",
            details ? `Details: ${details}` : void 0,
            docsPath8 ? `See: ${docs}` : void 0,
            showVersion ? `Version: ${version4}` : void 0
          ] : []
        ].filter((x) => typeof x === "string").join("\n");
        super(message, options.cause ? { cause: options.cause } : void 0);
        Object.defineProperty(this, "details", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "docs", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "docsOrigin", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "docsPath", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "shortMessage", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "showVersion", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "version", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "cause", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "BaseError"
        });
        this.cause = options.cause;
        this.details = details;
        this.docs = docs;
        this.docsOrigin = docsBaseUrl;
        this.docsPath = docsPath8;
        this.shortMessage = shortMessage;
        this.showVersion = showVersion;
        this.version = version4;
      }
      walk(fn) {
        return walk2(this, fn);
      }
    };
    Object.defineProperty(BaseError3, "defaultStaticOptions", {
      enumerable: true,
      configurable: true,
      writable: true,
      value: {
        docsOrigin: "https://oxlib.sh",
        showVersion: false,
        version: `ox@${getVersion()}`
      }
    });
    (() => {
      BaseError3.setStaticOptions(BaseError3.defaultStaticOptions);
    })();
  }
});

// node_modules/ox/_esm/core/internal/bytes.js
function assertSize2(bytes, size_) {
  if (size2(bytes) > size_)
    throw new SizeOverflowError2({
      givenSize: size2(bytes),
      maxSize: size_
    });
}
function assertStartOffset2(value, start) {
  if (typeof start === "number" && start > 0 && start > size2(value) - 1)
    throw new SliceOffsetOutOfBoundsError2({
      offset: start,
      position: "start",
      size: size2(value)
    });
}
function assertEndOffset2(value, start, end) {
  if (typeof start === "number" && typeof end === "number" && size2(value) !== end - start) {
    throw new SliceOffsetOutOfBoundsError2({
      offset: end,
      position: "end",
      size: size2(value)
    });
  }
}
function charCodeToBase162(char) {
  if (char >= charCodeMap2.zero && char <= charCodeMap2.nine)
    return char - charCodeMap2.zero;
  if (char >= charCodeMap2.A && char <= charCodeMap2.F)
    return char - (charCodeMap2.A - 10);
  if (char >= charCodeMap2.a && char <= charCodeMap2.f)
    return char - (charCodeMap2.a - 10);
  return void 0;
}
function pad2(bytes, options = {}) {
  const { dir, size: size5 = 32 } = options;
  if (size5 === 0)
    return bytes;
  if (bytes.length > size5)
    throw new SizeExceedsPaddingSizeError2({
      size: bytes.length,
      targetSize: size5,
      type: "Bytes"
    });
  const paddedBytes = new Uint8Array(size5);
  for (let i = 0; i < size5; i++) {
    const padEnd = dir === "right";
    paddedBytes[padEnd ? i : size5 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
  }
  return paddedBytes;
}
function trim2(value, options = {}) {
  const { dir = "left" } = options;
  let data = value;
  let sliceLength = 0;
  for (let i = 0; i < data.length - 1; i++) {
    if (data[dir === "left" ? i : data.length - i - 1].toString() === "0")
      sliceLength++;
    else
      break;
  }
  data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength);
  return data;
}
var charCodeMap2;
var init_bytes = __esm({
  "node_modules/ox/_esm/core/internal/bytes.js"() {
    "use strict";
    init_Bytes();
    charCodeMap2 = {
      zero: 48,
      nine: 57,
      A: 65,
      F: 70,
      a: 97,
      f: 102
    };
  }
});

// node_modules/ox/_esm/core/internal/hex.js
function assertSize3(hex, size_) {
  if (size3(hex) > size_)
    throw new SizeOverflowError3({
      givenSize: size3(hex),
      maxSize: size_
    });
}
function assertStartOffset3(value, start) {
  if (typeof start === "number" && start > 0 && start > size3(value) - 1)
    throw new SliceOffsetOutOfBoundsError3({
      offset: start,
      position: "start",
      size: size3(value)
    });
}
function assertEndOffset3(value, start, end) {
  if (typeof start === "number" && typeof end === "number" && size3(value) !== end - start) {
    throw new SliceOffsetOutOfBoundsError3({
      offset: end,
      position: "end",
      size: size3(value)
    });
  }
}
function pad3(hex_, options = {}) {
  const { dir, size: size5 = 32 } = options;
  if (size5 === 0)
    return hex_;
  const hex = hex_.replace("0x", "");
  if (hex.length > size5 * 2)
    throw new SizeExceedsPaddingSizeError3({
      size: Math.ceil(hex.length / 2),
      targetSize: size5,
      type: "Hex"
    });
  return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size5 * 2, "0")}`;
}
function trim3(value, options = {}) {
  const { dir = "left" } = options;
  let data = value.replace("0x", "");
  let sliceLength = 0;
  for (let i = 0; i < data.length - 1; i++) {
    if (data[dir === "left" ? i : data.length - i - 1].toString() === "0")
      sliceLength++;
    else
      break;
  }
  data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength);
  if (data === "0")
    return "0x";
  if (dir === "right" && data.length % 2 === 1)
    return `0x${data}0`;
  return `0x${data}`;
}
var init_hex = __esm({
  "node_modules/ox/_esm/core/internal/hex.js"() {
    "use strict";
    init_Hex();
  }
});

// node_modules/ox/_esm/core/Json.js
function stringify2(value, replacer, space) {
  return JSON.stringify(value, (key, value2) => {
    if (typeof replacer === "function")
      return replacer(key, value2);
    if (typeof value2 === "bigint")
      return value2.toString() + bigIntSuffix;
    return value2;
  }, space);
}
var bigIntSuffix;
var init_Json = __esm({
  "node_modules/ox/_esm/core/Json.js"() {
    "use strict";
    bigIntSuffix = "#__bigint";
  }
});

// node_modules/ox/_esm/core/Bytes.js
function assert(value) {
  if (value instanceof Uint8Array)
    return;
  if (!value)
    throw new InvalidBytesTypeError(value);
  if (typeof value !== "object")
    throw new InvalidBytesTypeError(value);
  if (!("BYTES_PER_ELEMENT" in value))
    throw new InvalidBytesTypeError(value);
  if (value.BYTES_PER_ELEMENT !== 1 || value.constructor.name !== "Uint8Array")
    throw new InvalidBytesTypeError(value);
}
function from(value) {
  if (value instanceof Uint8Array)
    return value;
  if (typeof value === "string")
    return fromHex(value);
  return fromArray(value);
}
function fromArray(value) {
  return value instanceof Uint8Array ? value : new Uint8Array(value);
}
function fromHex(value, options = {}) {
  const { size: size5 } = options;
  let hex = value;
  if (size5) {
    assertSize3(value, size5);
    hex = padRight(value, size5);
  }
  let hexString = hex.slice(2);
  if (hexString.length % 2)
    hexString = `0${hexString}`;
  const length = hexString.length / 2;
  const bytes = new Uint8Array(length);
  for (let index2 = 0, j = 0; index2 < length; index2++) {
    const nibbleLeft = charCodeToBase162(hexString.charCodeAt(j++));
    const nibbleRight = charCodeToBase162(hexString.charCodeAt(j++));
    if (nibbleLeft === void 0 || nibbleRight === void 0) {
      throw new BaseError3(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`);
    }
    bytes[index2] = nibbleLeft << 4 | nibbleRight;
  }
  return bytes;
}
function fromString(value, options = {}) {
  const { size: size5 } = options;
  const bytes = encoder3.encode(value);
  if (typeof size5 === "number") {
    assertSize2(bytes, size5);
    return padRight2(bytes, size5);
  }
  return bytes;
}
function padRight2(value, size5) {
  return pad2(value, { dir: "right", size: size5 });
}
function size2(value) {
  return value.length;
}
function slice2(value, start, end, options = {}) {
  const { strict } = options;
  assertStartOffset2(value, start);
  const value_ = value.slice(start, end);
  if (strict)
    assertEndOffset2(value_, start, end);
  return value_;
}
function toBigInt2(bytes, options = {}) {
  const { size: size5 } = options;
  if (typeof size5 !== "undefined")
    assertSize2(bytes, size5);
  const hex = fromBytes(bytes, options);
  return toBigInt(hex, options);
}
function toBoolean(bytes, options = {}) {
  const { size: size5 } = options;
  let bytes_ = bytes;
  if (typeof size5 !== "undefined") {
    assertSize2(bytes_, size5);
    bytes_ = trimLeft(bytes_);
  }
  if (bytes_.length > 1 || bytes_[0] > 1)
    throw new InvalidBytesBooleanError2(bytes_);
  return Boolean(bytes_[0]);
}
function toNumber2(bytes, options = {}) {
  const { size: size5 } = options;
  if (typeof size5 !== "undefined")
    assertSize2(bytes, size5);
  const hex = fromBytes(bytes, options);
  return toNumber(hex, options);
}
function toString(bytes, options = {}) {
  const { size: size5 } = options;
  let bytes_ = bytes;
  if (typeof size5 !== "undefined") {
    assertSize2(bytes_, size5);
    bytes_ = trimRight(bytes_);
  }
  return decoder.decode(bytes_);
}
function trimLeft(value) {
  return trim2(value, { dir: "left" });
}
function trimRight(value) {
  return trim2(value, { dir: "right" });
}
function validate(value) {
  try {
    assert(value);
    return true;
  } catch {
    return false;
  }
}
var decoder, encoder3, InvalidBytesBooleanError2, InvalidBytesTypeError, SizeOverflowError2, SliceOffsetOutOfBoundsError2, SizeExceedsPaddingSizeError2;
var init_Bytes = __esm({
  "node_modules/ox/_esm/core/Bytes.js"() {
    "use strict";
    init_Errors();
    init_Hex();
    init_bytes();
    init_hex();
    init_Json();
    decoder = /* @__PURE__ */ new TextDecoder();
    encoder3 = /* @__PURE__ */ new TextEncoder();
    InvalidBytesBooleanError2 = class extends BaseError3 {
      constructor(bytes) {
        super(`Bytes value \`${bytes}\` is not a valid boolean.`, {
          metaMessages: [
            "The bytes array must contain a single byte of either a `0` or `1` value."
          ]
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Bytes.InvalidBytesBooleanError"
        });
      }
    };
    InvalidBytesTypeError = class extends BaseError3 {
      constructor(value) {
        super(`Value \`${typeof value === "object" ? stringify2(value) : value}\` of type \`${typeof value}\` is an invalid Bytes value.`, {
          metaMessages: ["Bytes values must be of type `Bytes`."]
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Bytes.InvalidBytesTypeError"
        });
      }
    };
    SizeOverflowError2 = class extends BaseError3 {
      constructor({ givenSize, maxSize }) {
        super(`Size cannot exceed \`${maxSize}\` bytes. Given size: \`${givenSize}\` bytes.`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Bytes.SizeOverflowError"
        });
      }
    };
    SliceOffsetOutOfBoundsError2 = class extends BaseError3 {
      constructor({ offset, position, size: size5 }) {
        super(`Slice ${position === "start" ? "starting" : "ending"} at offset \`${offset}\` is out-of-bounds (size: \`${size5}\`).`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Bytes.SliceOffsetOutOfBoundsError"
        });
      }
    };
    SizeExceedsPaddingSizeError2 = class extends BaseError3 {
      constructor({ size: size5, targetSize, type }) {
        super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size5}\`) exceeds padding size (\`${targetSize}\`).`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Bytes.SizeExceedsPaddingSizeError"
        });
      }
    };
  }
});

// node_modules/ox/_esm/core/Hex.js
function assert2(value, options = {}) {
  const { strict = false } = options;
  if (!value)
    throw new InvalidHexTypeError(value);
  if (typeof value !== "string")
    throw new InvalidHexTypeError(value);
  if (strict) {
    if (!/^0x[0-9a-fA-F]*$/.test(value))
      throw new InvalidHexValueError(value);
  }
  if (!value.startsWith("0x"))
    throw new InvalidHexValueError(value);
}
function concat2(...values) {
  return `0x${values.reduce((acc, x) => acc + x.replace("0x", ""), "")}`;
}
function from2(value) {
  if (value instanceof Uint8Array)
    return fromBytes(value);
  if (Array.isArray(value))
    return fromBytes(new Uint8Array(value));
  return value;
}
function fromBoolean(value, options = {}) {
  const hex = `0x${Number(value)}`;
  if (typeof options.size === "number") {
    assertSize3(hex, options.size);
    return padLeft(hex, options.size);
  }
  return hex;
}
function fromBytes(value, options = {}) {
  let string = "";
  for (let i = 0; i < value.length; i++)
    string += hexes4[value[i]];
  const hex = `0x${string}`;
  if (typeof options.size === "number") {
    assertSize3(hex, options.size);
    return padRight(hex, options.size);
  }
  return hex;
}
function fromNumber(value, options = {}) {
  const { signed, size: size5 } = options;
  const value_ = BigInt(value);
  let maxValue;
  if (size5) {
    if (signed)
      maxValue = (1n << BigInt(size5) * 8n - 1n) - 1n;
    else
      maxValue = 2n ** (BigInt(size5) * 8n) - 1n;
  } else if (typeof value === "number") {
    maxValue = BigInt(Number.MAX_SAFE_INTEGER);
  }
  const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0;
  if (maxValue && value_ > maxValue || value_ < minValue) {
    const suffix = typeof value === "bigint" ? "n" : "";
    throw new IntegerOutOfRangeError2({
      max: maxValue ? `${maxValue}${suffix}` : void 0,
      min: `${minValue}${suffix}`,
      signed,
      size: size5,
      value: `${value}${suffix}`
    });
  }
  const stringValue = (signed && value_ < 0 ? BigInt.asUintN(size5 * 8, BigInt(value_)) : value_).toString(16);
  const hex = `0x${stringValue}`;
  if (size5)
    return padLeft(hex, size5);
  return hex;
}
function fromString2(value, options = {}) {
  return fromBytes(encoder4.encode(value), options);
}
function padLeft(value, size5) {
  return pad3(value, { dir: "left", size: size5 });
}
function padRight(value, size5) {
  return pad3(value, { dir: "right", size: size5 });
}
function slice3(value, start, end, options = {}) {
  const { strict } = options;
  assertStartOffset3(value, start);
  const value_ = `0x${value.replace("0x", "").slice((start ?? 0) * 2, (end ?? value.length) * 2)}`;
  if (strict)
    assertEndOffset3(value_, start, end);
  return value_;
}
function size3(value) {
  return Math.ceil((value.length - 2) / 2);
}
function trimLeft2(value) {
  return trim3(value, { dir: "left" });
}
function toBigInt(hex, options = {}) {
  const { signed } = options;
  if (options.size)
    assertSize3(hex, options.size);
  const value = BigInt(hex);
  if (!signed)
    return value;
  const size5 = (hex.length - 2) / 2;
  const max_unsigned = (1n << BigInt(size5) * 8n) - 1n;
  const max_signed = max_unsigned >> 1n;
  if (value <= max_signed)
    return value;
  return value - max_unsigned - 1n;
}
function toNumber(hex, options = {}) {
  const { signed, size: size5 } = options;
  if (!signed && !size5)
    return Number(hex);
  return Number(toBigInt(hex, options));
}
function validate2(value, options = {}) {
  const { strict = false } = options;
  try {
    assert2(value, { strict });
    return true;
  } catch {
    return false;
  }
}
var encoder4, hexes4, IntegerOutOfRangeError2, InvalidHexTypeError, InvalidHexValueError, SizeOverflowError3, SliceOffsetOutOfBoundsError3, SizeExceedsPaddingSizeError3;
var init_Hex = __esm({
  "node_modules/ox/_esm/core/Hex.js"() {
    "use strict";
    init_Errors();
    init_hex();
    init_Json();
    encoder4 = /* @__PURE__ */ new TextEncoder();
    hexes4 = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0"));
    IntegerOutOfRangeError2 = class extends BaseError3 {
      constructor({ max, min, signed, size: size5, value }) {
        super(`Number \`${value}\` is not in safe${size5 ? ` ${size5 * 8}-bit` : ""}${signed ? " signed" : " unsigned"} integer range ${max ? `(\`${min}\` to \`${max}\`)` : `(above \`${min}\`)`}`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Hex.IntegerOutOfRangeError"
        });
      }
    };
    InvalidHexTypeError = class extends BaseError3 {
      constructor(value) {
        super(`Value \`${typeof value === "object" ? stringify2(value) : value}\` of type \`${typeof value}\` is an invalid hex type.`, {
          metaMessages: ['Hex types must be represented as `"0x${string}"`.']
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Hex.InvalidHexTypeError"
        });
      }
    };
    InvalidHexValueError = class extends BaseError3 {
      constructor(value) {
        super(`Value \`${value}\` is an invalid hex value.`, {
          metaMessages: [
            'Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).'
          ]
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Hex.InvalidHexValueError"
        });
      }
    };
    SizeOverflowError3 = class extends BaseError3 {
      constructor({ givenSize, maxSize }) {
        super(`Size cannot exceed \`${maxSize}\` bytes. Given size: \`${givenSize}\` bytes.`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Hex.SizeOverflowError"
        });
      }
    };
    SliceOffsetOutOfBoundsError3 = class extends BaseError3 {
      constructor({ offset, position, size: size5 }) {
        super(`Slice ${position === "start" ? "starting" : "ending"} at offset \`${offset}\` is out-of-bounds (size: \`${size5}\`).`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Hex.SliceOffsetOutOfBoundsError"
        });
      }
    };
    SizeExceedsPaddingSizeError3 = class extends BaseError3 {
      constructor({ size: size5, targetSize, type }) {
        super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size5}\`) exceeds padding size (\`${targetSize}\`).`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Hex.SizeExceedsPaddingSizeError"
        });
      }
    };
  }
});

// node_modules/ox/_esm/core/Withdrawal.js
function toRpc(withdrawal) {
  return {
    address: withdrawal.address,
    amount: fromNumber(withdrawal.amount),
    index: fromNumber(withdrawal.index),
    validatorIndex: fromNumber(withdrawal.validatorIndex)
  };
}
var init_Withdrawal = __esm({
  "node_modules/ox/_esm/core/Withdrawal.js"() {
    "use strict";
    init_Hex();
  }
});

// node_modules/ox/_esm/core/BlockOverrides.js
function toRpc2(blockOverrides) {
  return {
    ...typeof blockOverrides.baseFeePerGas === "bigint" && {
      baseFeePerGas: fromNumber(blockOverrides.baseFeePerGas)
    },
    ...typeof blockOverrides.blobBaseFee === "bigint" && {
      blobBaseFee: fromNumber(blockOverrides.blobBaseFee)
    },
    ...typeof blockOverrides.feeRecipient === "string" && {
      feeRecipient: blockOverrides.feeRecipient
    },
    ...typeof blockOverrides.gasLimit === "bigint" && {
      gasLimit: fromNumber(blockOverrides.gasLimit)
    },
    ...typeof blockOverrides.number === "bigint" && {
      number: fromNumber(blockOverrides.number)
    },
    ...typeof blockOverrides.prevRandao === "bigint" && {
      prevRandao: fromNumber(blockOverrides.prevRandao)
    },
    ...typeof blockOverrides.time === "bigint" && {
      time: fromNumber(blockOverrides.time)
    },
    ...blockOverrides.withdrawals && {
      withdrawals: blockOverrides.withdrawals.map(toRpc)
    }
  };
}
var init_BlockOverrides = __esm({
  "node_modules/ox/_esm/core/BlockOverrides.js"() {
    "use strict";
    init_Hex();
    init_Withdrawal();
  }
});

// node_modules/viem/_esm/constants/abis.js
var multicall3Abi, batchGatewayAbi, universalResolverErrors, universalResolverResolveAbi, universalResolverReverseAbi, textResolverAbi, addressResolverAbi, erc1271Abi, erc6492SignatureValidatorAbi, erc20Abi;
var init_abis = __esm({
  "node_modules/viem/_esm/constants/abis.js"() {
    "use strict";
    multicall3Abi = [
      {
        inputs: [
          {
            components: [
              {
                name: "target",
                type: "address"
              },
              {
                name: "allowFailure",
                type: "bool"
              },
              {
                name: "callData",
                type: "bytes"
              }
            ],
            name: "calls",
            type: "tuple[]"
          }
        ],
        name: "aggregate3",
        outputs: [
          {
            components: [
              {
                name: "success",
                type: "bool"
              },
              {
                name: "returnData",
                type: "bytes"
              }
            ],
            name: "returnData",
            type: "tuple[]"
          }
        ],
        stateMutability: "view",
        type: "function"
      },
      {
        inputs: [
          {
            name: "addr",
            type: "address"
          }
        ],
        name: "getEthBalance",
        outputs: [
          {
            name: "balance",
            type: "uint256"
          }
        ],
        stateMutability: "view",
        type: "function"
      },
      {
        inputs: [],
        name: "getCurrentBlockTimestamp",
        outputs: [
          {
            internalType: "uint256",
            name: "timestamp",
            type: "uint256"
          }
        ],
        stateMutability: "view",
        type: "function"
      }
    ];
    batchGatewayAbi = [
      {
        name: "query",
        type: "function",
        stateMutability: "view",
        inputs: [
          {
            type: "tuple[]",
            name: "queries",
            components: [
              {
                type: "address",
                name: "sender"
              },
              {
                type: "string[]",
                name: "urls"
              },
              {
                type: "bytes",
                name: "data"
              }
            ]
          }
        ],
        outputs: [
          {
            type: "bool[]",
            name: "failures"
          },
          {
            type: "bytes[]",
            name: "responses"
          }
        ]
      },
      {
        name: "HttpError",
        type: "error",
        inputs: [
          {
            type: "uint16",
            name: "status"
          },
          {
            type: "string",
            name: "message"
          }
        ]
      }
    ];
    universalResolverErrors = [
      {
        inputs: [
          {
            name: "dns",
            type: "bytes"
          }
        ],
        name: "DNSDecodingFailed",
        type: "error"
      },
      {
        inputs: [
          {
            name: "ens",
            type: "string"
          }
        ],
        name: "DNSEncodingFailed",
        type: "error"
      },
      {
        inputs: [],
        name: "EmptyAddress",
        type: "error"
      },
      {
        inputs: [
          {
            name: "status",
            type: "uint16"
          },
          {
            name: "message",
            type: "string"
          }
        ],
        name: "HttpError",
        type: "error"
      },
      {
        inputs: [],
        name: "InvalidBatchGatewayResponse",
        type: "error"
      },
      {
        inputs: [
          {
            name: "errorData",
            type: "bytes"
          }
        ],
        name: "ResolverError",
        type: "error"
      },
      {
        inputs: [
          {
            name: "name",
            type: "bytes"
          },
          {
            name: "resolver",
            type: "address"
          }
        ],
        name: "ResolverNotContract",
        type: "error"
      },
      {
        inputs: [
          {
            name: "name",
            type: "bytes"
          }
        ],
        name: "ResolverNotFound",
        type: "error"
      },
      {
        inputs: [
          {
            name: "primary",
            type: "string"
          },
          {
            name: "primaryAddress",
            type: "bytes"
          }
        ],
        name: "ReverseAddressMismatch",
        type: "error"
      },
      {
        inputs: [
          {
            internalType: "bytes4",
            name: "selector",
            type: "bytes4"
          }
        ],
        name: "UnsupportedResolverProfile",
        type: "error"
      }
    ];
    universalResolverResolveAbi = [
      ...universalResolverErrors,
      {
        name: "resolveWithGateways",
        type: "function",
        stateMutability: "view",
        inputs: [
          { name: "name", type: "bytes" },
          { name: "data", type: "bytes" },
          { name: "gateways", type: "string[]" }
        ],
        outputs: [
          { name: "", type: "bytes" },
          { name: "address", type: "address" }
        ]
      }
    ];
    universalResolverReverseAbi = [
      ...universalResolverErrors,
      {
        name: "reverseWithGateways",
        type: "function",
        stateMutability: "view",
        inputs: [
          { type: "bytes", name: "reverseName" },
          { type: "uint256", name: "coinType" },
          { type: "string[]", name: "gateways" }
        ],
        outputs: [
          { type: "string", name: "resolvedName" },
          { type: "address", name: "resolver" },
          { type: "address", name: "reverseResolver" }
        ]
      }
    ];
    textResolverAbi = [
      {
        name: "text",
        type: "function",
        stateMutability: "view",
        inputs: [
          { name: "name", type: "bytes32" },
          { name: "key", type: "string" }
        ],
        outputs: [{ name: "", type: "string" }]
      }
    ];
    addressResolverAbi = [
      {
        name: "addr",
        type: "function",
        stateMutability: "view",
        inputs: [{ name: "name", type: "bytes32" }],
        outputs: [{ name: "", type: "address" }]
      },
      {
        name: "addr",
        type: "function",
        stateMutability: "view",
        inputs: [
          { name: "name", type: "bytes32" },
          { name: "coinType", type: "uint256" }
        ],
        outputs: [{ name: "", type: "bytes" }]
      }
    ];
    erc1271Abi = [
      {
        name: "isValidSignature",
        type: "function",
        stateMutability: "view",
        inputs: [
          { name: "hash", type: "bytes32" },
          { name: "signature", type: "bytes" }
        ],
        outputs: [{ name: "", type: "bytes4" }]
      }
    ];
    erc6492SignatureValidatorAbi = [
      {
        inputs: [
          {
            name: "_signer",
            type: "address"
          },
          {
            name: "_hash",
            type: "bytes32"
          },
          {
            name: "_signature",
            type: "bytes"
          }
        ],
        stateMutability: "nonpayable",
        type: "constructor"
      },
      {
        inputs: [
          {
            name: "_signer",
            type: "address"
          },
          {
            name: "_hash",
            type: "bytes32"
          },
          {
            name: "_signature",
            type: "bytes"
          }
        ],
        outputs: [
          {
            type: "bool"
          }
        ],
        stateMutability: "nonpayable",
        type: "function",
        name: "isValidSig"
      }
    ];
    erc20Abi = [
      {
        type: "event",
        name: "Approval",
        inputs: [
          {
            indexed: true,
            name: "owner",
            type: "address"
          },
          {
            indexed: true,
            name: "spender",
            type: "address"
          },
          {
            indexed: false,
            name: "value",
            type: "uint256"
          }
        ]
      },
      {
        type: "event",
        name: "Transfer",
        inputs: [
          {
            indexed: true,
            name: "from",
            type: "address"
          },
          {
            indexed: true,
            name: "to",
            type: "address"
          },
          {
            indexed: false,
            name: "value",
            type: "uint256"
          }
        ]
      },
      {
        type: "function",
        name: "allowance",
        stateMutability: "view",
        inputs: [
          {
            name: "owner",
            type: "address"
          },
          {
            name: "spender",
            type: "address"
          }
        ],
        outputs: [
          {
            type: "uint256"
          }
        ]
      },
      {
        type: "function",
        name: "approve",
        stateMutability: "nonpayable",
        inputs: [
          {
            name: "spender",
            type: "address"
          },
          {
            name: "amount",
            type: "uint256"
          }
        ],
        outputs: [
          {
            type: "bool"
          }
        ]
      },
      {
        type: "function",
        name: "balanceOf",
        stateMutability: "view",
        inputs: [
          {
            name: "account",
            type: "address"
          }
        ],
        outputs: [
          {
            type: "uint256"
          }
        ]
      },
      {
        type: "function",
        name: "decimals",
        stateMutability: "view",
        inputs: [],
        outputs: [
          {
            type: "uint8"
          }
        ]
      },
      {
        type: "function",
        name: "name",
        stateMutability: "view",
        inputs: [],
        outputs: [
          {
            type: "string"
          }
        ]
      },
      {
        type: "function",
        name: "symbol",
        stateMutability: "view",
        inputs: [],
        outputs: [
          {
            type: "string"
          }
        ]
      },
      {
        type: "function",
        name: "totalSupply",
        stateMutability: "view",
        inputs: [],
        outputs: [
          {
            type: "uint256"
          }
        ]
      },
      {
        type: "function",
        name: "transfer",
        stateMutability: "nonpayable",
        inputs: [
          {
            name: "recipient",
            type: "address"
          },
          {
            name: "amount",
            type: "uint256"
          }
        ],
        outputs: [
          {
            type: "bool"
          }
        ]
      },
      {
        type: "function",
        name: "transferFrom",
        stateMutability: "nonpayable",
        inputs: [
          {
            name: "sender",
            type: "address"
          },
          {
            name: "recipient",
            type: "address"
          },
          {
            name: "amount",
            type: "uint256"
          }
        ],
        outputs: [
          {
            type: "bool"
          }
        ]
      }
    ];
  }
});

// node_modules/viem/_esm/constants/contract.js
var aggregate3Signature;
var init_contract2 = __esm({
  "node_modules/viem/_esm/constants/contract.js"() {
    "use strict";
    aggregate3Signature = "0x82ad56cb";
  }
});

// node_modules/viem/_esm/constants/contracts.js
var deploylessCallViaBytecodeBytecode, deploylessCallViaFactoryBytecode, erc6492SignatureValidatorByteCode, multicall3Bytecode;
var init_contracts = __esm({
  "node_modules/viem/_esm/constants/contracts.js"() {
    "use strict";
    deploylessCallViaBytecodeBytecode = "0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe";
    deploylessCallViaFactoryBytecode = "0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe";
    erc6492SignatureValidatorByteCode = "0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572";
    multicall3Bytecode = " ";
  }
});

// node_modules/viem/_esm/errors/chain.js
var ChainDoesNotSupportContract, ClientChainNotConfiguredError, InvalidChainIdError;
var init_chain = __esm({
  "node_modules/viem/_esm/errors/chain.js"() {
    "use strict";
    init_base();
    ChainDoesNotSupportContract = class extends BaseError2 {
      constructor({ blockNumber, chain: chain3, contract }) {
        super(`Chain "${chain3.name}" does not support contract "${contract.name}".`, {
          metaMessages: [
            "This could be due to any of the following:",
            ...blockNumber && contract.blockCreated && contract.blockCreated > blockNumber ? [
              `- The contract "${contract.name}" was not deployed until block ${contract.blockCreated} (current block ${blockNumber}).`
            ] : [
              `- The chain does not have the contract "${contract.name}" configured.`
            ]
          ],
          name: "ChainDoesNotSupportContract"
        });
      }
    };
    ClientChainNotConfiguredError = class extends BaseError2 {
      constructor() {
        super("No chain was provided to the Client.", {
          name: "ClientChainNotConfiguredError"
        });
      }
    };
    InvalidChainIdError = class extends BaseError2 {
      constructor({ chainId }) {
        super(typeof chainId === "number" ? `Chain ID "${chainId}" is invalid.` : "Chain ID is invalid.", { name: "InvalidChainIdError" });
      }
    };
  }
});

// node_modules/viem/_esm/utils/abi/encodeDeployData.js
function encodeDeployData(parameters) {
  const { abi: abi2, args, bytecode } = parameters;
  if (!args || args.length === 0)
    return bytecode;
  const description = abi2.find((x) => "type" in x && x.type === "constructor");
  if (!description)
    throw new AbiConstructorNotFoundError({ docsPath: docsPath5 });
  if (!("inputs" in description))
    throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath5 });
  if (!description.inputs || description.inputs.length === 0)
    throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath5 });
  const data = encodeAbiParameters(description.inputs, args);
  return concatHex([bytecode, data]);
}
var docsPath5;
var init_encodeDeployData = __esm({
  "node_modules/viem/_esm/utils/abi/encodeDeployData.js"() {
    "use strict";
    init_abi();
    init_concat();
    init_encodeAbiParameters();
    docsPath5 = "/docs/contract/encodeDeployData";
  }
});

// node_modules/viem/_esm/utils/chain/getChainContractAddress.js
function getChainContractAddress({ blockNumber, chain: chain3, contract: name }) {
  const contract = chain3?.contracts?.[name];
  if (!contract)
    throw new ChainDoesNotSupportContract({
      chain: chain3,
      contract: { name }
    });
  if (blockNumber && contract.blockCreated && contract.blockCreated > blockNumber)
    throw new ChainDoesNotSupportContract({
      blockNumber,
      chain: chain3,
      contract: {
        name,
        blockCreated: contract.blockCreated
      }
    });
  return contract.address;
}
var init_getChainContractAddress = __esm({
  "node_modules/viem/_esm/utils/chain/getChainContractAddress.js"() {
    "use strict";
    init_chain();
  }
});

// node_modules/viem/_esm/utils/errors/getCallError.js
function getCallError(err, { docsPath: docsPath8, ...args }) {
  const cause = (() => {
    const cause2 = getNodeError(err, args);
    if (cause2 instanceof UnknownNodeError)
      return err;
    return cause2;
  })();
  return new CallExecutionError(cause, {
    docsPath: docsPath8,
    ...args
  });
}
var init_getCallError = __esm({
  "node_modules/viem/_esm/utils/errors/getCallError.js"() {
    "use strict";
    init_contract();
    init_node();
    init_getNodeError();
  }
});

// node_modules/viem/_esm/utils/promise/withResolvers.js
function withResolvers() {
  let resolve = () => void 0;
  let reject = () => void 0;
  const promise = new Promise((resolve_, reject_) => {
    resolve = resolve_;
    reject = reject_;
  });
  return { promise, resolve, reject };
}
var init_withResolvers = __esm({
  "node_modules/viem/_esm/utils/promise/withResolvers.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/utils/promise/createBatchScheduler.js
function createBatchScheduler({ fn, id, shouldSplitBatch, wait: wait2 = 0, sort }) {
  const exec = async () => {
    const scheduler = getScheduler();
    flush();
    const args = scheduler.map(({ args: args2 }) => args2);
    if (args.length === 0)
      return;
    fn(args).then((data) => {
      if (sort && Array.isArray(data))
        data.sort(sort);
      for (let i = 0; i < scheduler.length; i++) {
        const { resolve } = scheduler[i];
        resolve?.([data[i], data]);
      }
    }).catch((err) => {
      for (let i = 0; i < scheduler.length; i++) {
        const { reject } = scheduler[i];
        reject?.(err);
      }
    });
  };
  const flush = () => schedulerCache.delete(id);
  const getBatchedArgs = () => getScheduler().map(({ args }) => args);
  const getScheduler = () => schedulerCache.get(id) || [];
  const setScheduler = (item) => schedulerCache.set(id, [...getScheduler(), item]);
  return {
    flush,
    async schedule(args) {
      const { promise, resolve, reject } = withResolvers();
      const split5 = shouldSplitBatch?.([...getBatchedArgs(), args]);
      if (split5)
        exec();
      const hasActiveScheduler = getScheduler().length > 0;
      if (hasActiveScheduler) {
        setScheduler({ args, resolve, reject });
        return promise;
      }
      setScheduler({ args, resolve, reject });
      setTimeout(exec, wait2);
      return promise;
    }
  };
}
var schedulerCache;
var init_createBatchScheduler = __esm({
  "node_modules/viem/_esm/utils/promise/createBatchScheduler.js"() {
    "use strict";
    init_withResolvers();
    schedulerCache = /* @__PURE__ */ new Map();
  }
});

// node_modules/viem/_esm/errors/ccip.js
var OffchainLookupError, OffchainLookupResponseMalformedError, OffchainLookupSenderMismatchError;
var init_ccip = __esm({
  "node_modules/viem/_esm/errors/ccip.js"() {
    "use strict";
    init_stringify();
    init_base();
    init_utils3();
    OffchainLookupError = class extends BaseError2 {
      constructor({ callbackSelector, cause, data, extraData, sender, urls }) {
        super(cause.shortMessage || "An error occurred while fetching for an offchain result.", {
          cause,
          metaMessages: [
            ...cause.metaMessages || [],
            cause.metaMessages?.length ? "" : [],
            "Offchain Gateway Call:",
            urls && [
              "  Gateway URL(s):",
              ...urls.map((url) => `    ${getUrl(url)}`)
            ],
            `  Sender: ${sender}`,
            `  Data: ${data}`,
            `  Callback selector: ${callbackSelector}`,
            `  Extra data: ${extraData}`
          ].flat(),
          name: "OffchainLookupError"
        });
      }
    };
    OffchainLookupResponseMalformedError = class extends BaseError2 {
      constructor({ result, url }) {
        super("Offchain gateway response is malformed. Response data must be a hex value.", {
          metaMessages: [
            `Gateway URL: ${getUrl(url)}`,
            `Response: ${stringify(result)}`
          ],
          name: "OffchainLookupResponseMalformedError"
        });
      }
    };
    OffchainLookupSenderMismatchError = class extends BaseError2 {
      constructor({ sender, to }) {
        super("Reverted sender address does not match target contract address (`to`).", {
          metaMessages: [
            `Contract address: ${to}`,
            `OffchainLookup sender address: ${sender}`
          ],
          name: "OffchainLookupSenderMismatchError"
        });
      }
    };
  }
});

// node_modules/viem/_esm/utils/abi/decodeFunctionData.js
function decodeFunctionData(parameters) {
  const { abi: abi2, data } = parameters;
  const signature2 = slice(data, 0, 4);
  const description = abi2.find((x) => x.type === "function" && signature2 === toFunctionSelector(formatAbiItem2(x)));
  if (!description)
    throw new AbiFunctionSignatureNotFoundError(signature2, {
      docsPath: "/docs/contract/decodeFunctionData"
    });
  return {
    functionName: description.name,
    args: "inputs" in description && description.inputs && description.inputs.length > 0 ? decodeAbiParameters(description.inputs, slice(data, 4)) : void 0
  };
}
var init_decodeFunctionData = __esm({
  "node_modules/viem/_esm/utils/abi/decodeFunctionData.js"() {
    "use strict";
    init_abi();
    init_slice();
    init_toFunctionSelector();
    init_decodeAbiParameters();
    init_formatAbiItem2();
  }
});

// node_modules/viem/_esm/utils/abi/encodeErrorResult.js
function encodeErrorResult(parameters) {
  const { abi: abi2, errorName, args } = parameters;
  let abiItem = abi2[0];
  if (errorName) {
    const item = getAbiItem({ abi: abi2, args, name: errorName });
    if (!item)
      throw new AbiErrorNotFoundError(errorName, { docsPath: docsPath6 });
    abiItem = item;
  }
  if (abiItem.type !== "error")
    throw new AbiErrorNotFoundError(void 0, { docsPath: docsPath6 });
  const definition = formatAbiItem2(abiItem);
  const signature2 = toFunctionSelector(definition);
  let data = "0x";
  if (args && args.length > 0) {
    if (!abiItem.inputs)
      throw new AbiErrorInputsNotFoundError(abiItem.name, { docsPath: docsPath6 });
    data = encodeAbiParameters(abiItem.inputs, args);
  }
  return concatHex([signature2, data]);
}
var docsPath6;
var init_encodeErrorResult = __esm({
  "node_modules/viem/_esm/utils/abi/encodeErrorResult.js"() {
    "use strict";
    init_abi();
    init_concat();
    init_toFunctionSelector();
    init_encodeAbiParameters();
    init_formatAbiItem2();
    init_getAbiItem();
    docsPath6 = "/docs/contract/encodeErrorResult";
  }
});

// node_modules/viem/_esm/utils/abi/encodeFunctionResult.js
function encodeFunctionResult(parameters) {
  const { abi: abi2, functionName, result } = parameters;
  let abiItem = abi2[0];
  if (functionName) {
    const item = getAbiItem({ abi: abi2, name: functionName });
    if (!item)
      throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath7 });
    abiItem = item;
  }
  if (abiItem.type !== "function")
    throw new AbiFunctionNotFoundError(void 0, { docsPath: docsPath7 });
  if (!abiItem.outputs)
    throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath: docsPath7 });
  const values = (() => {
    if (abiItem.outputs.length === 0)
      return [];
    if (abiItem.outputs.length === 1)
      return [result];
    if (Array.isArray(result))
      return result;
    throw new InvalidArrayError(result);
  })();
  return encodeAbiParameters(abiItem.outputs, values);
}
var docsPath7;
var init_encodeFunctionResult = __esm({
  "node_modules/viem/_esm/utils/abi/encodeFunctionResult.js"() {
    "use strict";
    init_abi();
    init_encodeAbiParameters();
    init_getAbiItem();
    docsPath7 = "/docs/contract/encodeFunctionResult";
  }
});

// node_modules/viem/_esm/utils/ens/localBatchGatewayRequest.js
async function localBatchGatewayRequest(parameters) {
  const { data, ccipRequest: ccipRequest2 } = parameters;
  const { args: [queries] } = decodeFunctionData({ abi: batchGatewayAbi, data });
  const failures = [];
  const responses = [];
  await Promise.all(queries.map(async (query, i) => {
    try {
      responses[i] = query.urls.includes(localBatchGatewayUrl) ? await localBatchGatewayRequest({ data: query.data, ccipRequest: ccipRequest2 }) : await ccipRequest2(query);
      failures[i] = false;
    } catch (err) {
      failures[i] = true;
      responses[i] = encodeError(err);
    }
  }));
  return encodeFunctionResult({
    abi: batchGatewayAbi,
    functionName: "query",
    result: [failures, responses]
  });
}
function encodeError(error) {
  if (error.name === "HttpRequestError" && error.status)
    return encodeErrorResult({
      abi: batchGatewayAbi,
      errorName: "HttpError",
      args: [error.status, error.shortMessage]
    });
  return encodeErrorResult({
    abi: [solidityError],
    errorName: "Error",
    args: ["shortMessage" in error ? error.shortMessage : error.message]
  });
}
var localBatchGatewayUrl;
var init_localBatchGatewayRequest = __esm({
  "node_modules/viem/_esm/utils/ens/localBatchGatewayRequest.js"() {
    "use strict";
    init_abis();
    init_solidity();
    init_decodeFunctionData();
    init_encodeErrorResult();
    init_encodeFunctionResult();
    localBatchGatewayUrl = "x-batch-gateway:true";
  }
});

// node_modules/viem/_esm/utils/ccip.js
var ccip_exports = {};
__export(ccip_exports, {
  ccipRequest: () => ccipRequest,
  offchainLookup: () => offchainLookup,
  offchainLookupAbiItem: () => offchainLookupAbiItem,
  offchainLookupSignature: () => offchainLookupSignature
});
async function offchainLookup(client, { blockNumber, blockTag, data, to }) {
  const { args } = decodeErrorResult({
    data,
    abi: [offchainLookupAbiItem]
  });
  const [sender, urls, callData, callbackSelector, extraData] = args;
  const { ccipRead } = client;
  const ccipRequest_ = ccipRead && typeof ccipRead?.request === "function" ? ccipRead.request : ccipRequest;
  try {
    if (!isAddressEqual(to, sender))
      throw new OffchainLookupSenderMismatchError({ sender, to });
    const result = urls.includes(localBatchGatewayUrl) ? await localBatchGatewayRequest({
      data: callData,
      ccipRequest: ccipRequest_
    }) : await ccipRequest_({ data: callData, sender, urls });
    const { data: data_ } = await call(client, {
      blockNumber,
      blockTag,
      data: concat([
        callbackSelector,
        encodeAbiParameters([{ type: "bytes" }, { type: "bytes" }], [result, extraData])
      ]),
      to
    });
    return data_;
  } catch (err) {
    throw new OffchainLookupError({
      callbackSelector,
      cause: err,
      data,
      extraData,
      sender,
      urls
    });
  }
}
async function ccipRequest({ data, sender, urls }) {
  let error = new Error("An unknown error occurred.");
  for (let i = 0; i < urls.length; i++) {
    const url = urls[i];
    const method = url.includes("{data}") ? "GET" : "POST";
    const body = method === "POST" ? { data, sender } : void 0;
    const headers = method === "POST" ? { "Content-Type": "application/json" } : {};
    try {
      const response = await fetch(url.replace("{sender}", sender.toLowerCase()).replace("{data}", data), {
        body: JSON.stringify(body),
        headers,
        method
      });
      let result;
      if (response.headers.get("Content-Type")?.startsWith("application/json")) {
        result = (await response.json()).data;
      } else {
        result = await response.text();
      }
      if (!response.ok) {
        error = new HttpRequestError({
          body,
          details: result?.error ? stringify(result.error) : response.statusText,
          headers: response.headers,
          status: response.status,
          url
        });
        continue;
      }
      if (!isHex(result)) {
        error = new OffchainLookupResponseMalformedError({
          result,
          url
        });
        continue;
      }
      return result;
    } catch (err) {
      error = new HttpRequestError({
        body,
        details: err.message,
        url
      });
    }
  }
  throw error;
}
var offchainLookupSignature, offchainLookupAbiItem;
var init_ccip2 = __esm({
  "node_modules/viem/_esm/utils/ccip.js"() {
    "use strict";
    init_call();
    init_ccip();
    init_request();
    init_decodeErrorResult();
    init_encodeAbiParameters();
    init_isAddressEqual();
    init_concat();
    init_isHex();
    init_localBatchGatewayRequest();
    init_stringify();
    offchainLookupSignature = "0x556f1830";
    offchainLookupAbiItem = {
      name: "OffchainLookup",
      type: "error",
      inputs: [
        {
          name: "sender",
          type: "address"
        },
        {
          name: "urls",
          type: "string[]"
        },
        {
          name: "callData",
          type: "bytes"
        },
        {
          name: "callbackFunction",
          type: "bytes4"
        },
        {
          name: "extraData",
          type: "bytes"
        }
      ]
    };
  }
});

// node_modules/viem/_esm/actions/public/call.js
async function call(client, args) {
  const { account: account_ = client.account, authorizationList, batch = Boolean(client.batch?.multicall), blockNumber, blockTag = client.experimental_blockTag ?? "latest", accessList, blobs, blockOverrides, code, data: data_, factory, factoryData, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value, stateOverride, ...rest } = args;
  const account = account_ ? parseAccount(account_) : void 0;
  if (code && (factory || factoryData))
    throw new BaseError2("Cannot provide both `code` & `factory`/`factoryData` as parameters.");
  if (code && to)
    throw new BaseError2("Cannot provide both `code` & `to` as parameters.");
  const deploylessCallViaBytecode = code && data_;
  const deploylessCallViaFactory = factory && factoryData && to && data_;
  const deploylessCall = deploylessCallViaBytecode || deploylessCallViaFactory;
  const data = (() => {
    if (deploylessCallViaBytecode)
      return toDeploylessCallViaBytecodeData({
        code,
        data: data_
      });
    if (deploylessCallViaFactory)
      return toDeploylessCallViaFactoryData({
        data: data_,
        factory,
        factoryData,
        to
      });
    return data_;
  })();
  try {
    assertRequest(args);
    const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : void 0;
    const block = blockNumberHex || blockTag;
    const rpcBlockOverrides = blockOverrides ? toRpc2(blockOverrides) : void 0;
    const rpcStateOverride = serializeStateOverride(stateOverride);
    const chainFormat = client.chain?.formatters?.transactionRequest?.format;
    const format = chainFormat || formatTransactionRequest;
    const request = format({
      // Pick out extra data that might exist on the chain's transaction request type.
      ...extract(rest, { format: chainFormat }),
      accessList,
      account,
      authorizationList,
      blobs,
      data,
      gas,
      gasPrice,
      maxFeePerBlobGas,
      maxFeePerGas,
      maxPriorityFeePerGas,
      nonce,
      to: deploylessCall ? void 0 : to,
      value
    }, "call");
    if (batch && shouldPerformMulticall({ request }) && !rpcStateOverride && !rpcBlockOverrides) {
      try {
        return await scheduleMulticall(client, {
          ...request,
          blockNumber,
          blockTag
        });
      } catch (err) {
        if (!(err instanceof ClientChainNotConfiguredError) && !(err instanceof ChainDoesNotSupportContract))
          throw err;
      }
    }
    const params = (() => {
      const base2 = [
        request,
        block
      ];
      if (rpcStateOverride && rpcBlockOverrides)
        return [...base2, rpcStateOverride, rpcBlockOverrides];
      if (rpcStateOverride)
        return [...base2, rpcStateOverride];
      if (rpcBlockOverrides)
        return [...base2, {}, rpcBlockOverrides];
      return base2;
    })();
    const response = await client.request({
      method: "eth_call",
      params
    });
    if (response === "0x")
      return { data: void 0 };
    return { data: response };
  } catch (err) {
    const data2 = getRevertErrorData(err);
    const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await Promise.resolve().then(() => (init_ccip2(), ccip_exports));
    if (client.ccipRead !== false && data2?.slice(0, 10) === offchainLookupSignature2 && to)
      return { data: await offchainLookup2(client, { data: data2, to }) };
    if (deploylessCall && data2?.slice(0, 10) === "0x101bb98d")
      throw new CounterfactualDeploymentFailedError({ factory });
    throw getCallError(err, {
      ...args,
      account,
      chain: client.chain
    });
  }
}
function shouldPerformMulticall({ request }) {
  const { data, to, ...request_ } = request;
  if (!data)
    return false;
  if (data.startsWith(aggregate3Signature))
    return false;
  if (!to)
    return false;
  if (Object.values(request_).filter((x) => typeof x !== "undefined").length > 0)
    return false;
  return true;
}
async function scheduleMulticall(client, args) {
  const { batchSize = 1024, deployless = false, wait: wait2 = 0 } = typeof client.batch?.multicall === "object" ? client.batch.multicall : {};
  const { blockNumber, blockTag = client.experimental_blockTag ?? "latest", data, to } = args;
  const multicallAddress = (() => {
    if (deployless)
      return null;
    if (args.multicallAddress)
      return args.multicallAddress;
    if (client.chain) {
      return getChainContractAddress({
        blockNumber,
        chain: client.chain,
        contract: "multicall3"
      });
    }
    throw new ClientChainNotConfiguredError();
  })();
  const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : void 0;
  const block = blockNumberHex || blockTag;
  const { schedule } = createBatchScheduler({
    id: `${client.uid}.${block}`,
    wait: wait2,
    shouldSplitBatch(args2) {
      const size5 = args2.reduce((size6, { data: data2 }) => size6 + (data2.length - 2), 0);
      return size5 > batchSize * 2;
    },
    fn: async (requests) => {
      const calls = requests.map((request) => ({
        allowFailure: true,
        callData: request.data,
        target: request.to
      }));
      const calldata = encodeFunctionData({
        abi: multicall3Abi,
        args: [calls],
        functionName: "aggregate3"
      });
      const data2 = await client.request({
        method: "eth_call",
        params: [
          {
            ...multicallAddress === null ? {
              data: toDeploylessCallViaBytecodeData({
                code: multicall3Bytecode,
                data: calldata
              })
            } : { to: multicallAddress, data: calldata }
          },
          block
        ]
      });
      return decodeFunctionResult({
        abi: multicall3Abi,
        args: [calls],
        functionName: "aggregate3",
        data: data2 || "0x"
      });
    }
  });
  const [{ returnData, success }] = await schedule({ data, to });
  if (!success)
    throw new RawContractError({ data: returnData });
  if (returnData === "0x")
    return { data: void 0 };
  return { data: returnData };
}
function toDeploylessCallViaBytecodeData(parameters) {
  const { code, data } = parameters;
  return encodeDeployData({
    abi: parseAbi(["constructor(bytes, bytes)"]),
    bytecode: deploylessCallViaBytecodeBytecode,
    args: [code, data]
  });
}
function toDeploylessCallViaFactoryData(parameters) {
  const { data, factory, factoryData, to } = parameters;
  return encodeDeployData({
    abi: parseAbi(["constructor(address, bytes, address, bytes)"]),
    bytecode: deploylessCallViaFactoryBytecode,
    args: [to, data, factory, factoryData]
  });
}
function getRevertErrorData(err) {
  if (!(err instanceof BaseError2))
    return void 0;
  const error = err.walk();
  return typeof error?.data === "object" ? error.data?.data : error.data;
}
var init_call = __esm({
  "node_modules/viem/_esm/actions/public/call.js"() {
    "use strict";
    init_exports();
    init_BlockOverrides();
    init_parseAccount();
    init_abis();
    init_contract2();
    init_contracts();
    init_base();
    init_chain();
    init_contract();
    init_decodeFunctionResult();
    init_encodeDeployData();
    init_encodeFunctionData();
    init_getChainContractAddress();
    init_toHex();
    init_getCallError();
    init_extract();
    init_transactionRequest();
    init_createBatchScheduler();
    init_stateOverride2();
    init_assertRequest();
  }
});

// node_modules/viem/_esm/actions/public/readContract.js
async function readContract(client, parameters) {
  const { abi: abi2, address: address2, args, functionName, ...rest } = parameters;
  const calldata = encodeFunctionData({
    abi: abi2,
    args,
    functionName
  });
  try {
    const { data } = await getAction(client, call, "call")({
      ...rest,
      data: calldata,
      to: address2
    });
    return decodeFunctionResult({
      abi: abi2,
      args,
      functionName,
      data: data || "0x"
    });
  } catch (error) {
    throw getContractError(error, {
      abi: abi2,
      address: address2,
      args,
      docsPath: "/docs/contract/readContract",
      functionName
    });
  }
}
var init_readContract = __esm({
  "node_modules/viem/_esm/actions/public/readContract.js"() {
    "use strict";
    init_decodeFunctionResult();
    init_encodeFunctionData();
    init_getContractError();
    init_getAction();
    init_call();
  }
});

// node_modules/viem/_esm/actions/public/simulateContract.js
async function simulateContract(client, parameters) {
  const { abi: abi2, address: address2, args, functionName, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, ...callRequest } = parameters;
  const account = callRequest.account ? parseAccount(callRequest.account) : client.account;
  const calldata = encodeFunctionData({ abi: abi2, args, functionName });
  try {
    const { data } = await getAction(client, call, "call")({
      batch: false,
      data: `${calldata}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`,
      to: address2,
      ...callRequest,
      account
    });
    const result = decodeFunctionResult({
      abi: abi2,
      args,
      functionName,
      data: data || "0x"
    });
    const minimizedAbi = abi2.filter((abiItem) => "name" in abiItem && abiItem.name === parameters.functionName);
    return {
      result,
      request: {
        abi: minimizedAbi,
        address: address2,
        args,
        dataSuffix,
        functionName,
        ...callRequest,
        account
      }
    };
  } catch (error) {
    throw getContractError(error, {
      abi: abi2,
      address: address2,
      args,
      docsPath: "/docs/contract/simulateContract",
      functionName,
      sender: account?.address
    });
  }
}
var init_simulateContract = __esm({
  "node_modules/viem/_esm/actions/public/simulateContract.js"() {
    "use strict";
    init_parseAccount();
    init_decodeFunctionResult();
    init_encodeFunctionData();
    init_getContractError();
    init_getAction();
    init_call();
  }
});

// node_modules/viem/_esm/utils/observe.js
function observe(observerId, callbacks, fn) {
  const callbackId = ++callbackCount;
  const getListeners = () => listenersCache.get(observerId) || [];
  const unsubscribe = () => {
    const listeners2 = getListeners();
    listenersCache.set(observerId, listeners2.filter((cb) => cb.id !== callbackId));
  };
  const unwatch = () => {
    const listeners2 = getListeners();
    if (!listeners2.some((cb) => cb.id === callbackId))
      return;
    const cleanup2 = cleanupCache.get(observerId);
    if (listeners2.length === 1 && cleanup2) {
      const p = cleanup2();
      if (p instanceof Promise)
        p.catch(() => {
        });
    }
    unsubscribe();
  };
  const listeners = getListeners();
  listenersCache.set(observerId, [
    ...listeners,
    { id: callbackId, fns: callbacks }
  ]);
  if (listeners && listeners.length > 0)
    return unwatch;
  const emit = {};
  for (const key in callbacks) {
    emit[key] = ((...args) => {
      const listeners2 = getListeners();
      if (listeners2.length === 0)
        return;
      for (const listener of listeners2)
        listener.fns[key]?.(...args);
    });
  }
  const cleanup = fn(emit);
  if (typeof cleanup === "function")
    cleanupCache.set(observerId, cleanup);
  return unwatch;
}
var listenersCache, cleanupCache, callbackCount;
var init_observe = __esm({
  "node_modules/viem/_esm/utils/observe.js"() {
    "use strict";
    listenersCache = /* @__PURE__ */ new Map();
    cleanupCache = /* @__PURE__ */ new Map();
    callbackCount = 0;
  }
});

// node_modules/viem/_esm/utils/wait.js
async function wait(time) {
  return new Promise((res) => setTimeout(res, time));
}
var init_wait = __esm({
  "node_modules/viem/_esm/utils/wait.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/utils/poll.js
function poll(fn, { emitOnBegin, initialWaitTime, interval }) {
  let active = true;
  const unwatch = () => active = false;
  const watch = async () => {
    let data;
    if (emitOnBegin)
      data = await fn({ unpoll: unwatch });
    const initialWait = await initialWaitTime?.(data) ?? interval;
    await wait(initialWait);
    const poll2 = async () => {
      if (!active)
        return;
      await fn({ unpoll: unwatch });
      await wait(interval);
      poll2();
    };
    poll2();
  };
  watch();
  return unwatch;
}
var init_poll = __esm({
  "node_modules/viem/_esm/utils/poll.js"() {
    "use strict";
    init_wait();
  }
});

// node_modules/viem/_esm/utils/promise/withCache.js
function getCache(cacheKey2) {
  const buildCache = (cacheKey3, cache2) => ({
    clear: () => cache2.delete(cacheKey3),
    get: () => cache2.get(cacheKey3),
    set: (data) => cache2.set(cacheKey3, data)
  });
  const promise = buildCache(cacheKey2, promiseCache);
  const response = buildCache(cacheKey2, responseCache);
  return {
    clear: () => {
      promise.clear();
      response.clear();
    },
    promise,
    response
  };
}
async function withCache(fn, { cacheKey: cacheKey2, cacheTime = Number.POSITIVE_INFINITY }) {
  const cache2 = getCache(cacheKey2);
  const response = cache2.response.get();
  if (response && cacheTime > 0) {
    const age = Date.now() - response.created.getTime();
    if (age < cacheTime)
      return response.data;
  }
  let promise = cache2.promise.get();
  if (!promise) {
    promise = fn();
    cache2.promise.set(promise);
  }
  try {
    const data = await promise;
    cache2.response.set({ created: /* @__PURE__ */ new Date(), data });
    return data;
  } finally {
    cache2.promise.clear();
  }
}
var promiseCache, responseCache;
var init_withCache = __esm({
  "node_modules/viem/_esm/utils/promise/withCache.js"() {
    "use strict";
    promiseCache = /* @__PURE__ */ new Map();
    responseCache = /* @__PURE__ */ new Map();
  }
});

// node_modules/viem/_esm/actions/public/getBlockNumber.js
async function getBlockNumber(client, { cacheTime = client.cacheTime } = {}) {
  const blockNumberHex = await withCache(() => client.request({
    method: "eth_blockNumber"
  }), { cacheKey: cacheKey(client.uid), cacheTime });
  return BigInt(blockNumberHex);
}
var cacheKey;
var init_getBlockNumber = __esm({
  "node_modules/viem/_esm/actions/public/getBlockNumber.js"() {
    "use strict";
    init_withCache();
    cacheKey = (id) => `blockNumber.${id}`;
  }
});

// node_modules/viem/_esm/actions/public/getFilterChanges.js
async function getFilterChanges(_client, { filter }) {
  const strict = "strict" in filter && filter.strict;
  const logs = await filter.request({
    method: "eth_getFilterChanges",
    params: [filter.id]
  });
  if (typeof logs[0] === "string")
    return logs;
  const formattedLogs = logs.map((log) => formatLog(log));
  if (!("abi" in filter) || !filter.abi)
    return formattedLogs;
  return parseEventLogs({
    abi: filter.abi,
    logs: formattedLogs,
    strict
  });
}
var init_getFilterChanges = __esm({
  "node_modules/viem/_esm/actions/public/getFilterChanges.js"() {
    "use strict";
    init_parseEventLogs();
    init_log2();
  }
});

// node_modules/viem/_esm/actions/public/uninstallFilter.js
async function uninstallFilter(_client, { filter }) {
  return filter.request({
    method: "eth_uninstallFilter",
    params: [filter.id]
  });
}
var init_uninstallFilter = __esm({
  "node_modules/viem/_esm/actions/public/uninstallFilter.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/actions/public/watchContractEvent.js
function watchContractEvent(client, parameters) {
  const { abi: abi2, address: address2, args, batch = true, eventName, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client.pollingInterval, strict: strict_ } = parameters;
  const enablePolling = (() => {
    if (typeof poll_ !== "undefined")
      return poll_;
    if (typeof fromBlock === "bigint")
      return true;
    if (client.transport.type === "webSocket" || client.transport.type === "ipc")
      return false;
    if (client.transport.type === "fallback" && (client.transport.transports[0].config.type === "webSocket" || client.transport.transports[0].config.type === "ipc"))
      return false;
    return true;
  })();
  const pollContractEvent = () => {
    const strict = strict_ ?? false;
    const observerId = stringify([
      "watchContractEvent",
      address2,
      args,
      batch,
      client.uid,
      eventName,
      pollingInterval,
      strict,
      fromBlock
    ]);
    return observe(observerId, { onLogs, onError }, (emit) => {
      let previousBlockNumber;
      if (fromBlock !== void 0)
        previousBlockNumber = fromBlock - 1n;
      let filter;
      let initialized = false;
      const unwatch = poll(async () => {
        if (!initialized) {
          try {
            filter = await getAction(client, createContractEventFilter, "createContractEventFilter")({
              abi: abi2,
              address: address2,
              args,
              eventName,
              strict,
              fromBlock
            });
          } catch {
          }
          initialized = true;
          return;
        }
        try {
          let logs;
          if (filter) {
            logs = await getAction(client, getFilterChanges, "getFilterChanges")({ filter });
          } else {
            const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({});
            if (previousBlockNumber && previousBlockNumber < blockNumber) {
              logs = await getAction(client, getContractEvents, "getContractEvents")({
                abi: abi2,
                address: address2,
                args,
                eventName,
                fromBlock: previousBlockNumber + 1n,
                toBlock: blockNumber,
                strict
              });
            } else {
              logs = [];
            }
            previousBlockNumber = blockNumber;
          }
          if (logs.length === 0)
            return;
          if (batch)
            emit.onLogs(logs);
          else
            for (const log of logs)
              emit.onLogs([log]);
        } catch (err) {
          if (filter && err instanceof InvalidInputRpcError)
            initialized = false;
          emit.onError?.(err);
        }
      }, {
        emitOnBegin: true,
        interval: pollingInterval
      });
      return async () => {
        if (filter)
          await getAction(client, uninstallFilter, "uninstallFilter")({ filter });
        unwatch();
      };
    });
  };
  const subscribeContractEvent = () => {
    const strict = strict_ ?? false;
    const observerId = stringify([
      "watchContractEvent",
      address2,
      args,
      batch,
      client.uid,
      eventName,
      pollingInterval,
      strict
    ]);
    let active = true;
    let unsubscribe = () => active = false;
    return observe(observerId, { onLogs, onError }, (emit) => {
      ;
      (async () => {
        try {
          const transport = (() => {
            if (client.transport.type === "fallback") {
              const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc");
              if (!transport2)
                return client.transport;
              return transport2.value;
            }
            return client.transport;
          })();
          const topics = eventName ? encodeEventTopics({
            abi: abi2,
            eventName,
            args
          }) : [];
          const { unsubscribe: unsubscribe_ } = await transport.subscribe({
            params: ["logs", { address: address2, topics }],
            onData(data) {
              if (!active)
                return;
              const log = data.result;
              try {
                const { eventName: eventName2, args: args2 } = decodeEventLog({
                  abi: abi2,
                  data: log.data,
                  topics: log.topics,
                  strict: strict_
                });
                const formatted = formatLog(log, {
                  args: args2,
                  eventName: eventName2
                });
                emit.onLogs([formatted]);
              } catch (err) {
                let eventName2;
                let isUnnamed;
                if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) {
                  if (strict_)
                    return;
                  eventName2 = err.abiItem.name;
                  isUnnamed = err.abiItem.inputs?.some((x) => !("name" in x && x.name));
                }
                const formatted = formatLog(log, {
                  args: isUnnamed ? [] : {},
                  eventName: eventName2
                });
                emit.onLogs([formatted]);
              }
            },
            onError(error) {
              emit.onError?.(error);
            }
          });
          unsubscribe = unsubscribe_;
          if (!active)
            unsubscribe();
        } catch (err) {
          onError?.(err);
        }
      })();
      return () => unsubscribe();
    });
  };
  return enablePolling ? pollContractEvent() : subscribeContractEvent();
}
var init_watchContractEvent = __esm({
  "node_modules/viem/_esm/actions/public/watchContractEvent.js"() {
    "use strict";
    init_abi();
    init_rpc();
    init_decodeEventLog();
    init_encodeEventTopics();
    init_log2();
    init_getAction();
    init_observe();
    init_poll();
    init_stringify();
    init_createContractEventFilter();
    init_getBlockNumber();
    init_getContractEvents();
    init_getFilterChanges();
    init_uninstallFilter();
  }
});

// node_modules/viem/_esm/actions/wallet/sendRawTransaction.js
async function sendRawTransaction(client, { serializedTransaction }) {
  return client.request({
    method: "eth_sendRawTransaction",
    params: [serializedTransaction]
  }, { retryCount: 0 });
}
var init_sendRawTransaction = __esm({
  "node_modules/viem/_esm/actions/wallet/sendRawTransaction.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/utils/promise/withRetry.js
function withRetry(fn, { delay: delay_ = 100, retryCount = 2, shouldRetry: shouldRetry2 = () => true } = {}) {
  return new Promise((resolve, reject) => {
    const attemptRetry = async ({ count = 0 } = {}) => {
      const retry = async ({ error }) => {
        const delay = typeof delay_ === "function" ? delay_({ count, error }) : delay_;
        if (delay)
          await wait(delay);
        attemptRetry({ count: count + 1 });
      };
      try {
        const data = await fn();
        resolve(data);
      } catch (err) {
        if (count < retryCount && await shouldRetry2({ count, error: err }))
          return retry({ error: err });
        reject(err);
      }
    };
    attemptRetry();
  });
}
var init_withRetry = __esm({
  "node_modules/viem/_esm/utils/promise/withRetry.js"() {
    "use strict";
    init_wait();
  }
});

// node_modules/viem/_esm/utils/formatters/transactionReceipt.js
function formatTransactionReceipt(transactionReceipt, _) {
  const receipt = {
    ...transactionReceipt,
    blockNumber: transactionReceipt.blockNumber ? BigInt(transactionReceipt.blockNumber) : null,
    contractAddress: transactionReceipt.contractAddress ? transactionReceipt.contractAddress : null,
    cumulativeGasUsed: transactionReceipt.cumulativeGasUsed ? BigInt(transactionReceipt.cumulativeGasUsed) : null,
    effectiveGasPrice: transactionReceipt.effectiveGasPrice ? BigInt(transactionReceipt.effectiveGasPrice) : null,
    gasUsed: transactionReceipt.gasUsed ? BigInt(transactionReceipt.gasUsed) : null,
    logs: transactionReceipt.logs ? transactionReceipt.logs.map((log) => formatLog(log)) : null,
    to: transactionReceipt.to ? transactionReceipt.to : null,
    transactionIndex: transactionReceipt.transactionIndex ? hexToNumber(transactionReceipt.transactionIndex) : null,
    status: transactionReceipt.status ? receiptStatuses[transactionReceipt.status] : null,
    type: transactionReceipt.type ? transactionType[transactionReceipt.type] || transactionReceipt.type : null
  };
  if (transactionReceipt.blobGasPrice)
    receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice);
  if (transactionReceipt.blobGasUsed)
    receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed);
  return receipt;
}
var receiptStatuses, defineTransactionReceipt;
var init_transactionReceipt = __esm({
  "node_modules/viem/_esm/utils/formatters/transactionReceipt.js"() {
    "use strict";
    init_fromHex();
    init_formatter();
    init_log2();
    init_transaction2();
    receiptStatuses = {
      "0x0": "reverted",
      "0x1": "success"
    };
    defineTransactionReceipt = /* @__PURE__ */ defineFormatter("transactionReceipt", formatTransactionReceipt);
  }
});

// node_modules/viem/_esm/utils/uid.js
function uid(length = 11) {
  if (!buffer || index + length > size4 * 2) {
    buffer = "";
    index = 0;
    for (let i = 0; i < size4; i++) {
      buffer += (256 + Math.random() * 256 | 0).toString(16).substring(1);
    }
  }
  return buffer.substring(index, index++ + length);
}
var size4, index, buffer;
var init_uid = __esm({
  "node_modules/viem/_esm/utils/uid.js"() {
    "use strict";
    size4 = 256;
    index = size4;
  }
});

// node_modules/viem/_esm/clients/createClient.js
function createClient(parameters) {
  const { batch, chain: chain3, ccipRead, dataSuffix, key = "base", name = "Base Client", type = "base" } = parameters;
  const experimental_blockTag = parameters.experimental_blockTag ?? (typeof chain3?.experimental_preconfirmationTime === "number" ? "pending" : void 0);
  const blockTime = chain3?.blockTime ?? 12e3;
  const defaultPollingInterval = Math.min(Math.max(Math.floor(blockTime / 2), 500), 4e3);
  const pollingInterval = parameters.pollingInterval ?? defaultPollingInterval;
  const cacheTime = parameters.cacheTime ?? pollingInterval;
  const account = parameters.account ? parseAccount(parameters.account) : void 0;
  const { config, request, value } = parameters.transport({
    account,
    chain: chain3,
    pollingInterval
  });
  const transport = { ...config, ...value };
  const client = {
    account,
    batch,
    cacheTime,
    ccipRead,
    chain: chain3,
    dataSuffix,
    key,
    name,
    pollingInterval,
    request,
    transport,
    type,
    uid: uid(),
    ...experimental_blockTag ? { experimental_blockTag } : {}
  };
  function extend(base2) {
    return (extendFn) => {
      const extended = extendFn(base2);
      for (const key2 in client)
        delete extended[key2];
      const combined = { ...base2, ...extended };
      return Object.assign(combined, { extend: extend(combined) });
    };
  }
  return Object.assign(client, { extend: extend(client) });
}
var init_createClient = __esm({
  "node_modules/viem/_esm/clients/createClient.js"() {
    "use strict";
    init_parseAccount();
    init_uid();
  }
});

// node_modules/viem/_esm/utils/ens/errors.js
function isNullUniversalResolverError(err) {
  if (!(err instanceof BaseError2))
    return false;
  const cause = err.walk((e7) => e7 instanceof ContractFunctionRevertedError);
  if (!(cause instanceof ContractFunctionRevertedError))
    return false;
  if (cause.data?.errorName === "HttpError")
    return true;
  if (cause.data?.errorName === "ResolverError")
    return true;
  if (cause.data?.errorName === "ResolverNotContract")
    return true;
  if (cause.data?.errorName === "ResolverNotFound")
    return true;
  if (cause.data?.errorName === "ReverseAddressMismatch")
    return true;
  if (cause.data?.errorName === "UnsupportedResolverProfile")
    return true;
  return false;
}
var init_errors3 = __esm({
  "node_modules/viem/_esm/utils/ens/errors.js"() {
    "use strict";
    init_base();
    init_contract();
  }
});

// node_modules/viem/_esm/utils/ens/encodedLabelToLabelhash.js
function encodedLabelToLabelhash(label) {
  if (label.length !== 66)
    return null;
  if (label.indexOf("[") !== 0)
    return null;
  if (label.indexOf("]") !== 65)
    return null;
  const hash3 = `0x${label.slice(1, 65)}`;
  if (!isHex(hash3))
    return null;
  return hash3;
}
var init_encodedLabelToLabelhash = __esm({
  "node_modules/viem/_esm/utils/ens/encodedLabelToLabelhash.js"() {
    "use strict";
    init_isHex();
  }
});

// node_modules/viem/_esm/utils/ens/namehash.js
function namehash(name) {
  let result = new Uint8Array(32).fill(0);
  if (!name)
    return bytesToHex(result);
  const labels = name.split(".");
  for (let i = labels.length - 1; i >= 0; i -= 1) {
    const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i]);
    const hashed = hashFromEncodedLabel ? toBytes(hashFromEncodedLabel) : keccak256(stringToBytes(labels[i]), "bytes");
    result = keccak256(concat([result, hashed]), "bytes");
  }
  return bytesToHex(result);
}
var init_namehash = __esm({
  "node_modules/viem/_esm/utils/ens/namehash.js"() {
    "use strict";
    init_concat();
    init_toBytes();
    init_toHex();
    init_keccak256();
    init_encodedLabelToLabelhash();
  }
});

// node_modules/viem/_esm/utils/ens/encodeLabelhash.js
function encodeLabelhash(hash3) {
  return `[${hash3.slice(2)}]`;
}
var init_encodeLabelhash = __esm({
  "node_modules/viem/_esm/utils/ens/encodeLabelhash.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/utils/ens/labelhash.js
function labelhash(label) {
  const result = new Uint8Array(32).fill(0);
  if (!label)
    return bytesToHex(result);
  return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label));
}
var init_labelhash = __esm({
  "node_modules/viem/_esm/utils/ens/labelhash.js"() {
    "use strict";
    init_toBytes();
    init_toHex();
    init_keccak256();
    init_encodedLabelToLabelhash();
  }
});

// node_modules/viem/_esm/utils/ens/packetToBytes.js
function packetToBytes(packet) {
  const value = packet.replace(/^\.|\.$/gm, "");
  if (value.length === 0)
    return new Uint8Array(1);
  const bytes = new Uint8Array(stringToBytes(value).byteLength + 2);
  let offset = 0;
  const list = value.split(".");
  for (let i = 0; i < list.length; i++) {
    let encoded = stringToBytes(list[i]);
    if (encoded.byteLength > 255)
      encoded = stringToBytes(encodeLabelhash(labelhash(list[i])));
    bytes[offset] = encoded.length;
    bytes.set(encoded, offset + 1);
    offset += encoded.length + 1;
  }
  if (bytes.byteLength !== offset + 1)
    return bytes.slice(0, offset + 1);
  return bytes;
}
var init_packetToBytes = __esm({
  "node_modules/viem/_esm/utils/ens/packetToBytes.js"() {
    "use strict";
    init_toBytes();
    init_encodeLabelhash();
    init_labelhash();
  }
});

// node_modules/viem/_esm/actions/ens/getEnsAddress.js
async function getEnsAddress(client, parameters) {
  const { blockNumber, blockTag, coinType, name, gatewayUrls, strict } = parameters;
  const { chain: chain3 } = client;
  const universalResolverAddress = (() => {
    if (parameters.universalResolverAddress)
      return parameters.universalResolverAddress;
    if (!chain3)
      throw new Error("client chain not configured. universalResolverAddress is required.");
    return getChainContractAddress({
      blockNumber,
      chain: chain3,
      contract: "ensUniversalResolver"
    });
  })();
  const tlds = chain3?.ensTlds;
  if (tlds && !tlds.some((tld) => name.endsWith(tld)))
    return null;
  const args = (() => {
    if (coinType != null)
      return [namehash(name), BigInt(coinType)];
    return [namehash(name)];
  })();
  try {
    const functionData = encodeFunctionData({
      abi: addressResolverAbi,
      functionName: "addr",
      args
    });
    const readContractParameters = {
      address: universalResolverAddress,
      abi: universalResolverResolveAbi,
      functionName: "resolveWithGateways",
      args: [
        toHex(packetToBytes(name)),
        functionData,
        gatewayUrls ?? [localBatchGatewayUrl]
      ],
      blockNumber,
      blockTag
    };
    const readContractAction = getAction(client, readContract, "readContract");
    const res = await readContractAction(readContractParameters);
    if (res[0] === "0x")
      return null;
    const address2 = decodeFunctionResult({
      abi: addressResolverAbi,
      args,
      functionName: "addr",
      data: res[0]
    });
    if (address2 === "0x")
      return null;
    if (trim(address2) === "0x00")
      return null;
    return address2;
  } catch (err) {
    if (strict)
      throw err;
    if (isNullUniversalResolverError(err))
      return null;
    throw err;
  }
}
var init_getEnsAddress = __esm({
  "node_modules/viem/_esm/actions/ens/getEnsAddress.js"() {
    "use strict";
    init_abis();
    init_decodeFunctionResult();
    init_encodeFunctionData();
    init_getChainContractAddress();
    init_trim();
    init_toHex();
    init_errors3();
    init_localBatchGatewayRequest();
    init_namehash();
    init_packetToBytes();
    init_getAction();
    init_readContract();
  }
});

// node_modules/viem/_esm/errors/ens.js
var EnsAvatarInvalidMetadataError, EnsAvatarInvalidNftUriError, EnsAvatarUriResolutionError, EnsAvatarUnsupportedNamespaceError;
var init_ens = __esm({
  "node_modules/viem/_esm/errors/ens.js"() {
    "use strict";
    init_base();
    EnsAvatarInvalidMetadataError = class extends BaseError2 {
      constructor({ data }) {
        super("Unable to extract image from metadata. The metadata may be malformed or invalid.", {
          metaMessages: [
            "- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.",
            "",
            `Provided data: ${JSON.stringify(data)}`
          ],
          name: "EnsAvatarInvalidMetadataError"
        });
      }
    };
    EnsAvatarInvalidNftUriError = class extends BaseError2 {
      constructor({ reason }) {
        super(`ENS NFT avatar URI is invalid. ${reason}`, {
          name: "EnsAvatarInvalidNftUriError"
        });
      }
    };
    EnsAvatarUriResolutionError = class extends BaseError2 {
      constructor({ uri }) {
        super(`Unable to resolve ENS avatar URI "${uri}". The URI may be malformed, invalid, or does not respond with a valid image.`, { name: "EnsAvatarUriResolutionError" });
      }
    };
    EnsAvatarUnsupportedNamespaceError = class extends BaseError2 {
      constructor({ namespace }) {
        super(`ENS NFT avatar namespace "${namespace}" is not supported. Must be "erc721" or "erc1155".`, { name: "EnsAvatarUnsupportedNamespaceError" });
      }
    };
  }
});

// node_modules/viem/_esm/utils/ens/avatar/utils.js
async function isImageUri(uri) {
  try {
    const res = await fetch(uri, { method: "HEAD" });
    if (res.status === 200) {
      const contentType = res.headers.get("content-type");
      return contentType?.startsWith("image/");
    }
    return false;
  } catch (error) {
    if (typeof error === "object" && typeof error.response !== "undefined") {
      return false;
    }
    if (!Object.hasOwn(globalThis, "Image"))
      return false;
    return new Promise((resolve) => {
      const img = new Image();
      img.onload = () => {
        resolve(true);
      };
      img.onerror = () => {
        resolve(false);
      };
      img.src = uri;
    });
  }
}
function getGateway(custom2, defaultGateway) {
  if (!custom2)
    return defaultGateway;
  if (custom2.endsWith("/"))
    return custom2.slice(0, -1);
  return custom2;
}
function resolveAvatarUri({ uri, gatewayUrls }) {
  const isEncoded = base64Regex.test(uri);
  if (isEncoded)
    return { uri, isOnChain: true, isEncoded };
  const ipfsGateway = getGateway(gatewayUrls?.ipfs, "https://ipfs.io");
  const arweaveGateway = getGateway(gatewayUrls?.arweave, "https://arweave.net");
  const networkRegexMatch = uri.match(networkRegex);
  const { protocol, subpath, target, subtarget = "" } = networkRegexMatch?.groups || {};
  const isIPNS = protocol === "ipns:/" || subpath === "ipns/";
  const isIPFS = protocol === "ipfs:/" || subpath === "ipfs/" || ipfsHashRegex.test(uri);
  if (uri.startsWith("http") && !isIPNS && !isIPFS) {
    let replacedUri = uri;
    if (gatewayUrls?.arweave)
      replacedUri = uri.replace(/https:\/\/arweave.net/g, gatewayUrls?.arweave);
    return { uri: replacedUri, isOnChain: false, isEncoded: false };
  }
  if ((isIPNS || isIPFS) && target) {
    return {
      uri: `${ipfsGateway}/${isIPNS ? "ipns" : "ipfs"}/${target}${subtarget}`,
      isOnChain: false,
      isEncoded: false
    };
  }
  if (protocol === "ar:/" && target) {
    return {
      uri: `${arweaveGateway}/${target}${subtarget || ""}`,
      isOnChain: false,
      isEncoded: false
    };
  }
  let parsedUri = uri.replace(dataURIRegex, "");
  if (parsedUri.startsWith("<svg")) {
    parsedUri = `data:image/svg+xml;base64,${btoa(parsedUri)}`;
  }
  if (parsedUri.startsWith("data:") || parsedUri.startsWith("{")) {
    return {
      uri: parsedUri,
      isOnChain: true,
      isEncoded: false
    };
  }
  throw new EnsAvatarUriResolutionError({ uri });
}
function getJsonImage(data) {
  if (typeof data !== "object" || !("image" in data) && !("image_url" in data) && !("image_data" in data)) {
    throw new EnsAvatarInvalidMetadataError({ data });
  }
  return data.image || data.image_url || data.image_data;
}
async function getMetadataAvatarUri({ gatewayUrls, uri }) {
  try {
    const res = await fetch(uri).then((res2) => res2.json());
    const image = await parseAvatarUri({
      gatewayUrls,
      uri: getJsonImage(res)
    });
    return image;
  } catch {
    throw new EnsAvatarUriResolutionError({ uri });
  }
}
async function parseAvatarUri({ gatewayUrls, uri }) {
  const { uri: resolvedURI, isOnChain } = resolveAvatarUri({ uri, gatewayUrls });
  if (isOnChain)
    return resolvedURI;
  const isImage = await isImageUri(resolvedURI);
  if (isImage)
    return resolvedURI;
  throw new EnsAvatarUriResolutionError({ uri });
}
function parseNftUri(uri_) {
  let uri = uri_;
  if (uri.startsWith("did:nft:")) {
    uri = uri.replace("did:nft:", "").replace(/_/g, "/");
  }
  const [reference, asset_namespace, tokenID] = uri.split("/");
  const [eip_namespace, chainID] = reference.split(":");
  const [erc_namespace, contractAddress] = asset_namespace.split(":");
  if (!eip_namespace || eip_namespace.toLowerCase() !== "eip155")
    throw new EnsAvatarInvalidNftUriError({ reason: "Only EIP-155 supported" });
  if (!chainID)
    throw new EnsAvatarInvalidNftUriError({ reason: "Chain ID not found" });
  if (!contractAddress)
    throw new EnsAvatarInvalidNftUriError({
      reason: "Contract address not found"
    });
  if (!tokenID)
    throw new EnsAvatarInvalidNftUriError({ reason: "Token ID not found" });
  if (!erc_namespace)
    throw new EnsAvatarInvalidNftUriError({ reason: "ERC namespace not found" });
  return {
    chainID: Number.parseInt(chainID, 10),
    namespace: erc_namespace.toLowerCase(),
    contractAddress,
    tokenID
  };
}
async function getNftTokenUri(client, { nft }) {
  if (nft.namespace === "erc721") {
    return readContract(client, {
      address: nft.contractAddress,
      abi: [
        {
          name: "tokenURI",
          type: "function",
          stateMutability: "view",
          inputs: [{ name: "tokenId", type: "uint256" }],
          outputs: [{ name: "", type: "string" }]
        }
      ],
      functionName: "tokenURI",
      args: [BigInt(nft.tokenID)]
    });
  }
  if (nft.namespace === "erc1155") {
    return readContract(client, {
      address: nft.contractAddress,
      abi: [
        {
          name: "uri",
          type: "function",
          stateMutability: "view",
          inputs: [{ name: "_id", type: "uint256" }],
          outputs: [{ name: "", type: "string" }]
        }
      ],
      functionName: "uri",
      args: [BigInt(nft.tokenID)]
    });
  }
  throw new EnsAvatarUnsupportedNamespaceError({ namespace: nft.namespace });
}
var networkRegex, ipfsHashRegex, base64Regex, dataURIRegex;
var init_utils6 = __esm({
  "node_modules/viem/_esm/utils/ens/avatar/utils.js"() {
    "use strict";
    init_readContract();
    init_ens();
    networkRegex = /(?<protocol>https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?<root>\/)?(?<subpath>ipfs\/|ipns\/)?(?<target>[\w\-.]+)(?<subtarget>\/.*)?/;
    ipfsHashRegex = /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?<target>[\w\-.]+))?(?<subtarget>\/.*)?$/;
    base64Regex = /^data:([a-zA-Z\-/+]*);base64,([^"].*)/;
    dataURIRegex = /^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/;
  }
});

// node_modules/viem/_esm/utils/ens/avatar/parseAvatarRecord.js
async function parseAvatarRecord(client, { gatewayUrls, record }) {
  if (/eip155:/i.test(record))
    return parseNftAvatarUri(client, { gatewayUrls, record });
  return parseAvatarUri({ uri: record, gatewayUrls });
}
async function parseNftAvatarUri(client, { gatewayUrls, record }) {
  const nft = parseNftUri(record);
  const nftUri = await getNftTokenUri(client, { nft });
  const { uri: resolvedNftUri, isOnChain, isEncoded } = resolveAvatarUri({ uri: nftUri, gatewayUrls });
  if (isOnChain && (resolvedNftUri.includes("data:application/json;base64,") || resolvedNftUri.startsWith("{"))) {
    const encodedJson = isEncoded ? (
      // if it is encoded, decode it
      atob(resolvedNftUri.replace("data:application/json;base64,", ""))
    ) : (
      // if it isn't encoded assume it is a JSON string, but it could be anything (it will error if it is)
      resolvedNftUri
    );
    const decoded = JSON.parse(encodedJson);
    return parseAvatarUri({ uri: getJsonImage(decoded), gatewayUrls });
  }
  let uriTokenId = nft.tokenID;
  if (nft.namespace === "erc1155")
    uriTokenId = uriTokenId.replace("0x", "").padStart(64, "0");
  return getMetadataAvatarUri({
    gatewayUrls,
    uri: resolvedNftUri.replace(/(?:0x)?{id}/, uriTokenId)
  });
}
var init_parseAvatarRecord = __esm({
  "node_modules/viem/_esm/utils/ens/avatar/parseAvatarRecord.js"() {
    "use strict";
    init_utils6();
  }
});

// node_modules/viem/_esm/actions/ens/getEnsText.js
async function getEnsText(client, parameters) {
  const { blockNumber, blockTag, key, name, gatewayUrls, strict } = parameters;
  const { chain: chain3 } = client;
  const universalResolverAddress = (() => {
    if (parameters.universalResolverAddress)
      return parameters.universalResolverAddress;
    if (!chain3)
      throw new Error("client chain not configured. universalResolverAddress is required.");
    return getChainContractAddress({
      blockNumber,
      chain: chain3,
      contract: "ensUniversalResolver"
    });
  })();
  const tlds = chain3?.ensTlds;
  if (tlds && !tlds.some((tld) => name.endsWith(tld)))
    return null;
  try {
    const readContractParameters = {
      address: universalResolverAddress,
      abi: universalResolverResolveAbi,
      args: [
        toHex(packetToBytes(name)),
        encodeFunctionData({
          abi: textResolverAbi,
          functionName: "text",
          args: [namehash(name), key]
        }),
        gatewayUrls ?? [localBatchGatewayUrl]
      ],
      functionName: "resolveWithGateways",
      blockNumber,
      blockTag
    };
    const readContractAction = getAction(client, readContract, "readContract");
    const res = await readContractAction(readContractParameters);
    if (res[0] === "0x")
      return null;
    const record = decodeFunctionResult({
      abi: textResolverAbi,
      functionName: "text",
      data: res[0]
    });
    return record === "" ? null : record;
  } catch (err) {
    if (strict)
      throw err;
    if (isNullUniversalResolverError(err))
      return null;
    throw err;
  }
}
var init_getEnsText = __esm({
  "node_modules/viem/_esm/actions/ens/getEnsText.js"() {
    "use strict";
    init_abis();
    init_decodeFunctionResult();
    init_encodeFunctionData();
    init_getChainContractAddress();
    init_toHex();
    init_errors3();
    init_localBatchGatewayRequest();
    init_namehash();
    init_packetToBytes();
    init_getAction();
    init_readContract();
  }
});

// node_modules/viem/_esm/actions/ens/getEnsAvatar.js
async function getEnsAvatar(client, { blockNumber, blockTag, assetGatewayUrls, name, gatewayUrls, strict, universalResolverAddress }) {
  const record = await getAction(client, getEnsText, "getEnsText")({
    blockNumber,
    blockTag,
    key: "avatar",
    name,
    universalResolverAddress,
    gatewayUrls,
    strict
  });
  if (!record)
    return null;
  try {
    return await parseAvatarRecord(client, {
      record,
      gatewayUrls: assetGatewayUrls
    });
  } catch {
    return null;
  }
}
var init_getEnsAvatar = __esm({
  "node_modules/viem/_esm/actions/ens/getEnsAvatar.js"() {
    "use strict";
    init_parseAvatarRecord();
    init_getAction();
    init_getEnsText();
  }
});

// node_modules/viem/_esm/actions/ens/getEnsName.js
async function getEnsName(client, parameters) {
  const { address: address2, blockNumber, blockTag, coinType = 60n, gatewayUrls, strict } = parameters;
  const { chain: chain3 } = client;
  const universalResolverAddress = (() => {
    if (parameters.universalResolverAddress)
      return parameters.universalResolverAddress;
    if (!chain3)
      throw new Error("client chain not configured. universalResolverAddress is required.");
    return getChainContractAddress({
      blockNumber,
      chain: chain3,
      contract: "ensUniversalResolver"
    });
  })();
  try {
    const readContractParameters = {
      address: universalResolverAddress,
      abi: universalResolverReverseAbi,
      args: [address2, coinType, gatewayUrls ?? [localBatchGatewayUrl]],
      functionName: "reverseWithGateways",
      blockNumber,
      blockTag
    };
    const readContractAction = getAction(client, readContract, "readContract");
    const [name] = await readContractAction(readContractParameters);
    return name || null;
  } catch (err) {
    if (strict)
      throw err;
    if (isNullUniversalResolverError(err))
      return null;
    throw err;
  }
}
var init_getEnsName = __esm({
  "node_modules/viem/_esm/actions/ens/getEnsName.js"() {
    "use strict";
    init_abis();
    init_getChainContractAddress();
    init_errors3();
    init_localBatchGatewayRequest();
    init_getAction();
    init_readContract();
  }
});

// node_modules/viem/_esm/actions/ens/getEnsResolver.js
async function getEnsResolver(client, parameters) {
  const { blockNumber, blockTag, name } = parameters;
  const { chain: chain3 } = client;
  const universalResolverAddress = (() => {
    if (parameters.universalResolverAddress)
      return parameters.universalResolverAddress;
    if (!chain3)
      throw new Error("client chain not configured. universalResolverAddress is required.");
    return getChainContractAddress({
      blockNumber,
      chain: chain3,
      contract: "ensUniversalResolver"
    });
  })();
  const tlds = chain3?.ensTlds;
  if (tlds && !tlds.some((tld) => name.endsWith(tld)))
    throw new Error(`${name} is not a valid ENS TLD (${tlds?.join(", ")}) for chain "${chain3.name}" (id: ${chain3.id}).`);
  const [resolverAddress] = await getAction(client, readContract, "readContract")({
    address: universalResolverAddress,
    abi: [
      {
        inputs: [{ type: "bytes" }],
        name: "findResolver",
        outputs: [
          { type: "address" },
          { type: "bytes32" },
          { type: "uint256" }
        ],
        stateMutability: "view",
        type: "function"
      }
    ],
    functionName: "findResolver",
    args: [toHex(packetToBytes(name))],
    blockNumber,
    blockTag
  });
  return resolverAddress;
}
var init_getEnsResolver = __esm({
  "node_modules/viem/_esm/actions/ens/getEnsResolver.js"() {
    "use strict";
    init_getChainContractAddress();
    init_toHex();
    init_packetToBytes();
    init_getAction();
    init_readContract();
  }
});

// node_modules/viem/_esm/actions/public/createAccessList.js
async function createAccessList(client, args) {
  const { account: account_ = client.account, blockNumber, blockTag = "latest", blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, to, value, ...rest } = args;
  const account = account_ ? parseAccount(account_) : void 0;
  try {
    assertRequest(args);
    const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : void 0;
    const block = blockNumberHex || blockTag;
    const chainFormat = client.chain?.formatters?.transactionRequest?.format;
    const format = chainFormat || formatTransactionRequest;
    const request = format({
      // Pick out extra data that might exist on the chain's transaction request type.
      ...extract(rest, { format: chainFormat }),
      account,
      blobs,
      data,
      gas,
      gasPrice,
      maxFeePerBlobGas,
      maxFeePerGas,
      maxPriorityFeePerGas,
      to,
      value
    }, "createAccessList");
    const response = await client.request({
      method: "eth_createAccessList",
      params: [request, block]
    });
    return {
      accessList: response.accessList,
      gasUsed: BigInt(response.gasUsed)
    };
  } catch (err) {
    throw getCallError(err, {
      ...args,
      account,
      chain: client.chain
    });
  }
}
var init_createAccessList = __esm({
  "node_modules/viem/_esm/actions/public/createAccessList.js"() {
    "use strict";
    init_parseAccount();
    init_toHex();
    init_getCallError();
    init_extract();
    init_transactionRequest();
    init_assertRequest();
  }
});

// node_modules/viem/_esm/actions/public/createBlockFilter.js
async function createBlockFilter(client) {
  const getRequest = createFilterRequestScope(client, {
    method: "eth_newBlockFilter"
  });
  const id = await client.request({
    method: "eth_newBlockFilter"
  });
  return { id, request: getRequest(id), type: "block" };
}
var init_createBlockFilter = __esm({
  "node_modules/viem/_esm/actions/public/createBlockFilter.js"() {
    "use strict";
    init_createFilterRequestScope();
  }
});

// node_modules/viem/_esm/actions/public/createEventFilter.js
async function createEventFilter(client, { address: address2, args, event, events: events_, fromBlock, strict, toBlock } = {}) {
  const events = events_ ?? (event ? [event] : void 0);
  const getRequest = createFilterRequestScope(client, {
    method: "eth_newFilter"
  });
  let topics = [];
  if (events) {
    const encoded = events.flatMap((event2) => encodeEventTopics({
      abi: [event2],
      eventName: event2.name,
      args
    }));
    topics = [encoded];
    if (event)
      topics = topics[0];
  }
  const id = await client.request({
    method: "eth_newFilter",
    params: [
      {
        address: address2,
        fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock,
        toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock,
        ...topics.length ? { topics } : {}
      }
    ]
  });
  return {
    abi: events,
    args,
    eventName: event ? event.name : void 0,
    fromBlock,
    id,
    request: getRequest(id),
    strict: Boolean(strict),
    toBlock,
    type: "event"
  };
}
var init_createEventFilter = __esm({
  "node_modules/viem/_esm/actions/public/createEventFilter.js"() {
    "use strict";
    init_encodeEventTopics();
    init_toHex();
    init_createFilterRequestScope();
  }
});

// node_modules/viem/_esm/actions/public/createPendingTransactionFilter.js
async function createPendingTransactionFilter(client) {
  const getRequest = createFilterRequestScope(client, {
    method: "eth_newPendingTransactionFilter"
  });
  const id = await client.request({
    method: "eth_newPendingTransactionFilter"
  });
  return { id, request: getRequest(id), type: "transaction" };
}
var init_createPendingTransactionFilter = __esm({
  "node_modules/viem/_esm/actions/public/createPendingTransactionFilter.js"() {
    "use strict";
    init_createFilterRequestScope();
  }
});

// node_modules/viem/_esm/actions/public/getBalance.js
async function getBalance(client, { address: address2, blockNumber, blockTag = client.experimental_blockTag ?? "latest" }) {
  if (client.batch?.multicall && client.chain?.contracts?.multicall3) {
    const multicall3Address = client.chain.contracts.multicall3.address;
    const calldata = encodeFunctionData({
      abi: multicall3Abi,
      functionName: "getEthBalance",
      args: [address2]
    });
    const { data } = await getAction(client, call, "call")({
      to: multicall3Address,
      data: calldata,
      blockNumber,
      blockTag
    });
    return decodeFunctionResult({
      abi: multicall3Abi,
      functionName: "getEthBalance",
      args: [address2],
      data: data || "0x"
    });
  }
  const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : void 0;
  const balance = await client.request({
    method: "eth_getBalance",
    params: [address2, blockNumberHex || blockTag]
  });
  return BigInt(balance);
}
var init_getBalance = __esm({
  "node_modules/viem/_esm/actions/public/getBalance.js"() {
    "use strict";
    init_abis();
    init_decodeFunctionResult();
    init_encodeFunctionData();
    init_toHex();
    init_getAction();
    init_call();
  }
});

// node_modules/viem/_esm/actions/public/getBlobBaseFee.js
async function getBlobBaseFee(client) {
  const baseFee = await client.request({
    method: "eth_blobBaseFee"
  });
  return BigInt(baseFee);
}
var init_getBlobBaseFee = __esm({
  "node_modules/viem/_esm/actions/public/getBlobBaseFee.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/actions/public/getBlockTransactionCount.js
async function getBlockTransactionCount(client, { blockHash, blockNumber, blockTag = "latest" } = {}) {
  const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
  let count;
  if (blockHash) {
    count = await client.request({
      method: "eth_getBlockTransactionCountByHash",
      params: [blockHash]
    }, { dedupe: true });
  } else {
    count = await client.request({
      method: "eth_getBlockTransactionCountByNumber",
      params: [blockNumberHex || blockTag]
    }, { dedupe: Boolean(blockNumberHex) });
  }
  return hexToNumber(count);
}
var init_getBlockTransactionCount = __esm({
  "node_modules/viem/_esm/actions/public/getBlockTransactionCount.js"() {
    "use strict";
    init_fromHex();
    init_toHex();
  }
});

// node_modules/viem/_esm/actions/public/getCode.js
async function getCode(client, { address: address2, blockNumber, blockTag = "latest" }) {
  const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
  const hex = await client.request({
    method: "eth_getCode",
    params: [address2, blockNumberHex || blockTag]
  }, { dedupe: Boolean(blockNumberHex) });
  if (hex === "0x")
    return void 0;
  return hex;
}
var init_getCode = __esm({
  "node_modules/viem/_esm/actions/public/getCode.js"() {
    "use strict";
    init_toHex();
  }
});

// node_modules/viem/_esm/actions/public/getDelegation.js
async function getDelegation(client, { address: address2, blockNumber, blockTag = "latest" }) {
  const code = await getCode(client, {
    address: address2,
    ...blockNumber !== void 0 ? { blockNumber } : { blockTag }
  });
  if (!code)
    return void 0;
  if (size(code) !== 23)
    return void 0;
  if (!code.startsWith("0xef0100"))
    return void 0;
  return getAddress(slice(code, 3, 23));
}
var init_getDelegation = __esm({
  "node_modules/viem/_esm/actions/public/getDelegation.js"() {
    "use strict";
    init_getAddress();
    init_size();
    init_slice();
    init_getCode();
  }
});

// node_modules/viem/_esm/errors/eip712.js
var Eip712DomainNotFoundError;
var init_eip712 = __esm({
  "node_modules/viem/_esm/errors/eip712.js"() {
    "use strict";
    init_base();
    Eip712DomainNotFoundError = class extends BaseError2 {
      constructor({ address: address2 }) {
        super(`No EIP-712 domain found on contract "${address2}".`, {
          metaMessages: [
            "Ensure that:",
            `- The contract is deployed at the address "${address2}".`,
            "- `eip712Domain()` function exists on the contract.",
            "- `eip712Domain()` function matches signature to ERC-5267 specification."
          ],
          name: "Eip712DomainNotFoundError"
        });
      }
    };
  }
});

// node_modules/viem/_esm/actions/public/getEip712Domain.js
async function getEip712Domain(client, parameters) {
  const { address: address2, factory, factoryData } = parameters;
  try {
    const [fields, name, version4, chainId, verifyingContract, salt, extensions] = await getAction(client, readContract, "readContract")({
      abi,
      address: address2,
      functionName: "eip712Domain",
      factory,
      factoryData
    });
    return {
      domain: {
        name,
        version: version4,
        chainId: Number(chainId),
        verifyingContract,
        salt
      },
      extensions,
      fields
    };
  } catch (e7) {
    const error = e7;
    if (error.name === "ContractFunctionExecutionError" && error.cause.name === "ContractFunctionZeroDataError") {
      throw new Eip712DomainNotFoundError({ address: address2 });
    }
    throw error;
  }
}
var abi;
var init_getEip712Domain = __esm({
  "node_modules/viem/_esm/actions/public/getEip712Domain.js"() {
    "use strict";
    init_eip712();
    init_getAction();
    init_readContract();
    abi = [
      {
        inputs: [],
        name: "eip712Domain",
        outputs: [
          { name: "fields", type: "bytes1" },
          { name: "name", type: "string" },
          { name: "version", type: "string" },
          { name: "chainId", type: "uint256" },
          { name: "verifyingContract", type: "address" },
          { name: "salt", type: "bytes32" },
          { name: "extensions", type: "uint256[]" }
        ],
        stateMutability: "view",
        type: "function"
      }
    ];
  }
});

// node_modules/viem/_esm/utils/formatters/feeHistory.js
function formatFeeHistory(feeHistory) {
  return {
    baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)),
    gasUsedRatio: feeHistory.gasUsedRatio,
    oldestBlock: BigInt(feeHistory.oldestBlock),
    reward: feeHistory.reward?.map((reward) => reward.map((value) => BigInt(value)))
  };
}
var init_feeHistory = __esm({
  "node_modules/viem/_esm/utils/formatters/feeHistory.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/actions/public/getFeeHistory.js
async function getFeeHistory(client, { blockCount, blockNumber, blockTag = "latest", rewardPercentiles }) {
  const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : void 0;
  const feeHistory = await client.request({
    method: "eth_feeHistory",
    params: [
      numberToHex(blockCount),
      blockNumberHex || blockTag,
      rewardPercentiles
    ]
  }, { dedupe: Boolean(blockNumberHex) });
  return formatFeeHistory(feeHistory);
}
var init_getFeeHistory = __esm({
  "node_modules/viem/_esm/actions/public/getFeeHistory.js"() {
    "use strict";
    init_toHex();
    init_feeHistory();
  }
});

// node_modules/viem/_esm/actions/public/getFilterLogs.js
async function getFilterLogs(_client, { filter }) {
  const strict = filter.strict ?? false;
  const logs = await filter.request({
    method: "eth_getFilterLogs",
    params: [filter.id]
  });
  const formattedLogs = logs.map((log) => formatLog(log));
  if (!filter.abi)
    return formattedLogs;
  return parseEventLogs({
    abi: filter.abi,
    logs: formattedLogs,
    strict
  });
}
var init_getFilterLogs = __esm({
  "node_modules/viem/_esm/actions/public/getFilterLogs.js"() {
    "use strict";
    init_parseEventLogs();
    init_log2();
  }
});

// node_modules/viem/_esm/utils/transaction/assertTransaction.js
function assertTransactionEIP7702(transaction) {
  const { authorizationList } = transaction;
  if (authorizationList) {
    for (const authorization of authorizationList) {
      const { chainId } = authorization;
      const address2 = authorization.address;
      if (!isAddress(address2))
        throw new InvalidAddressError({ address: address2 });
      if (chainId < 0)
        throw new InvalidChainIdError({ chainId });
    }
  }
  assertTransactionEIP1559(transaction);
}
function assertTransactionEIP4844(transaction) {
  const { blobVersionedHashes } = transaction;
  if (blobVersionedHashes) {
    if (blobVersionedHashes.length === 0)
      throw new EmptyBlobError();
    for (const hash3 of blobVersionedHashes) {
      const size_ = size(hash3);
      const version4 = hexToNumber(slice(hash3, 0, 1));
      if (size_ !== 32)
        throw new InvalidVersionedHashSizeError({ hash: hash3, size: size_ });
      if (version4 !== versionedHashVersionKzg)
        throw new InvalidVersionedHashVersionError({
          hash: hash3,
          version: version4
        });
    }
  }
  assertTransactionEIP1559(transaction);
}
function assertTransactionEIP1559(transaction) {
  const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction;
  if (chainId <= 0)
    throw new InvalidChainIdError({ chainId });
  if (to && !isAddress(to))
    throw new InvalidAddressError({ address: to });
  if (maxFeePerGas && maxFeePerGas > maxUint256)
    throw new FeeCapTooHighError({ maxFeePerGas });
  if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas)
    throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });
}
function assertTransactionEIP2930(transaction) {
  const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;
  if (chainId <= 0)
    throw new InvalidChainIdError({ chainId });
  if (to && !isAddress(to))
    throw new InvalidAddressError({ address: to });
  if (maxPriorityFeePerGas || maxFeePerGas)
    throw new BaseError2("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");
  if (gasPrice && gasPrice > maxUint256)
    throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });
}
function assertTransactionLegacy(transaction) {
  const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction;
  if (to && !isAddress(to))
    throw new InvalidAddressError({ address: to });
  if (typeof chainId !== "undefined" && chainId <= 0)
    throw new InvalidChainIdError({ chainId });
  if (maxPriorityFeePerGas || maxFeePerGas)
    throw new BaseError2("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");
  if (gasPrice && gasPrice > maxUint256)
    throw new FeeCapTooHighError({ maxFeePerGas: gasPrice });
}
var init_assertTransaction = __esm({
  "node_modules/viem/_esm/utils/transaction/assertTransaction.js"() {
    "use strict";
    init_kzg();
    init_number();
    init_address();
    init_base();
    init_blob2();
    init_chain();
    init_node();
    init_isAddress();
    init_size();
    init_slice();
    init_fromHex();
  }
});

// node_modules/viem/_esm/utils/transaction/serializeAccessList.js
function serializeAccessList(accessList) {
  if (!accessList || accessList.length === 0)
    return [];
  const serializedAccessList = [];
  for (let i = 0; i < accessList.length; i++) {
    const { address: address2, storageKeys } = accessList[i];
    for (let j = 0; j < storageKeys.length; j++) {
      if (storageKeys[j].length - 2 !== 64) {
        throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] });
      }
    }
    if (!isAddress(address2, { strict: false })) {
      throw new InvalidAddressError({ address: address2 });
    }
    serializedAccessList.push([address2, storageKeys]);
  }
  return serializedAccessList;
}
var init_serializeAccessList = __esm({
  "node_modules/viem/_esm/utils/transaction/serializeAccessList.js"() {
    "use strict";
    init_address();
    init_transaction();
    init_isAddress();
  }
});

// node_modules/viem/_esm/utils/transaction/serializeTransaction.js
function serializeTransaction(transaction, signature2) {
  const type = getTransactionType(transaction);
  if (type === "eip1559")
    return serializeTransactionEIP1559(transaction, signature2);
  if (type === "eip2930")
    return serializeTransactionEIP2930(transaction, signature2);
  if (type === "eip4844")
    return serializeTransactionEIP4844(transaction, signature2);
  if (type === "eip7702")
    return serializeTransactionEIP7702(transaction, signature2);
  return serializeTransactionLegacy(transaction, signature2);
}
function serializeTransactionEIP7702(transaction, signature2) {
  const { authorizationList, chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
  assertTransactionEIP7702(transaction);
  const serializedAccessList = serializeAccessList(accessList);
  const serializedAuthorizationList = serializeAuthorizationList(authorizationList);
  return concatHex([
    "0x04",
    toRlp([
      numberToHex(chainId),
      nonce ? numberToHex(nonce) : "0x",
      maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x",
      maxFeePerGas ? numberToHex(maxFeePerGas) : "0x",
      gas ? numberToHex(gas) : "0x",
      to ?? "0x",
      value ? numberToHex(value) : "0x",
      data ?? "0x",
      serializedAccessList,
      serializedAuthorizationList,
      ...toYParitySignatureArray(transaction, signature2)
    ])
  ]);
}
function serializeTransactionEIP4844(transaction, signature2) {
  const { chainId, gas, nonce, to, value, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
  assertTransactionEIP4844(transaction);
  let blobVersionedHashes = transaction.blobVersionedHashes;
  let sidecars = transaction.sidecars;
  if (transaction.blobs && (typeof blobVersionedHashes === "undefined" || typeof sidecars === "undefined")) {
    const blobs2 = typeof transaction.blobs[0] === "string" ? transaction.blobs : transaction.blobs.map((x) => bytesToHex(x));
    const kzg = transaction.kzg;
    const commitments2 = blobsToCommitments({
      blobs: blobs2,
      kzg
    });
    if (typeof blobVersionedHashes === "undefined")
      blobVersionedHashes = commitmentsToVersionedHashes({
        commitments: commitments2
      });
    if (typeof sidecars === "undefined") {
      const proofs2 = blobsToProofs({ blobs: blobs2, commitments: commitments2, kzg });
      sidecars = toBlobSidecars({ blobs: blobs2, commitments: commitments2, proofs: proofs2 });
    }
  }
  const serializedAccessList = serializeAccessList(accessList);
  const serializedTransaction = [
    numberToHex(chainId),
    nonce ? numberToHex(nonce) : "0x",
    maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x",
    maxFeePerGas ? numberToHex(maxFeePerGas) : "0x",
    gas ? numberToHex(gas) : "0x",
    to ?? "0x",
    value ? numberToHex(value) : "0x",
    data ?? "0x",
    serializedAccessList,
    maxFeePerBlobGas ? numberToHex(maxFeePerBlobGas) : "0x",
    blobVersionedHashes ?? [],
    ...toYParitySignatureArray(transaction, signature2)
  ];
  const blobs = [];
  const commitments = [];
  const proofs = [];
  if (sidecars)
    for (let i = 0; i < sidecars.length; i++) {
      const { blob, commitment, proof } = sidecars[i];
      blobs.push(blob);
      commitments.push(commitment);
      proofs.push(proof);
    }
  return concatHex([
    "0x03",
    sidecars ? (
      // If sidecars are enabled, envelope turns into a "wrapper":
      toRlp([serializedTransaction, blobs, commitments, proofs])
    ) : (
      // If sidecars are disabled, standard envelope is used:
      toRlp(serializedTransaction)
    )
  ]);
}
function serializeTransactionEIP1559(transaction, signature2) {
  const { chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction;
  assertTransactionEIP1559(transaction);
  const serializedAccessList = serializeAccessList(accessList);
  const serializedTransaction = [
    numberToHex(chainId),
    nonce ? numberToHex(nonce) : "0x",
    maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x",
    maxFeePerGas ? numberToHex(maxFeePerGas) : "0x",
    gas ? numberToHex(gas) : "0x",
    to ?? "0x",
    value ? numberToHex(value) : "0x",
    data ?? "0x",
    serializedAccessList,
    ...toYParitySignatureArray(transaction, signature2)
  ];
  return concatHex([
    "0x02",
    toRlp(serializedTransaction)
  ]);
}
function serializeTransactionEIP2930(transaction, signature2) {
  const { chainId, gas, data, nonce, to, value, accessList, gasPrice } = transaction;
  assertTransactionEIP2930(transaction);
  const serializedAccessList = serializeAccessList(accessList);
  const serializedTransaction = [
    numberToHex(chainId),
    nonce ? numberToHex(nonce) : "0x",
    gasPrice ? numberToHex(gasPrice) : "0x",
    gas ? numberToHex(gas) : "0x",
    to ?? "0x",
    value ? numberToHex(value) : "0x",
    data ?? "0x",
    serializedAccessList,
    ...toYParitySignatureArray(transaction, signature2)
  ];
  return concatHex([
    "0x01",
    toRlp(serializedTransaction)
  ]);
}
function serializeTransactionLegacy(transaction, signature2) {
  const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction;
  assertTransactionLegacy(transaction);
  let serializedTransaction = [
    nonce ? numberToHex(nonce) : "0x",
    gasPrice ? numberToHex(gasPrice) : "0x",
    gas ? numberToHex(gas) : "0x",
    to ?? "0x",
    value ? numberToHex(value) : "0x",
    data ?? "0x"
  ];
  if (signature2) {
    const v = (() => {
      if (signature2.v >= 35n) {
        const inferredChainId = (signature2.v - 35n) / 2n;
        if (inferredChainId > 0)
          return signature2.v;
        return 27n + (signature2.v === 35n ? 0n : 1n);
      }
      if (chainId > 0)
        return BigInt(chainId * 2) + BigInt(35n + signature2.v - 27n);
      const v2 = 27n + (signature2.v === 27n ? 0n : 1n);
      if (signature2.v !== v2)
        throw new InvalidLegacyVError({ v: signature2.v });
      return v2;
    })();
    const r = trim(signature2.r);
    const s3 = trim(signature2.s);
    serializedTransaction = [
      ...serializedTransaction,
      numberToHex(v),
      r === "0x00" ? "0x" : r,
      s3 === "0x00" ? "0x" : s3
    ];
  } else if (chainId > 0) {
    serializedTransaction = [
      ...serializedTransaction,
      numberToHex(chainId),
      "0x",
      "0x"
    ];
  }
  return toRlp(serializedTransaction);
}
function toYParitySignatureArray(transaction, signature_) {
  const signature2 = signature_ ?? transaction;
  const { v, yParity } = signature2;
  if (typeof signature2.r === "undefined")
    return [];
  if (typeof signature2.s === "undefined")
    return [];
  if (typeof v === "undefined" && typeof yParity === "undefined")
    return [];
  const r = trim(signature2.r);
  const s3 = trim(signature2.s);
  const yParity_ = (() => {
    if (typeof yParity === "number")
      return yParity ? numberToHex(1) : "0x";
    if (v === 0n)
      return "0x";
    if (v === 1n)
      return numberToHex(1);
    return v === 27n ? "0x" : numberToHex(1);
  })();
  return [yParity_, r === "0x00" ? "0x" : r, s3 === "0x00" ? "0x" : s3];
}
var init_serializeTransaction = __esm({
  "node_modules/viem/_esm/utils/transaction/serializeTransaction.js"() {
    "use strict";
    init_transaction();
    init_serializeAuthorizationList();
    init_blobsToCommitments();
    init_blobsToProofs();
    init_commitmentsToVersionedHashes();
    init_toBlobSidecars();
    init_concat();
    init_trim();
    init_toHex();
    init_toRlp();
    init_assertTransaction();
    init_getTransactionType();
    init_serializeAccessList();
  }
});

// node_modules/viem/_esm/utils/authorization/serializeAuthorizationList.js
function serializeAuthorizationList(authorizationList) {
  if (!authorizationList || authorizationList.length === 0)
    return [];
  const serializedAuthorizationList = [];
  for (const authorization of authorizationList) {
    const { chainId, nonce, ...signature2 } = authorization;
    const contractAddress = authorization.address;
    serializedAuthorizationList.push([
      chainId ? toHex(chainId) : "0x",
      contractAddress,
      nonce ? toHex(nonce) : "0x",
      ...toYParitySignatureArray({}, signature2)
    ]);
  }
  return serializedAuthorizationList;
}
var init_serializeAuthorizationList = __esm({
  "node_modules/viem/_esm/utils/authorization/serializeAuthorizationList.js"() {
    "use strict";
    init_toHex();
    init_serializeTransaction();
  }
});

// node_modules/viem/_esm/utils/authorization/verifyAuthorization.js
async function verifyAuthorization({ address: address2, authorization, signature: signature2 }) {
  return isAddressEqual(getAddress(address2), await recoverAuthorizationAddress({
    authorization,
    signature: signature2
  }));
}
var init_verifyAuthorization = __esm({
  "node_modules/viem/_esm/utils/authorization/verifyAuthorization.js"() {
    "use strict";
    init_getAddress();
    init_isAddressEqual();
    init_recoverAuthorizationAddress();
  }
});

// node_modules/viem/_esm/utils/promise/withDedupe.js
function withDedupe(fn, { enabled = true, id }) {
  if (!enabled || !id)
    return fn();
  if (promiseCache2.get(id))
    return promiseCache2.get(id);
  const promise = fn().finally(() => promiseCache2.delete(id));
  promiseCache2.set(id, promise);
  return promise;
}
var promiseCache2;
var init_withDedupe = __esm({
  "node_modules/viem/_esm/utils/promise/withDedupe.js"() {
    "use strict";
    init_lru();
    promiseCache2 = /* @__PURE__ */ new LruMap(8192);
  }
});

// node_modules/viem/_esm/utils/buildRequest.js
function buildRequest(request, options = {}) {
  return async (args, overrideOptions = {}) => {
    const { dedupe = false, methods, retryDelay = 150, retryCount = 3, uid: uid2 } = {
      ...options,
      ...overrideOptions
    };
    const { method } = args;
    if (methods?.exclude?.includes(method))
      throw new MethodNotSupportedRpcError(new Error("method not supported"), {
        method
      });
    if (methods?.include && !methods.include.includes(method))
      throw new MethodNotSupportedRpcError(new Error("method not supported"), {
        method
      });
    const requestId = dedupe ? hashString(`${uid2}.${stringify(args)}`) : void 0;
    return withDedupe(() => withRetry(async () => {
      try {
        return await request(args);
      } catch (err_) {
        const err = err_;
        switch (err.code) {
          // -32700
          case ParseRpcError.code:
            throw new ParseRpcError(err);
          // -32600
          case InvalidRequestRpcError.code:
            throw new InvalidRequestRpcError(err);
          // -32601
          case MethodNotFoundRpcError.code:
            throw new MethodNotFoundRpcError(err, { method: args.method });
          // -32602
          case InvalidParamsRpcError.code:
            throw new InvalidParamsRpcError(err);
          // -32603
          case InternalRpcError.code:
            throw new InternalRpcError(err);
          // -32000
          case InvalidInputRpcError.code:
            throw new InvalidInputRpcError(err);
          // -32001
          case ResourceNotFoundRpcError.code:
            throw new ResourceNotFoundRpcError(err);
          // -32002
          case ResourceUnavailableRpcError.code:
            throw new ResourceUnavailableRpcError(err);
          // -32003
          case TransactionRejectedRpcError.code:
            throw new TransactionRejectedRpcError(err);
          // -32004
          case MethodNotSupportedRpcError.code:
            throw new MethodNotSupportedRpcError(err, {
              method: args.method
            });
          // -32005
          case LimitExceededRpcError.code:
            throw new LimitExceededRpcError(err);
          // -32006
          case JsonRpcVersionUnsupportedError.code:
            throw new JsonRpcVersionUnsupportedError(err);
          // 4001
          case UserRejectedRequestError.code:
            throw new UserRejectedRequestError(err);
          // 4100
          case UnauthorizedProviderError.code:
            throw new UnauthorizedProviderError(err);
          // 4200
          case UnsupportedProviderMethodError.code:
            throw new UnsupportedProviderMethodError(err);
          // 4900
          case ProviderDisconnectedError.code:
            throw new ProviderDisconnectedError(err);
          // 4901
          case ChainDisconnectedError.code:
            throw new ChainDisconnectedError(err);
          // 4902
          case SwitchChainError.code:
            throw new SwitchChainError(err);
          // 5700
          case UnsupportedNonOptionalCapabilityError.code:
            throw new UnsupportedNonOptionalCapabilityError(err);
          // 5710
          case UnsupportedChainIdError.code:
            throw new UnsupportedChainIdError(err);
          // 5720
          case DuplicateIdError.code:
            throw new DuplicateIdError(err);
          // 5730
          case UnknownBundleIdError.code:
            throw new UnknownBundleIdError(err);
          // 5740
          case BundleTooLargeError.code:
            throw new BundleTooLargeError(err);
          // 5750
          case AtomicReadyWalletRejectedUpgradeError.code:
            throw new AtomicReadyWalletRejectedUpgradeError(err);
          // 5760
          case AtomicityNotSupportedError.code:
            throw new AtomicityNotSupportedError(err);
          // CAIP-25: User Rejected Error
          // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes#rejected-caip-25
          case 5e3:
            throw new UserRejectedRequestError(err);
          // WalletConnect: Session Settlement Failed
          // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes
          case WalletConnectSessionSettlementError.code:
            throw new WalletConnectSessionSettlementError(err);
          default:
            if (err_ instanceof BaseError2)
              throw err_;
            throw new UnknownRpcError(err);
        }
      }
    }, {
      delay: ({ count, error }) => {
        if (error && error instanceof HttpRequestError) {
          const retryAfter = error?.headers?.get("Retry-After");
          if (retryAfter?.match(/\d/))
            return Number.parseInt(retryAfter, 10) * 1e3;
        }
        return ~~(1 << count) * retryDelay;
      },
      retryCount,
      shouldRetry: ({ error }) => shouldRetry(error)
    }), { enabled: dedupe, id: requestId });
  };
}
function shouldRetry(error) {
  if ("code" in error && typeof error.code === "number") {
    if (error.code === -1)
      return true;
    if (error.code === LimitExceededRpcError.code)
      return true;
    if (error.code === InternalRpcError.code)
      return true;
    if (error.code === 429)
      return true;
    return false;
  }
  if (error instanceof HttpRequestError && error.status) {
    if (error.status === 403)
      return true;
    if (error.status === 408)
      return true;
    if (error.status === 413)
      return true;
    if (error.status === 429)
      return true;
    if (error.status === 500)
      return true;
    if (error.status === 502)
      return true;
    if (error.status === 503)
      return true;
    if (error.status === 504)
      return true;
    return false;
  }
  return true;
}
function hashString(str, seed = 0) {
  let h1 = 3735928559 ^ seed;
  let h2 = 1103547991 ^ seed;
  for (let i = 0; i < str.length; i++) {
    const ch = str.charCodeAt(i);
    h1 = Math.imul(h1 ^ ch, 2654435761);
    h2 = Math.imul(h2 ^ ch, 1597334677);
  }
  h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507);
  h1 ^= Math.imul(h2 ^ h2 >>> 16, 3266489909);
  h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507);
  h2 ^= Math.imul(h1 ^ h1 >>> 16, 3266489909);
  return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
}
var init_buildRequest = __esm({
  "node_modules/viem/_esm/utils/buildRequest.js"() {
    "use strict";
    init_base();
    init_request();
    init_rpc();
    init_withDedupe();
    init_withRetry();
    init_stringify();
  }
});

// node_modules/viem/_esm/utils/chain/defineChain.js
function defineChain(chain3) {
  const chainInstance = {
    formatters: void 0,
    fees: void 0,
    serializers: void 0,
    ...chain3
  };
  function extend(base2) {
    return (fnOrExtended) => {
      const properties = typeof fnOrExtended === "function" ? fnOrExtended(base2) : fnOrExtended;
      const combined = { ...base2, ...properties };
      return Object.assign(combined, { extend: extend(combined) });
    };
  }
  return Object.assign(chainInstance, {
    extend: extend(chainInstance)
  });
}
var init_defineChain = __esm({
  "node_modules/viem/_esm/utils/chain/defineChain.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/utils/promise/withTimeout.js
function withTimeout(fn, { errorInstance = new Error("timed out"), timeout, signal }) {
  return new Promise((resolve, reject) => {
    ;
    (async () => {
      let timeoutId;
      try {
        const controller = new AbortController();
        if (timeout > 0) {
          timeoutId = setTimeout(() => {
            if (signal) {
              controller.abort();
            } else {
              reject(errorInstance);
            }
          }, timeout);
        }
        resolve(await fn({ signal: controller?.signal || null }));
      } catch (err) {
        if (err?.name === "AbortError")
          reject(errorInstance);
        reject(err);
      } finally {
        clearTimeout(timeoutId);
      }
    })();
  });
}
var init_withTimeout = __esm({
  "node_modules/viem/_esm/utils/promise/withTimeout.js"() {
    "use strict";
  }
});

// node_modules/viem/_esm/utils/rpc/id.js
function createIdStore() {
  return {
    current: 0,
    take() {
      return this.current++;
    },
    reset() {
      this.current = 0;
    }
  };
}
var idCache;
var init_id = __esm({
  "node_modules/viem/_esm/utils/rpc/id.js"() {
    "use strict";
    idCache = /* @__PURE__ */ createIdStore();
  }
});

// node_modules/viem/_esm/utils/rpc/http.js
function getHttpRpcClient(url_, options = {}) {
  const { url, headers: headers_url } = parseUrl(url_);
  return {
    async request(params) {
      const { body, fetchFn = options.fetchFn ?? fetch, onRequest = options.onRequest, onResponse = options.onResponse, timeout = options.timeout ?? 1e4 } = params;
      const fetchOptions = {
        ...options.fetchOptions ?? {},
        ...params.fetchOptions ?? {}
      };
      const { headers, method, signal: signal_ } = fetchOptions;
      try {
        const response = await withTimeout(async ({ signal }) => {
          const init = {
            ...fetchOptions,
            body: Array.isArray(body) ? stringify(body.map((body2) => ({
              jsonrpc: "2.0",
              id: body2.id ?? idCache.take(),
              ...body2
            }))) : stringify({
              jsonrpc: "2.0",
              id: body.id ?? idCache.take(),
              ...body
            }),
            headers: {
              ...headers_url,
              "Content-Type": "application/json",
              ...headers
            },
            method: method || "POST",
            signal: signal_ || (timeout > 0 ? signal : null)
          };
          const request = new Request(url, init);
          const args = await onRequest?.(request, init) ?? { ...init, url };
          const response2 = await fetchFn(args.url ?? url, args);
          return response2;
        }, {
          errorInstance: new TimeoutError({ body, url }),
          timeout,
          signal: true
        });
        if (onResponse)
          await onResponse(response);
        let data;
        if (response.headers.get("Content-Type")?.startsWith("application/json"))
          data = await response.json();
        else {
          data = await response.text();
          try {
            data = JSON.parse(data || "{}");
          } catch (err) {
            if (response.ok)
              throw err;
            data = { error: data };
          }
        }
        if (!response.ok) {
          if (typeof data.error?.code === "number" && typeof data.error?.message === "string")
            return data;
          throw new HttpRequestError({
            body,
            details: stringify(data.error) || response.statusText,
            headers: response.headers,
            status: response.status,
            url
          });
        }
        return data;
      } catch (err) {
        if (err instanceof HttpRequestError)
          throw err;
        if (err instanceof TimeoutError)
          throw err;
        throw new HttpRequestError({
          body,
          cause: err,
          url
        });
      }
    }
  };
}
function parseUrl(url_) {
  try {
    const url = new URL(url_);
    const result = (() => {
      if (url.username) {
        const credentials = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`;
        url.username = "";
        url.password = "";
        return {
          url: url.toString(),
          headers: { Authorization: `Basic ${btoa(credentials)}` }
        };
      }
      return;
    })();
    return { url: url.toString(), ...result };
  } catch {
    return { url: url_ };
  }
}
var init_http = __esm({
  "node_modules/viem/_esm/utils/rpc/http.js"() {
    "use strict";
    init_request();
    init_withTimeout();
    init_stringify();
    init_id();
  }
});

// node_modules/viem/_esm/constants/strings.js
var presignMessagePrefix;
var init_strings = __esm({
  "node_modules/viem/_esm/constants/strings.js"() {
    "use strict";
    presignMessagePrefix = "Ethereum Signed Message:\n";
  }
});

// node_modules/viem/_esm/utils/signature/toPrefixedMessage.js
function toPrefixedMessage(message_) {
  const message = (() => {
    if (typeof message_ === "string")
      return stringToHex(message_);
    if (typeof message_.raw === "string")
      return message_.raw;
    return bytesToHex(message_.raw);
  })();
  const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`);
  return concat([prefix, message]);
}
var init_toPrefixedMessage = __esm({
  "node_modules/viem/_esm/utils/signature/toPrefixedMessage.js"() {
    "use strict";
    init_strings();
    init_concat();
    init_size();
    init_toHex();
  }
});

// node_modules/viem/_esm/utils/signature/hashMessage.js
function hashMessage(message, to_) {
  return keccak256(toPrefixedMessage(message), to_);
}
var init_hashMessage = __esm({
  "node_modules/viem/_esm/utils/signature/hashMessage.js"() {
    "use strict";
    init_keccak256();
    init_toPrefixedMessage();
  }
});

// node_modules/viem/_esm/errors/typedData.js
var InvalidDomainError, InvalidPrimaryTypeError, InvalidStructTypeError;
var init_typedData = __esm({
  "node_modules/viem/_esm/errors/typedData.js"() {
    "use strict";
    init_stringify();
    init_base();
    InvalidDomainError = class extends BaseError2 {
      constructor({ domain }) {
        super(`Invalid domain "${stringify(domain)}".`, {
          metaMessages: ["Must be a valid EIP-712 domain."]
        });
      }
    };
    InvalidPrimaryTypeError = class extends BaseError2 {
      constructor({ primaryType, types }) {
        super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types))}\`.`, {
          docsPath: "/api/glossary/Errors#typeddatainvalidprimarytypeerror",
          metaMessages: ["Check that the primary type is a key in `types`."]
        });
      }
    };
    InvalidStructTypeError = class extends BaseError2 {
      constructor({ type }) {
        super(`Struct type "${type}" is invalid.`, {
          metaMessages: ["Struct type must not be a Solidity type."],
          name: "InvalidStructTypeError"
        });
      }
    };
  }
});

// node_modules/viem/_esm/utils/typedData.js
function validateTypedData(parameters) {
  const { domain, message, primaryType, types } = parameters;
  const validateData = (struct, data) => {
    for (const param of struct) {
      const { name, type } = param;
      const value = data[name];
      const integerMatch = type.match(integerRegex2);
      if (integerMatch && (typeof value === "number" || typeof value === "bigint")) {
        const [_type, base2, size_] = integerMatch;
        numberToHex(value, {
          signed: base2 === "int",
          size: Number.parseInt(size_, 10) / 8
        });
      }
      if (type === "address" && typeof value === "string" && !isAddress(value))
        throw new InvalidAddressError({ address: value });
      const bytesMatch = type.match(bytesRegex2);
      if (bytesMatch) {
        const [_type, size_] = bytesMatch;
        if (size_ && size(value) !== Number.parseInt(size_, 10))
          throw new BytesSizeMismatchError({
            expectedSize: Number.parseInt(size_, 10),
            givenSize: size(value)
          });
      }
      const struct2 = types[type];
      if (struct2) {
        validateReference(type);
        validateData(struct2, value);
      }
    }
  };
  if (types.EIP712Domain && domain) {
    if (typeof domain !== "object")
      throw new InvalidDomainError({ domain });
    validateData(types.EIP712Domain, domain);
  }
  if (primaryType !== "EIP712Domain") {
    if (types[primaryType])
      validateData(types[primaryType], message);
    else
      throw new InvalidPrimaryTypeError({ primaryType, types });
  }
}
function getTypesForEIP712Domain({ domain }) {
  return [
    typeof domain?.name === "string" && { name: "name", type: "string" },
    domain?.version && { name: "version", type: "string" },
    (typeof domain?.chainId === "number" || typeof domain?.chainId === "bigint") && {
      name: "chainId",
      type: "uint256"
    },
    domain?.verifyingContract && {
      name: "verifyingContract",
      type: "address"
    },
    domain?.salt && { name: "salt", type: "bytes32" }
  ].filter(Boolean);
}
function validateReference(type) {
  if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int"))
    throw new InvalidStructTypeError({ type });
}
var init_typedData2 = __esm({
  "node_modules/viem/_esm/utils/typedData.js"() {
    "use strict";
    init_abi();
    init_address();
    init_typedData();
    init_isAddress();
    init_size();
    init_toHex();
    init_regex2();
  }
});

// node_modules/viem/_esm/utils/signature/hashTypedData.js
function hashTypedData(parameters) {
  const { domain = {}, message, primaryType } = parameters;
  const types = {
    EIP712Domain: getTypesForEIP712Domain({ domain }),
    ...parameters.types
  };
  validateTypedData({
    domain,
    message,
    primaryType,
    types
  });
  const parts = ["0x1901"];
  if (domain)
    parts.push(hashDomain({
      domain,
      types
    }));
  if (primaryType !== "EIP712Domain")
    parts.push(hashStruct({
      data: message,
      primaryType,
      types
    }));
  return keccak256(concat(parts));
}
function hashDomain({ domain, types }) {
  return hashStruct({
    data: domain,
    primaryType: "EIP712Domain",
    types
  });
}
function hashStruct({ data, primaryType, types }) {
  const encoded = encodeData({
    data,
    primaryType,
    types
  });
  return keccak256(encoded);
}
function encodeData({ data, primaryType, types }) {
  const encodedTypes = [{ type: "bytes32" }];
  const encodedValues = [hashType({ primaryType, types })];
  for (const field of types[primaryType]) {
    const [type, value] = encodeField({
      types,
      name: field.name,
      type: field.type,
      value: data[field.name]
    });
    encodedTypes.push(type);
    encodedValues.push(value);
  }
  return encodeAbiParameters(encodedTypes, encodedValues);
}
function hashType({ primaryType, types }) {
  const encodedHashType = toHex(encodeType({ primaryType, types }));
  return keccak256(encodedHashType);
}
function encodeType({ primaryType, types }) {
  let result = "";
  const unsortedDeps = findTypeDependencies({ primaryType, types });
  unsortedDeps.delete(primaryType);
  const deps = [primaryType, ...Array.from(unsortedDeps).sort()];
  for (const type of deps) {
    result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`;
  }
  return result;
}
function findTypeDependencies({ primaryType: primaryType_, types }, results = /* @__PURE__ */ new Set()) {
  const match = primaryType_.match(/^\w*/u);
  const primaryType = match?.[0];
  if (results.has(primaryType) || types[primaryType] === void 0) {
    return results;
  }
  results.add(primaryType);
  for (const field of types[primaryType]) {
    findTypeDependencies({ primaryType: field.type, types }, results);
  }
  return results;
}
function encodeField({ types, name, type, value }) {
  if (types[type] !== void 0) {
    return [
      { type: "bytes32" },
      keccak256(encodeData({ data: value, primaryType: type, types }))
    ];
  }
  if (type === "bytes")
    return [{ type: "bytes32" }, keccak256(value)];
  if (type === "string")
    return [{ type: "bytes32" }, keccak256(toHex(value))];
  if (type.lastIndexOf("]") === type.length - 1) {
    const parsedType = type.slice(0, type.lastIndexOf("["));
    const typeValuePairs = value.map((item) => encodeField({
      name,
      type: parsedType,
      types,
      value: item
    }));
    return [
      { type: "bytes32" },
      keccak256(encodeAbiParameters(typeValuePairs.map(([t]) => t), typeValuePairs.map(([, v]) => v)))
    ];
  }
  return [{ type }, value];
}
var init_hashTypedData = __esm({
  "node_modules/viem/_esm/utils/signature/hashTypedData.js"() {
    "use strict";
    init_encodeAbiParameters();
    init_concat();
    init_toHex();
    init_keccak256();
    init_typedData2();
  }
});

// node_modules/ox/_esm/core/internal/lru.js
var LruMap2;
var init_lru2 = __esm({
  "node_modules/ox/_esm/core/internal/lru.js"() {
    "use strict";
    LruMap2 = class extends Map {
      constructor(size5) {
        super();
        Object.defineProperty(this, "maxSize", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: void 0
        });
        this.maxSize = size5;
      }
      get(key) {
        const value = super.get(key);
        if (super.has(key) && value !== void 0) {
          this.delete(key);
          super.set(key, value);
        }
        return value;
      }
      set(key, value) {
        super.set(key, value);
        if (this.maxSize && this.size > this.maxSize) {
          const firstKey = this.keys().next().value;
          if (firstKey)
            this.delete(firstKey);
        }
        return this;
      }
    };
  }
});

// node_modules/ox/_esm/core/Caches.js
var caches, checksum;
var init_Caches = __esm({
  "node_modules/ox/_esm/core/Caches.js"() {
    "use strict";
    init_lru2();
    caches = {
      checksum: /* @__PURE__ */ new LruMap2(8192)
    };
    checksum = caches.checksum;
  }
});

// node_modules/ox/node_modules/@noble/hashes/esm/cryptoNode.js
import * as nc2 from "crypto";
var crypto3;
var init_cryptoNode2 = __esm({
  "node_modules/ox/node_modules/@noble/hashes/esm/cryptoNode.js"() {
    "use strict";
    crypto3 = nc2 && typeof nc2 === "object" && "webcrypto" in nc2 ? nc2.webcrypto : nc2 && typeof nc2 === "object" && "randomBytes" in nc2 ? nc2 : void 0;
  }
});

// node_modules/ox/node_modules/@noble/hashes/esm/utils.js
function isBytes4(a) {
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
function anumber2(n) {
  if (!Number.isSafeInteger(n) || n < 0)
    throw new Error("positive integer expected, got " + n);
}
function abytes4(b, ...lengths) {
  if (!isBytes4(b))
    throw new Error("Uint8Array expected");
  if (lengths.length > 0 && !lengths.includes(b.length))
    throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
}
function ahash2(h) {
  if (typeof h !== "function" || typeof h.create !== "function")
    throw new Error("Hash should be wrapped by utils.createHasher");
  anumber2(h.outputLen);
  anumber2(h.blockLen);
}
function aexists2(instance, checkFinished = true) {
  if (instance.destroyed)
    throw new Error("Hash instance has been destroyed");
  if (checkFinished && instance.finished)
    throw new Error("Hash#digest() has already been called");
}
function aoutput2(out, instance) {
  abytes4(out);
  const min = instance.outputLen;
  if (out.length < min) {
    throw new Error("digestInto() expects output buffer of length at least " + min);
  }
}
function u322(arr) {
  return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
}
function clean2(...arrays) {
  for (let i = 0; i < arrays.length; i++) {
    arrays[i].fill(0);
  }
}
function createView2(arr) {
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
function rotr2(word, shift) {
  return word << 32 - shift | word >>> shift;
}
function byteSwap2(word) {
  return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
}
function byteSwap322(arr) {
  for (let i = 0; i < arr.length; i++) {
    arr[i] = byteSwap2(arr[i]);
  }
  return arr;
}
function utf8ToBytes3(str) {
  if (typeof str !== "string")
    throw new Error("string expected");
  return new Uint8Array(new TextEncoder().encode(str));
}
function toBytes3(data) {
  if (typeof data === "string")
    data = utf8ToBytes3(data);
  abytes4(data);
  return data;
}
function concatBytes5(...arrays) {
  let sum = 0;
  for (let i = 0; i < arrays.length; i++) {
    const a = arrays[i];
    abytes4(a);
    sum += a.length;
  }
  const res = new Uint8Array(sum);
  for (let i = 0, pad4 = 0; i < arrays.length; i++) {
    const a = arrays[i];
    res.set(a, pad4);
    pad4 += a.length;
  }
  return res;
}
function createHasher3(hashCons) {
  const hashC = (msg) => hashCons().update(toBytes3(msg)).digest();
  const tmp = hashCons();
  hashC.outputLen = tmp.outputLen;
  hashC.blockLen = tmp.blockLen;
  hashC.create = () => hashCons();
  return hashC;
}
function randomBytes2(bytesLength = 32) {
  if (crypto3 && typeof crypto3.getRandomValues === "function") {
    return crypto3.getRandomValues(new Uint8Array(bytesLength));
  }
  if (crypto3 && typeof crypto3.randomBytes === "function") {
    return Uint8Array.from(crypto3.randomBytes(bytesLength));
  }
  throw new Error("crypto.getRandomValues must be defined");
}
var isLE2, swap32IfBE2, Hash2;
var init_utils7 = __esm({
  "node_modules/ox/node_modules/@noble/hashes/esm/utils.js"() {
    "use strict";
    init_cryptoNode2();
    isLE2 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
    swap32IfBE2 = isLE2 ? (u) => u : byteSwap322;
    Hash2 = class {
    };
  }
});

// node_modules/ox/node_modules/@noble/hashes/esm/hmac.js
var HMAC2, hmac2;
var init_hmac2 = __esm({
  "node_modules/ox/node_modules/@noble/hashes/esm/hmac.js"() {
    "use strict";
    init_utils7();
    HMAC2 = class extends Hash2 {
      constructor(hash3, _key) {
        super();
        this.finished = false;
        this.destroyed = false;
        ahash2(hash3);
        const key = toBytes3(_key);
        this.iHash = hash3.create();
        if (typeof this.iHash.update !== "function")
          throw new Error("Expected instance of class which extends utils.Hash");
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad4 = new Uint8Array(blockLen);
        pad4.set(key.length > blockLen ? hash3.create().update(key).digest() : key);
        for (let i = 0; i < pad4.length; i++)
          pad4[i] ^= 54;
        this.iHash.update(pad4);
        this.oHash = hash3.create();
        for (let i = 0; i < pad4.length; i++)
          pad4[i] ^= 54 ^ 92;
        this.oHash.update(pad4);
        clean2(pad4);
      }
      update(buf) {
        aexists2(this);
        this.iHash.update(buf);
        return this;
      }
      digestInto(out) {
        aexists2(this);
        abytes4(out, this.outputLen);
        this.finished = true;
        this.iHash.digestInto(out);
        this.oHash.update(out);
        this.oHash.digestInto(out);
        this.destroy();
      }
      digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
      }
      _cloneInto(to) {
        to || (to = Object.create(Object.getPrototypeOf(this), {}));
        const { oHash, iHash, finished: finished2, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished2;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
      }
      clone() {
        return this._cloneInto();
      }
      destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
      }
    };
    hmac2 = (hash3, key, message) => new HMAC2(hash3, key).update(message).digest();
    hmac2.create = (hash3, key) => new HMAC2(hash3, key);
  }
});

// node_modules/ox/node_modules/@noble/hashes/esm/_md.js
function setBigUint642(view, byteOffset, value, isLE3) {
  if (typeof view.setBigUint64 === "function")
    return view.setBigUint64(byteOffset, value, isLE3);
  const _32n5 = BigInt(32);
  const _u32_max = BigInt(4294967295);
  const wh = Number(value >> _32n5 & _u32_max);
  const wl = Number(value & _u32_max);
  const h = isLE3 ? 4 : 0;
  const l2 = isLE3 ? 0 : 4;
  view.setUint32(byteOffset + h, wh, isLE3);
  view.setUint32(byteOffset + l2, wl, isLE3);
}
function Chi2(a, b, c) {
  return a & b ^ ~a & c;
}
function Maj2(a, b, c) {
  return a & b ^ a & c ^ b & c;
}
var HashMD2, SHA256_IV2;
var init_md2 = __esm({
  "node_modules/ox/node_modules/@noble/hashes/esm/_md.js"() {
    "use strict";
    init_utils7();
    HashMD2 = class extends Hash2 {
      constructor(blockLen, outputLen, padOffset, isLE3) {
        super();
        this.finished = false;
        this.length = 0;
        this.pos = 0;
        this.destroyed = false;
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE3;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView2(this.buffer);
      }
      update(data) {
        aexists2(this);
        data = toBytes3(data);
        abytes4(data);
        const { view, buffer: buffer2, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len; ) {
          const take = Math.min(blockLen - this.pos, len - pos);
          if (take === blockLen) {
            const dataView = createView2(data);
            for (; blockLen <= len - pos; pos += blockLen)
              this.process(dataView, pos);
            continue;
          }
          buffer2.set(data.subarray(pos, pos + take), this.pos);
          this.pos += take;
          pos += take;
          if (this.pos === blockLen) {
            this.process(view, 0);
            this.pos = 0;
          }
        }
        this.length += data.length;
        this.roundClean();
        return this;
      }
      digestInto(out) {
        aexists2(this);
        aoutput2(out, this);
        this.finished = true;
        const { buffer: buffer2, view, blockLen, isLE: isLE3 } = this;
        let { pos } = this;
        buffer2[pos++] = 128;
        clean2(this.buffer.subarray(pos));
        if (this.padOffset > blockLen - pos) {
          this.process(view, 0);
          pos = 0;
        }
        for (let i = pos; i < blockLen; i++)
          buffer2[i] = 0;
        setBigUint642(view, blockLen - 8, BigInt(this.length * 8), isLE3);
        this.process(view, 0);
        const oview = createView2(out);
        const len = this.outputLen;
        if (len % 4)
          throw new Error("_sha2: outputLen should be aligned to 32bit");
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
          throw new Error("_sha2: outputLen bigger than state");
        for (let i = 0; i < outLen; i++)
          oview.setUint32(4 * i, state[i], isLE3);
      }
      digest() {
        const { buffer: buffer2, outputLen } = this;
        this.digestInto(buffer2);
        const res = buffer2.slice(0, outputLen);
        this.destroy();
        return res;
      }
      _cloneInto(to) {
        to || (to = new this.constructor());
        to.set(...this.get());
        const { blockLen, buffer: buffer2, length, finished: finished2, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished2;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
          to.buffer.set(buffer2);
        return to;
      }
      clone() {
        return this._cloneInto();
      }
    };
    SHA256_IV2 = /* @__PURE__ */ Uint32Array.from([
      1779033703,
      3144134277,
      1013904242,
      2773480762,
      1359893119,
      2600822924,
      528734635,
      1541459225
    ]);
  }
});

// node_modules/ox/node_modules/@noble/hashes/esm/_u64.js
function fromBig2(n, le = false) {
  if (le)
    return { h: Number(n & U32_MASK642), l: Number(n >> _32n2 & U32_MASK642) };
  return { h: Number(n >> _32n2 & U32_MASK642) | 0, l: Number(n & U32_MASK642) | 0 };
}
function split2(lst, le = false) {
  const len = lst.length;
  let Ah = new Uint32Array(len);
  let Al = new Uint32Array(len);
  for (let i = 0; i < len; i++) {
    const { h, l: l2 } = fromBig2(lst[i], le);
    [Ah[i], Al[i]] = [h, l2];
  }
  return [Ah, Al];
}
var U32_MASK642, _32n2, rotlSH2, rotlSL2, rotlBH2, rotlBL2;
var init_u642 = __esm({
  "node_modules/ox/node_modules/@noble/hashes/esm/_u64.js"() {
    "use strict";
    U32_MASK642 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
    _32n2 = /* @__PURE__ */ BigInt(32);
    rotlSH2 = (h, l2, s3) => h << s3 | l2 >>> 32 - s3;
    rotlSL2 = (h, l2, s3) => l2 << s3 | h >>> 32 - s3;
    rotlBH2 = (h, l2, s3) => l2 << s3 - 32 | h >>> 64 - s3;
    rotlBL2 = (h, l2, s3) => h << s3 - 32 | l2 >>> 64 - s3;
  }
});

// node_modules/ox/node_modules/@noble/hashes/esm/sha3.js
function keccakP2(s3, rounds = 24) {
  const B = new Uint32Array(5 * 2);
  for (let round = 24 - rounds; round < 24; round++) {
    for (let x = 0; x < 10; x++)
      B[x] = s3[x] ^ s3[x + 10] ^ s3[x + 20] ^ s3[x + 30] ^ s3[x + 40];
    for (let x = 0; x < 10; x += 2) {
      const idx1 = (x + 8) % 10;
      const idx0 = (x + 2) % 10;
      const B0 = B[idx0];
      const B1 = B[idx0 + 1];
      const Th = rotlH2(B0, B1, 1) ^ B[idx1];
      const Tl = rotlL2(B0, B1, 1) ^ B[idx1 + 1];
      for (let y = 0; y < 50; y += 10) {
        s3[x + y] ^= Th;
        s3[x + y + 1] ^= Tl;
      }
    }
    let curH = s3[2];
    let curL = s3[3];
    for (let t = 0; t < 24; t++) {
      const shift = SHA3_ROTL2[t];
      const Th = rotlH2(curH, curL, shift);
      const Tl = rotlL2(curH, curL, shift);
      const PI = SHA3_PI2[t];
      curH = s3[PI];
      curL = s3[PI + 1];
      s3[PI] = Th;
      s3[PI + 1] = Tl;
    }
    for (let y = 0; y < 50; y += 10) {
      for (let x = 0; x < 10; x++)
        B[x] = s3[y + x];
      for (let x = 0; x < 10; x++)
        s3[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
    }
    s3[0] ^= SHA3_IOTA_H2[round];
    s3[1] ^= SHA3_IOTA_L2[round];
  }
  clean2(B);
}
var _0n8, _1n8, _2n5, _7n2, _256n2, _0x71n2, SHA3_PI2, SHA3_ROTL2, _SHA3_IOTA2, IOTAS2, SHA3_IOTA_H2, SHA3_IOTA_L2, rotlH2, rotlL2, Keccak2, gen2, keccak_2562;
var init_sha32 = __esm({
  "node_modules/ox/node_modules/@noble/hashes/esm/sha3.js"() {
    "use strict";
    init_u642();
    init_utils7();
    _0n8 = BigInt(0);
    _1n8 = BigInt(1);
    _2n5 = BigInt(2);
    _7n2 = BigInt(7);
    _256n2 = BigInt(256);
    _0x71n2 = BigInt(113);
    SHA3_PI2 = [];
    SHA3_ROTL2 = [];
    _SHA3_IOTA2 = [];
    for (let round = 0, R = _1n8, x = 1, y = 0; round < 24; round++) {
      [x, y] = [y, (2 * x + 3 * y) % 5];
      SHA3_PI2.push(2 * (5 * y + x));
      SHA3_ROTL2.push((round + 1) * (round + 2) / 2 % 64);
      let t = _0n8;
      for (let j = 0; j < 7; j++) {
        R = (R << _1n8 ^ (R >> _7n2) * _0x71n2) % _256n2;
        if (R & _2n5)
          t ^= _1n8 << (_1n8 << /* @__PURE__ */ BigInt(j)) - _1n8;
      }
      _SHA3_IOTA2.push(t);
    }
    IOTAS2 = split2(_SHA3_IOTA2, true);
    SHA3_IOTA_H2 = IOTAS2[0];
    SHA3_IOTA_L2 = IOTAS2[1];
    rotlH2 = (h, l2, s3) => s3 > 32 ? rotlBH2(h, l2, s3) : rotlSH2(h, l2, s3);
    rotlL2 = (h, l2, s3) => s3 > 32 ? rotlBL2(h, l2, s3) : rotlSL2(h, l2, s3);
    Keccak2 = class _Keccak extends Hash2 {
      // NOTE: we accept arguments in bytes instead of bits here.
      constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
        super();
        this.pos = 0;
        this.posOut = 0;
        this.finished = false;
        this.destroyed = false;
        this.enableXOF = false;
        this.blockLen = blockLen;
        this.suffix = suffix;
        this.outputLen = outputLen;
        this.enableXOF = enableXOF;
        this.rounds = rounds;
        anumber2(outputLen);
        if (!(0 < blockLen && blockLen < 200))
          throw new Error("only keccak-f1600 function is supported");
        this.state = new Uint8Array(200);
        this.state32 = u322(this.state);
      }
      clone() {
        return this._cloneInto();
      }
      keccak() {
        swap32IfBE2(this.state32);
        keccakP2(this.state32, this.rounds);
        swap32IfBE2(this.state32);
        this.posOut = 0;
        this.pos = 0;
      }
      update(data) {
        aexists2(this);
        data = toBytes3(data);
        abytes4(data);
        const { blockLen, state } = this;
        const len = data.length;
        for (let pos = 0; pos < len; ) {
          const take = Math.min(blockLen - this.pos, len - pos);
          for (let i = 0; i < take; i++)
            state[this.pos++] ^= data[pos++];
          if (this.pos === blockLen)
            this.keccak();
        }
        return this;
      }
      finish() {
        if (this.finished)
          return;
        this.finished = true;
        const { state, suffix, pos, blockLen } = this;
        state[pos] ^= suffix;
        if ((suffix & 128) !== 0 && pos === blockLen - 1)
          this.keccak();
        state[blockLen - 1] ^= 128;
        this.keccak();
      }
      writeInto(out) {
        aexists2(this, false);
        abytes4(out);
        this.finish();
        const bufferOut = this.state;
        const { blockLen } = this;
        for (let pos = 0, len = out.length; pos < len; ) {
          if (this.posOut >= blockLen)
            this.keccak();
          const take = Math.min(blockLen - this.posOut, len - pos);
          out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
          this.posOut += take;
          pos += take;
        }
        return out;
      }
      xofInto(out) {
        if (!this.enableXOF)
          throw new Error("XOF is not possible for this instance");
        return this.writeInto(out);
      }
      xof(bytes) {
        anumber2(bytes);
        return this.xofInto(new Uint8Array(bytes));
      }
      digestInto(out) {
        aoutput2(out, this);
        if (this.finished)
          throw new Error("digest() was already called");
        this.writeInto(out);
        this.destroy();
        return out;
      }
      digest() {
        return this.digestInto(new Uint8Array(this.outputLen));
      }
      destroy() {
        this.destroyed = true;
        clean2(this.state);
      }
      _cloneInto(to) {
        const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
        to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
        to.state32.set(this.state32);
        to.pos = this.pos;
        to.posOut = this.posOut;
        to.finished = this.finished;
        to.rounds = rounds;
        to.suffix = suffix;
        to.outputLen = outputLen;
        to.enableXOF = enableXOF;
        to.destroyed = this.destroyed;
        return to;
      }
    };
    gen2 = (suffix, blockLen, outputLen) => createHasher3(() => new Keccak2(blockLen, suffix, outputLen));
    keccak_2562 = /* @__PURE__ */ (() => gen2(1, 136, 256 / 8))();
  }
});

// node_modules/ox/node_modules/@noble/hashes/esm/sha2.js
var SHA256_K2, SHA256_W2, SHA2562, sha2564;
var init_sha22 = __esm({
  "node_modules/ox/node_modules/@noble/hashes/esm/sha2.js"() {
    "use strict";
    init_md2();
    init_utils7();
    SHA256_K2 = /* @__PURE__ */ Uint32Array.from([
      1116352408,
      1899447441,
      3049323471,
      3921009573,
      961987163,
      1508970993,
      2453635748,
      2870763221,
      3624381080,
      310598401,
      607225278,
      1426881987,
      1925078388,
      2162078206,
      2614888103,
      3248222580,
      3835390401,
      4022224774,
      264347078,
      604807628,
      770255983,
      1249150122,
      1555081692,
      1996064986,
      2554220882,
      2821834349,
      2952996808,
      3210313671,
      3336571891,
      3584528711,
      113926993,
      338241895,
      666307205,
      773529912,
      1294757372,
      1396182291,
      1695183700,
      1986661051,
      2177026350,
      2456956037,
      2730485921,
      2820302411,
      3259730800,
      3345764771,
      3516065817,
      3600352804,
      4094571909,
      275423344,
      430227734,
      506948616,
      659060556,
      883997877,
      958139571,
      1322822218,
      1537002063,
      1747873779,
      1955562222,
      2024104815,
      2227730452,
      2361852424,
      2428436474,
      2756734187,
      3204031479,
      3329325298
    ]);
    SHA256_W2 = /* @__PURE__ */ new Uint32Array(64);
    SHA2562 = class extends HashMD2 {
      constructor(outputLen = 32) {
        super(64, outputLen, 8, false);
        this.A = SHA256_IV2[0] | 0;
        this.B = SHA256_IV2[1] | 0;
        this.C = SHA256_IV2[2] | 0;
        this.D = SHA256_IV2[3] | 0;
        this.E = SHA256_IV2[4] | 0;
        this.F = SHA256_IV2[5] | 0;
        this.G = SHA256_IV2[6] | 0;
        this.H = SHA256_IV2[7] | 0;
      }
      get() {
        const { A, B, C, D: D2, E, F, G, H } = this;
        return [A, B, C, D2, E, F, G, H];
      }
      // prettier-ignore
      set(A, B, C, D2, E, F, G, H) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D2 | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G | 0;
        this.H = H | 0;
      }
      process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
          SHA256_W2[i] = view.getUint32(offset, false);
        for (let i = 16; i < 64; i++) {
          const W15 = SHA256_W2[i - 15];
          const W2 = SHA256_W2[i - 2];
          const s0 = rotr2(W15, 7) ^ rotr2(W15, 18) ^ W15 >>> 3;
          const s1 = rotr2(W2, 17) ^ rotr2(W2, 19) ^ W2 >>> 10;
          SHA256_W2[i] = s1 + SHA256_W2[i - 7] + s0 + SHA256_W2[i - 16] | 0;
        }
        let { A, B, C, D: D2, E, F, G, H } = this;
        for (let i = 0; i < 64; i++) {
          const sigma1 = rotr2(E, 6) ^ rotr2(E, 11) ^ rotr2(E, 25);
          const T1 = H + sigma1 + Chi2(E, F, G) + SHA256_K2[i] + SHA256_W2[i] | 0;
          const sigma0 = rotr2(A, 2) ^ rotr2(A, 13) ^ rotr2(A, 22);
          const T2 = sigma0 + Maj2(A, B, C) | 0;
          H = G;
          G = F;
          F = E;
          E = D2 + T1 | 0;
          D2 = C;
          C = B;
          B = A;
          A = T1 + T2 | 0;
        }
        A = A + this.A | 0;
        B = B + this.B | 0;
        C = C + this.C | 0;
        D2 = D2 + this.D | 0;
        E = E + this.E | 0;
        F = F + this.F | 0;
        G = G + this.G | 0;
        H = H + this.H | 0;
        this.set(A, B, C, D2, E, F, G, H);
      }
      roundClean() {
        clean2(SHA256_W2);
      }
      destroy() {
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean2(this.buffer);
      }
    };
    sha2564 = /* @__PURE__ */ createHasher3(() => new SHA2562());
  }
});

// node_modules/ox/_esm/core/Hash.js
function keccak2562(value, options = {}) {
  const { as = typeof value === "string" ? "Hex" : "Bytes" } = options;
  const bytes = keccak_2562(from(value));
  if (as === "Bytes")
    return bytes;
  return fromBytes(bytes);
}
var init_Hash = __esm({
  "node_modules/ox/_esm/core/Hash.js"() {
    "use strict";
    init_sha32();
    init_Bytes();
    init_Hex();
  }
});

// node_modules/ox/_esm/core/PublicKey.js
function assert3(publicKey, options = {}) {
  const { compressed } = options;
  const { prefix, x, y } = publicKey;
  if (compressed === false || typeof x === "bigint" && typeof y === "bigint") {
    if (prefix !== 4)
      throw new InvalidPrefixError({
        prefix,
        cause: new InvalidUncompressedPrefixError()
      });
    return;
  }
  if (compressed === true || typeof x === "bigint" && typeof y === "undefined") {
    if (prefix !== 3 && prefix !== 2)
      throw new InvalidPrefixError({
        prefix,
        cause: new InvalidCompressedPrefixError()
      });
    return;
  }
  throw new InvalidError({ publicKey });
}
function from3(value) {
  const publicKey = (() => {
    if (validate2(value))
      return fromHex2(value);
    if (validate(value))
      return fromBytes2(value);
    const { prefix, x, y } = value;
    if (typeof x === "bigint" && typeof y === "bigint")
      return { prefix: prefix ?? 4, x, y };
    return { prefix, x };
  })();
  assert3(publicKey);
  return publicKey;
}
function fromBytes2(publicKey) {
  return fromHex2(fromBytes(publicKey));
}
function fromHex2(publicKey) {
  if (publicKey.length !== 132 && publicKey.length !== 130 && publicKey.length !== 68)
    throw new InvalidSerializedSizeError({ publicKey });
  if (publicKey.length === 130) {
    const x2 = BigInt(slice3(publicKey, 0, 32));
    const y = BigInt(slice3(publicKey, 32, 64));
    return {
      prefix: 4,
      x: x2,
      y
    };
  }
  if (publicKey.length === 132) {
    const prefix2 = Number(slice3(publicKey, 0, 1));
    const x2 = BigInt(slice3(publicKey, 1, 33));
    const y = BigInt(slice3(publicKey, 33, 65));
    return {
      prefix: prefix2,
      x: x2,
      y
    };
  }
  const prefix = Number(slice3(publicKey, 0, 1));
  const x = BigInt(slice3(publicKey, 1, 33));
  return {
    prefix,
    x
  };
}
function toHex2(publicKey, options = {}) {
  assert3(publicKey);
  const { prefix, x, y } = publicKey;
  const { includePrefix = true } = options;
  const publicKey_ = concat2(
    includePrefix ? fromNumber(prefix, { size: 1 }) : "0x",
    fromNumber(x, { size: 32 }),
    // If the public key is not compressed, add the y coordinate.
    typeof y === "bigint" ? fromNumber(y, { size: 32 }) : "0x"
  );
  return publicKey_;
}
var InvalidError, InvalidPrefixError, InvalidCompressedPrefixError, InvalidUncompressedPrefixError, InvalidSerializedSizeError;
var init_PublicKey = __esm({
  "node_modules/ox/_esm/core/PublicKey.js"() {
    "use strict";
    init_Bytes();
    init_Errors();
    init_Hex();
    init_Json();
    InvalidError = class extends BaseError3 {
      constructor({ publicKey }) {
        super(`Value \`${stringify2(publicKey)}\` is not a valid public key.`, {
          metaMessages: [
            "Public key must contain:",
            "- an `x` and `prefix` value (compressed)",
            "- an `x`, `y`, and `prefix` value (uncompressed)"
          ]
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "PublicKey.InvalidError"
        });
      }
    };
    InvalidPrefixError = class extends BaseError3 {
      constructor({ prefix, cause }) {
        super(`Prefix "${prefix}" is invalid.`, {
          cause
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "PublicKey.InvalidPrefixError"
        });
      }
    };
    InvalidCompressedPrefixError = class extends BaseError3 {
      constructor() {
        super("Prefix must be 2 or 3 for compressed public keys.");
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "PublicKey.InvalidCompressedPrefixError"
        });
      }
    };
    InvalidUncompressedPrefixError = class extends BaseError3 {
      constructor() {
        super("Prefix must be 4 for uncompressed public keys.");
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "PublicKey.InvalidUncompressedPrefixError"
        });
      }
    };
    InvalidSerializedSizeError = class extends BaseError3 {
      constructor({ publicKey }) {
        super(`Value \`${publicKey}\` is an invalid public key size.`, {
          metaMessages: [
            "Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",
            `Received ${size3(from2(publicKey))} bytes.`
          ]
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "PublicKey.InvalidSerializedSizeError"
        });
      }
    };
  }
});

// node_modules/ox/_esm/core/Address.js
function assert4(value, options = {}) {
  const { strict = true } = options;
  if (!addressRegex2.test(value))
    throw new InvalidAddressError2({
      address: value,
      cause: new InvalidInputError()
    });
  if (strict) {
    if (value.toLowerCase() === value)
      return;
    if (checksum2(value) !== value)
      throw new InvalidAddressError2({
        address: value,
        cause: new InvalidChecksumError()
      });
  }
}
function checksum2(address2) {
  if (checksum.has(address2))
    return checksum.get(address2);
  assert4(address2, { strict: false });
  const hexAddress = address2.substring(2).toLowerCase();
  const hash3 = keccak2562(fromString(hexAddress), { as: "Bytes" });
  const characters = hexAddress.split("");
  for (let i = 0; i < 40; i += 2) {
    if (hash3[i >> 1] >> 4 >= 8 && characters[i]) {
      characters[i] = characters[i].toUpperCase();
    }
    if ((hash3[i >> 1] & 15) >= 8 && characters[i + 1]) {
      characters[i + 1] = characters[i + 1].toUpperCase();
    }
  }
  const result = `0x${characters.join("")}`;
  checksum.set(address2, result);
  return result;
}
function from4(address2, options = {}) {
  const { checksum: checksumVal = false } = options;
  assert4(address2);
  if (checksumVal)
    return checksum2(address2);
  return address2;
}
function fromPublicKey(publicKey, options = {}) {
  const address2 = keccak2562(`0x${toHex2(publicKey).slice(4)}`).substring(26);
  return from4(`0x${address2}`, options);
}
function validate3(address2, options = {}) {
  const { strict = true } = options ?? {};
  try {
    assert4(address2, { strict });
    return true;
  } catch {
    return false;
  }
}
var addressRegex2, InvalidAddressError2, InvalidInputError, InvalidChecksumError;
var init_Address = __esm({
  "node_modules/ox/_esm/core/Address.js"() {
    "use strict";
    init_Bytes();
    init_Caches();
    init_Errors();
    init_Hash();
    init_PublicKey();
    addressRegex2 = /^0x[a-fA-F0-9]{40}$/;
    InvalidAddressError2 = class extends BaseError3 {
      constructor({ address: address2, cause }) {
        super(`Address "${address2}" is invalid.`, {
          cause
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Address.InvalidAddressError"
        });
      }
    };
    InvalidInputError = class extends BaseError3 {
      constructor() {
        super("Address is not a 20 byte (40 hexadecimal character) value.");
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Address.InvalidInputError"
        });
      }
    };
    InvalidChecksumError = class extends BaseError3 {
      constructor() {
        super("Address does not match its checksum counterpart.");
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Address.InvalidChecksumError"
        });
      }
    };
  }
});

// node_modules/ox/_esm/core/Solidity.js
var arrayRegex, bytesRegex3, integerRegex3, maxInt82, maxInt162, maxInt242, maxInt322, maxInt402, maxInt482, maxInt562, maxInt642, maxInt722, maxInt802, maxInt882, maxInt962, maxInt1042, maxInt1122, maxInt1202, maxInt1282, maxInt1362, maxInt1442, maxInt1522, maxInt1602, maxInt1682, maxInt1762, maxInt1842, maxInt1922, maxInt2002, maxInt2082, maxInt2162, maxInt2242, maxInt2322, maxInt2402, maxInt2482, maxInt2562, minInt82, minInt162, minInt242, minInt322, minInt402, minInt482, minInt562, minInt642, minInt722, minInt802, minInt882, minInt962, minInt1042, minInt1122, minInt1202, minInt1282, minInt1362, minInt1442, minInt1522, minInt1602, minInt1682, minInt1762, minInt1842, minInt1922, minInt2002, minInt2082, minInt2162, minInt2242, minInt2322, minInt2402, minInt2482, minInt2562, maxUint82, maxUint162, maxUint242, maxUint322, maxUint402, maxUint482, maxUint562, maxUint642, maxUint722, maxUint802, maxUint882, maxUint962, maxUint1042, maxUint1122, maxUint1202, maxUint1282, maxUint1362, maxUint1442, maxUint1522, maxUint1602, maxUint1682, maxUint1762, maxUint1842, maxUint1922, maxUint2002, maxUint2082, maxUint2162, maxUint2242, maxUint2322, maxUint2402, maxUint2482, maxUint2562;
var init_Solidity = __esm({
  "node_modules/ox/_esm/core/Solidity.js"() {
    "use strict";
    arrayRegex = /^(.*)\[([0-9]*)\]$/;
    bytesRegex3 = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;
    integerRegex3 = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;
    maxInt82 = 2n ** (8n - 1n) - 1n;
    maxInt162 = 2n ** (16n - 1n) - 1n;
    maxInt242 = 2n ** (24n - 1n) - 1n;
    maxInt322 = 2n ** (32n - 1n) - 1n;
    maxInt402 = 2n ** (40n - 1n) - 1n;
    maxInt482 = 2n ** (48n - 1n) - 1n;
    maxInt562 = 2n ** (56n - 1n) - 1n;
    maxInt642 = 2n ** (64n - 1n) - 1n;
    maxInt722 = 2n ** (72n - 1n) - 1n;
    maxInt802 = 2n ** (80n - 1n) - 1n;
    maxInt882 = 2n ** (88n - 1n) - 1n;
    maxInt962 = 2n ** (96n - 1n) - 1n;
    maxInt1042 = 2n ** (104n - 1n) - 1n;
    maxInt1122 = 2n ** (112n - 1n) - 1n;
    maxInt1202 = 2n ** (120n - 1n) - 1n;
    maxInt1282 = 2n ** (128n - 1n) - 1n;
    maxInt1362 = 2n ** (136n - 1n) - 1n;
    maxInt1442 = 2n ** (144n - 1n) - 1n;
    maxInt1522 = 2n ** (152n - 1n) - 1n;
    maxInt1602 = 2n ** (160n - 1n) - 1n;
    maxInt1682 = 2n ** (168n - 1n) - 1n;
    maxInt1762 = 2n ** (176n - 1n) - 1n;
    maxInt1842 = 2n ** (184n - 1n) - 1n;
    maxInt1922 = 2n ** (192n - 1n) - 1n;
    maxInt2002 = 2n ** (200n - 1n) - 1n;
    maxInt2082 = 2n ** (208n - 1n) - 1n;
    maxInt2162 = 2n ** (216n - 1n) - 1n;
    maxInt2242 = 2n ** (224n - 1n) - 1n;
    maxInt2322 = 2n ** (232n - 1n) - 1n;
    maxInt2402 = 2n ** (240n - 1n) - 1n;
    maxInt2482 = 2n ** (248n - 1n) - 1n;
    maxInt2562 = 2n ** (256n - 1n) - 1n;
    minInt82 = -(2n ** (8n - 1n));
    minInt162 = -(2n ** (16n - 1n));
    minInt242 = -(2n ** (24n - 1n));
    minInt322 = -(2n ** (32n - 1n));
    minInt402 = -(2n ** (40n - 1n));
    minInt482 = -(2n ** (48n - 1n));
    minInt562 = -(2n ** (56n - 1n));
    minInt642 = -(2n ** (64n - 1n));
    minInt722 = -(2n ** (72n - 1n));
    minInt802 = -(2n ** (80n - 1n));
    minInt882 = -(2n ** (88n - 1n));
    minInt962 = -(2n ** (96n - 1n));
    minInt1042 = -(2n ** (104n - 1n));
    minInt1122 = -(2n ** (112n - 1n));
    minInt1202 = -(2n ** (120n - 1n));
    minInt1282 = -(2n ** (128n - 1n));
    minInt1362 = -(2n ** (136n - 1n));
    minInt1442 = -(2n ** (144n - 1n));
    minInt1522 = -(2n ** (152n - 1n));
    minInt1602 = -(2n ** (160n - 1n));
    minInt1682 = -(2n ** (168n - 1n));
    minInt1762 = -(2n ** (176n - 1n));
    minInt1842 = -(2n ** (184n - 1n));
    minInt1922 = -(2n ** (192n - 1n));
    minInt2002 = -(2n ** (200n - 1n));
    minInt2082 = -(2n ** (208n - 1n));
    minInt2162 = -(2n ** (216n - 1n));
    minInt2242 = -(2n ** (224n - 1n));
    minInt2322 = -(2n ** (232n - 1n));
    minInt2402 = -(2n ** (240n - 1n));
    minInt2482 = -(2n ** (248n - 1n));
    minInt2562 = -(2n ** (256n - 1n));
    maxUint82 = 2n ** 8n - 1n;
    maxUint162 = 2n ** 16n - 1n;
    maxUint242 = 2n ** 24n - 1n;
    maxUint322 = 2n ** 32n - 1n;
    maxUint402 = 2n ** 40n - 1n;
    maxUint482 = 2n ** 48n - 1n;
    maxUint562 = 2n ** 56n - 1n;
    maxUint642 = 2n ** 64n - 1n;
    maxUint722 = 2n ** 72n - 1n;
    maxUint802 = 2n ** 80n - 1n;
    maxUint882 = 2n ** 88n - 1n;
    maxUint962 = 2n ** 96n - 1n;
    maxUint1042 = 2n ** 104n - 1n;
    maxUint1122 = 2n ** 112n - 1n;
    maxUint1202 = 2n ** 120n - 1n;
    maxUint1282 = 2n ** 128n - 1n;
    maxUint1362 = 2n ** 136n - 1n;
    maxUint1442 = 2n ** 144n - 1n;
    maxUint1522 = 2n ** 152n - 1n;
    maxUint1602 = 2n ** 160n - 1n;
    maxUint1682 = 2n ** 168n - 1n;
    maxUint1762 = 2n ** 176n - 1n;
    maxUint1842 = 2n ** 184n - 1n;
    maxUint1922 = 2n ** 192n - 1n;
    maxUint2002 = 2n ** 200n - 1n;
    maxUint2082 = 2n ** 208n - 1n;
    maxUint2162 = 2n ** 216n - 1n;
    maxUint2242 = 2n ** 224n - 1n;
    maxUint2322 = 2n ** 232n - 1n;
    maxUint2402 = 2n ** 240n - 1n;
    maxUint2482 = 2n ** 248n - 1n;
    maxUint2562 = 2n ** 256n - 1n;
  }
});

// node_modules/ox/_esm/core/internal/abiParameters.js
function decodeParameter2(cursor, param, options) {
  const { checksumAddress: checksumAddress2, staticPosition } = options;
  const arrayComponents = getArrayComponents2(param.type);
  if (arrayComponents) {
    const [length, type] = arrayComponents;
    return decodeArray2(cursor, { ...param, type }, { checksumAddress: checksumAddress2, length, staticPosition });
  }
  if (param.type === "tuple")
    return decodeTuple2(cursor, param, {
      checksumAddress: checksumAddress2,
      staticPosition
    });
  if (param.type === "address")
    return decodeAddress2(cursor, { checksum: checksumAddress2 });
  if (param.type === "bool")
    return decodeBool2(cursor);
  if (param.type.startsWith("bytes"))
    return decodeBytes2(cursor, param, { staticPosition });
  if (param.type.startsWith("uint") || param.type.startsWith("int"))
    return decodeNumber2(cursor, param);
  if (param.type === "string")
    return decodeString2(cursor, { staticPosition });
  throw new InvalidTypeError(param.type);
}
function decodeAddress2(cursor, options = {}) {
  const { checksum: checksum5 = false } = options;
  const value = cursor.readBytes(32);
  const wrap3 = (address2) => checksum5 ? checksum2(address2) : address2;
  return [wrap3(fromBytes(slice2(value, -20))), 32];
}
function decodeArray2(cursor, param, options) {
  const { checksumAddress: checksumAddress2, length, staticPosition } = options;
  if (!length) {
    const offset = toNumber2(cursor.readBytes(sizeOfOffset2));
    const start = staticPosition + offset;
    const startOfData = start + sizeOfLength2;
    cursor.setPosition(start);
    const length2 = toNumber2(cursor.readBytes(sizeOfLength2));
    const dynamicChild = hasDynamicChild2(param);
    let consumed2 = 0;
    const value2 = [];
    for (let i = 0; i < length2; ++i) {
      cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed2));
      const [data, consumed_] = decodeParameter2(cursor, param, {
        checksumAddress: checksumAddress2,
        staticPosition: startOfData
      });
      consumed2 += consumed_;
      value2.push(data);
    }
    cursor.setPosition(staticPosition + 32);
    return [value2, 32];
  }
  if (hasDynamicChild2(param)) {
    const offset = toNumber2(cursor.readBytes(sizeOfOffset2));
    const start = staticPosition + offset;
    const value2 = [];
    for (let i = 0; i < length; ++i) {
      cursor.setPosition(start + i * 32);
      const [data] = decodeParameter2(cursor, param, {
        checksumAddress: checksumAddress2,
        staticPosition: start
      });
      value2.push(data);
    }
    cursor.setPosition(staticPosition + 32);
    return [value2, 32];
  }
  let consumed = 0;
  const value = [];
  for (let i = 0; i < length; ++i) {
    const [data, consumed_] = decodeParameter2(cursor, param, {
      checksumAddress: checksumAddress2,
      staticPosition: staticPosition + consumed
    });
    consumed += consumed_;
    value.push(data);
  }
  return [value, consumed];
}
function decodeBool2(cursor) {
  return [toBoolean(cursor.readBytes(32), { size: 32 }), 32];
}
function decodeBytes2(cursor, param, { staticPosition }) {
  const [_, size5] = param.type.split("bytes");
  if (!size5) {
    const offset = toNumber2(cursor.readBytes(32));
    cursor.setPosition(staticPosition + offset);
    const length = toNumber2(cursor.readBytes(32));
    if (length === 0) {
      cursor.setPosition(staticPosition + 32);
      return ["0x", 32];
    }
    const data = cursor.readBytes(length);
    cursor.setPosition(staticPosition + 32);
    return [fromBytes(data), 32];
  }
  const value = fromBytes(cursor.readBytes(Number.parseInt(size5, 10), 32));
  return [value, 32];
}
function decodeNumber2(cursor, param) {
  const signed = param.type.startsWith("int");
  const size5 = Number.parseInt(param.type.split("int")[1] || "256", 10);
  const value = cursor.readBytes(32);
  return [
    size5 > 48 ? toBigInt2(value, { signed }) : toNumber2(value, { signed }),
    32
  ];
}
function decodeTuple2(cursor, param, options) {
  const { checksumAddress: checksumAddress2, staticPosition } = options;
  const hasUnnamedChild = param.components.length === 0 || param.components.some(({ name }) => !name);
  const value = hasUnnamedChild ? [] : {};
  let consumed = 0;
  if (hasDynamicChild2(param)) {
    const offset = toNumber2(cursor.readBytes(sizeOfOffset2));
    const start = staticPosition + offset;
    for (let i = 0; i < param.components.length; ++i) {
      const component = param.components[i];
      cursor.setPosition(start + consumed);
      const [data, consumed_] = decodeParameter2(cursor, component, {
        checksumAddress: checksumAddress2,
        staticPosition: start
      });
      consumed += consumed_;
      value[hasUnnamedChild ? i : component?.name] = data;
    }
    cursor.setPosition(staticPosition + 32);
    return [value, 32];
  }
  for (let i = 0; i < param.components.length; ++i) {
    const component = param.components[i];
    const [data, consumed_] = decodeParameter2(cursor, component, {
      checksumAddress: checksumAddress2,
      staticPosition
    });
    value[hasUnnamedChild ? i : component?.name] = data;
    consumed += consumed_;
  }
  return [value, consumed];
}
function decodeString2(cursor, { staticPosition }) {
  const offset = toNumber2(cursor.readBytes(32));
  const start = staticPosition + offset;
  cursor.setPosition(start);
  const length = toNumber2(cursor.readBytes(32));
  if (length === 0) {
    cursor.setPosition(staticPosition + 32);
    return ["", 32];
  }
  const data = cursor.readBytes(length, 32);
  const value = toString(trimLeft(data));
  cursor.setPosition(staticPosition + 32);
  return [value, 32];
}
function prepareParameters({ checksumAddress: checksumAddress2, parameters, values }) {
  const preparedParameters = [];
  for (let i = 0; i < parameters.length; i++) {
    preparedParameters.push(prepareParameter({
      checksumAddress: checksumAddress2,
      parameter: parameters[i],
      value: values[i]
    }));
  }
  return preparedParameters;
}
function prepareParameter({ checksumAddress: checksumAddress2 = false, parameter: parameter_, value }) {
  const parameter = parameter_;
  const arrayComponents = getArrayComponents2(parameter.type);
  if (arrayComponents) {
    const [length, type] = arrayComponents;
    return encodeArray2(value, {
      checksumAddress: checksumAddress2,
      length,
      parameter: {
        ...parameter,
        type
      }
    });
  }
  if (parameter.type === "tuple") {
    return encodeTuple2(value, {
      checksumAddress: checksumAddress2,
      parameter
    });
  }
  if (parameter.type === "address") {
    return encodeAddress2(value, {
      checksum: checksumAddress2
    });
  }
  if (parameter.type === "bool") {
    return encodeBoolean(value);
  }
  if (parameter.type.startsWith("uint") || parameter.type.startsWith("int")) {
    const signed = parameter.type.startsWith("int");
    const [, , size5 = "256"] = integerRegex3.exec(parameter.type) ?? [];
    return encodeNumber2(value, {
      signed,
      size: Number(size5)
    });
  }
  if (parameter.type.startsWith("bytes")) {
    return encodeBytes2(value, { type: parameter.type });
  }
  if (parameter.type === "string") {
    return encodeString2(value);
  }
  throw new InvalidTypeError(parameter.type);
}
function encode(preparedParameters) {
  let staticSize = 0;
  for (let i = 0; i < preparedParameters.length; i++) {
    const { dynamic, encoded } = preparedParameters[i];
    if (dynamic)
      staticSize += 32;
    else
      staticSize += size3(encoded);
  }
  const staticParameters = [];
  const dynamicParameters = [];
  let dynamicSize = 0;
  for (let i = 0; i < preparedParameters.length; i++) {
    const { dynamic, encoded } = preparedParameters[i];
    if (dynamic) {
      staticParameters.push(fromNumber(staticSize + dynamicSize, { size: 32 }));
      dynamicParameters.push(encoded);
      dynamicSize += size3(encoded);
    } else {
      staticParameters.push(encoded);
    }
  }
  return concat2(...staticParameters, ...dynamicParameters);
}
function encodeAddress2(value, options) {
  const { checksum: checksum5 = false } = options;
  assert4(value, { strict: checksum5 });
  return {
    dynamic: false,
    encoded: padLeft(value.toLowerCase())
  };
}
function encodeArray2(value, options) {
  const { checksumAddress: checksumAddress2, length, parameter } = options;
  const dynamic = length === null;
  if (!Array.isArray(value))
    throw new InvalidArrayError2(value);
  if (!dynamic && value.length !== length)
    throw new ArrayLengthMismatchError({
      expectedLength: length,
      givenLength: value.length,
      type: `${parameter.type}[${length}]`
    });
  let dynamicChild = false;
  const preparedParameters = [];
  for (let i = 0; i < value.length; i++) {
    const preparedParam = prepareParameter({
      checksumAddress: checksumAddress2,
      parameter,
      value: value[i]
    });
    if (preparedParam.dynamic)
      dynamicChild = true;
    preparedParameters.push(preparedParam);
  }
  if (dynamic || dynamicChild) {
    const data = encode(preparedParameters);
    if (dynamic) {
      const length2 = fromNumber(preparedParameters.length, { size: 32 });
      return {
        dynamic: true,
        encoded: preparedParameters.length > 0 ? concat2(length2, data) : length2
      };
    }
    if (dynamicChild)
      return { dynamic: true, encoded: data };
  }
  return {
    dynamic: false,
    encoded: concat2(...preparedParameters.map(({ encoded }) => encoded))
  };
}
function encodeBytes2(value, { type }) {
  const [, parametersize] = type.split("bytes");
  const bytesSize = size3(value);
  if (!parametersize) {
    let value_ = value;
    if (bytesSize % 32 !== 0)
      value_ = padRight(value_, Math.ceil((value.length - 2) / 2 / 32) * 32);
    return {
      dynamic: true,
      encoded: concat2(padLeft(fromNumber(bytesSize, { size: 32 })), value_)
    };
  }
  if (bytesSize !== Number.parseInt(parametersize, 10))
    throw new BytesSizeMismatchError2({
      expectedSize: Number.parseInt(parametersize, 10),
      value
    });
  return { dynamic: false, encoded: padRight(value) };
}
function encodeBoolean(value) {
  if (typeof value !== "boolean")
    throw new BaseError3(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`);
  return { dynamic: false, encoded: padLeft(fromBoolean(value)) };
}
function encodeNumber2(value, { signed, size: size5 }) {
  if (typeof size5 === "number") {
    const max = 2n ** (BigInt(size5) - (signed ? 1n : 0n)) - 1n;
    const min = signed ? -max - 1n : 0n;
    if (value > max || value < min)
      throw new IntegerOutOfRangeError2({
        max: max.toString(),
        min: min.toString(),
        signed,
        size: size5 / 8,
        value: value.toString()
      });
  }
  return {
    dynamic: false,
    encoded: fromNumber(value, {
      size: 32,
      signed
    })
  };
}
function encodeString2(value) {
  const hexValue = fromString2(value);
  const partsLength = Math.ceil(size3(hexValue) / 32);
  const parts = [];
  for (let i = 0; i < partsLength; i++) {
    parts.push(padRight(slice3(hexValue, i * 32, (i + 1) * 32)));
  }
  return {
    dynamic: true,
    encoded: concat2(padRight(fromNumber(size3(hexValue), { size: 32 })), ...parts)
  };
}
function encodeTuple2(value, options) {
  const { checksumAddress: checksumAddress2, parameter } = options;
  let dynamic = false;
  const preparedParameters = [];
  for (let i = 0; i < parameter.components.length; i++) {
    const param_ = parameter.components[i];
    const index2 = Array.isArray(value) ? i : param_.name;
    const preparedParam = prepareParameter({
      checksumAddress: checksumAddress2,
      parameter: param_,
      value: value[index2]
    });
    preparedParameters.push(preparedParam);
    if (preparedParam.dynamic)
      dynamic = true;
  }
  return {
    dynamic,
    encoded: dynamic ? encode(preparedParameters) : concat2(...preparedParameters.map(({ encoded }) => encoded))
  };
}
function getArrayComponents2(type) {
  const matches = type.match(/^(.*)\[(\d+)?\]$/);
  return matches ? (
    // Return `null` if the array is dynamic.
    [matches[2] ? Number(matches[2]) : null, matches[1]]
  ) : void 0;
}
function hasDynamicChild2(param) {
  const { type } = param;
  if (type === "string")
    return true;
  if (type === "bytes")
    return true;
  if (type.endsWith("[]"))
    return true;
  if (type === "tuple")
    return param.components?.some(hasDynamicChild2);
  const arrayComponents = getArrayComponents2(param.type);
  if (arrayComponents && hasDynamicChild2({
    ...param,
    type: arrayComponents[1]
  }))
    return true;
  return false;
}
var sizeOfLength2, sizeOfOffset2;
var init_abiParameters = __esm({
  "node_modules/ox/_esm/core/internal/abiParameters.js"() {
    "use strict";
    init_AbiParameters();
    init_Address();
    init_Bytes();
    init_Errors();
    init_Hex();
    init_Solidity();
    sizeOfLength2 = 32;
    sizeOfOffset2 = 32;
  }
});

// node_modules/ox/_esm/core/internal/cursor.js
function create(bytes, { recursiveReadLimit = 8192 } = {}) {
  const cursor = Object.create(staticCursor2);
  cursor.bytes = bytes;
  cursor.dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  cursor.positionReadCount = /* @__PURE__ */ new Map();
  cursor.recursiveReadLimit = recursiveReadLimit;
  return cursor;
}
var staticCursor2, NegativeOffsetError2, PositionOutOfBoundsError2, RecursiveReadLimitExceededError2;
var init_cursor3 = __esm({
  "node_modules/ox/_esm/core/internal/cursor.js"() {
    "use strict";
    init_Errors();
    staticCursor2 = {
      bytes: new Uint8Array(),
      dataView: new DataView(new ArrayBuffer(0)),
      position: 0,
      positionReadCount: /* @__PURE__ */ new Map(),
      recursiveReadCount: 0,
      recursiveReadLimit: Number.POSITIVE_INFINITY,
      assertReadLimit() {
        if (this.recursiveReadCount >= this.recursiveReadLimit)
          throw new RecursiveReadLimitExceededError2({
            count: this.recursiveReadCount + 1,
            limit: this.recursiveReadLimit
          });
      },
      assertPosition(position) {
        if (position < 0 || position > this.bytes.length - 1)
          throw new PositionOutOfBoundsError2({
            length: this.bytes.length,
            position
          });
      },
      decrementPosition(offset) {
        if (offset < 0)
          throw new NegativeOffsetError2({ offset });
        const position = this.position - offset;
        this.assertPosition(position);
        this.position = position;
      },
      getReadCount(position) {
        return this.positionReadCount.get(position || this.position) || 0;
      },
      incrementPosition(offset) {
        if (offset < 0)
          throw new NegativeOffsetError2({ offset });
        const position = this.position + offset;
        this.assertPosition(position);
        this.position = position;
      },
      inspectByte(position_) {
        const position = position_ ?? this.position;
        this.assertPosition(position);
        return this.bytes[position];
      },
      inspectBytes(length, position_) {
        const position = position_ ?? this.position;
        this.assertPosition(position + length - 1);
        return this.bytes.subarray(position, position + length);
      },
      inspectUint8(position_) {
        const position = position_ ?? this.position;
        this.assertPosition(position);
        return this.bytes[position];
      },
      inspectUint16(position_) {
        const position = position_ ?? this.position;
        this.assertPosition(position + 1);
        return this.dataView.getUint16(position);
      },
      inspectUint24(position_) {
        const position = position_ ?? this.position;
        this.assertPosition(position + 2);
        return (this.dataView.getUint16(position) << 8) + this.dataView.getUint8(position + 2);
      },
      inspectUint32(position_) {
        const position = position_ ?? this.position;
        this.assertPosition(position + 3);
        return this.dataView.getUint32(position);
      },
      pushByte(byte) {
        this.assertPosition(this.position);
        this.bytes[this.position] = byte;
        this.position++;
      },
      pushBytes(bytes) {
        this.assertPosition(this.position + bytes.length - 1);
        this.bytes.set(bytes, this.position);
        this.position += bytes.length;
      },
      pushUint8(value) {
        this.assertPosition(this.position);
        this.bytes[this.position] = value;
        this.position++;
      },
      pushUint16(value) {
        this.assertPosition(this.position + 1);
        this.dataView.setUint16(this.position, value);
        this.position += 2;
      },
      pushUint24(value) {
        this.assertPosition(this.position + 2);
        this.dataView.setUint16(this.position, value >> 8);
        this.dataView.setUint8(this.position + 2, value & ~4294967040);
        this.position += 3;
      },
      pushUint32(value) {
        this.assertPosition(this.position + 3);
        this.dataView.setUint32(this.position, value);
        this.position += 4;
      },
      readByte() {
        this.assertReadLimit();
        this._touch();
        const value = this.inspectByte();
        this.position++;
        return value;
      },
      readBytes(length, size5) {
        this.assertReadLimit();
        this._touch();
        const value = this.inspectBytes(length);
        this.position += size5 ?? length;
        return value;
      },
      readUint8() {
        this.assertReadLimit();
        this._touch();
        const value = this.inspectUint8();
        this.position += 1;
        return value;
      },
      readUint16() {
        this.assertReadLimit();
        this._touch();
        const value = this.inspectUint16();
        this.position += 2;
        return value;
      },
      readUint24() {
        this.assertReadLimit();
        this._touch();
        const value = this.inspectUint24();
        this.position += 3;
        return value;
      },
      readUint32() {
        this.assertReadLimit();
        this._touch();
        const value = this.inspectUint32();
        this.position += 4;
        return value;
      },
      get remaining() {
        return this.bytes.length - this.position;
      },
      setPosition(position) {
        const oldPosition = this.position;
        this.assertPosition(position);
        this.position = position;
        return () => this.position = oldPosition;
      },
      _touch() {
        if (this.recursiveReadLimit === Number.POSITIVE_INFINITY)
          return;
        const count = this.getReadCount();
        this.positionReadCount.set(this.position, count + 1);
        if (count > 0)
          this.recursiveReadCount++;
      }
    };
    NegativeOffsetError2 = class extends BaseError3 {
      constructor({ offset }) {
        super(`Offset \`${offset}\` cannot be negative.`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Cursor.NegativeOffsetError"
        });
      }
    };
    PositionOutOfBoundsError2 = class extends BaseError3 {
      constructor({ length, position }) {
        super(`Position \`${position}\` is out of bounds (\`0 < position < ${length}\`).`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Cursor.PositionOutOfBoundsError"
        });
      }
    };
    RecursiveReadLimitExceededError2 = class extends BaseError3 {
      constructor({ count, limit }) {
        super(`Recursive read limit of \`${limit}\` exceeded (recursive read count: \`${count}\`).`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Cursor.RecursiveReadLimitExceededError"
        });
      }
    };
  }
});

// node_modules/ox/_esm/core/AbiParameters.js
function decode(parameters, data, options = {}) {
  const { as = "Array", checksumAddress: checksumAddress2 = false } = options;
  const bytes = typeof data === "string" ? fromHex(data) : data;
  const cursor = create(bytes);
  if (size2(bytes) === 0 && parameters.length > 0)
    throw new ZeroDataError();
  if (size2(bytes) && size2(bytes) < 32)
    throw new DataSizeTooSmallError({
      data: typeof data === "string" ? data : fromBytes(data),
      parameters,
      size: size2(bytes)
    });
  let consumed = 0;
  const values = as === "Array" ? [] : {};
  for (let i = 0; i < parameters.length; ++i) {
    const param = parameters[i];
    cursor.setPosition(consumed);
    const [data2, consumed_] = decodeParameter2(cursor, param, {
      checksumAddress: checksumAddress2,
      staticPosition: 0
    });
    consumed += consumed_;
    if (as === "Array")
      values.push(data2);
    else
      values[param.name ?? i] = data2;
  }
  return values;
}
function encode2(parameters, values, options) {
  const { checksumAddress: checksumAddress2 = false } = options ?? {};
  if (parameters.length !== values.length)
    throw new LengthMismatchError({
      expectedLength: parameters.length,
      givenLength: values.length
    });
  const preparedParameters = prepareParameters({
    checksumAddress: checksumAddress2,
    parameters,
    values
  });
  const data = encode(preparedParameters);
  if (data.length === 0)
    return "0x";
  return data;
}
function encodePacked(types, values) {
  if (types.length !== values.length)
    throw new LengthMismatchError({
      expectedLength: types.length,
      givenLength: values.length
    });
  const data = [];
  for (let i = 0; i < types.length; i++) {
    const type = types[i];
    const value = values[i];
    data.push(encodePacked.encode(type, value));
  }
  return concat2(...data);
}
function from5(parameters) {
  if (Array.isArray(parameters) && typeof parameters[0] === "string")
    return parseAbiParameters(parameters);
  if (typeof parameters === "string")
    return parseAbiParameters(parameters);
  return parameters;
}
var DataSizeTooSmallError, ZeroDataError, ArrayLengthMismatchError, BytesSizeMismatchError2, LengthMismatchError, InvalidArrayError2, InvalidTypeError;
var init_AbiParameters = __esm({
  "node_modules/ox/_esm/core/AbiParameters.js"() {
    "use strict";
    init_exports();
    init_Address();
    init_Bytes();
    init_Errors();
    init_Hex();
    init_abiParameters();
    init_cursor3();
    init_Solidity();
    (function(encodePacked2) {
      function encode4(type, value, isArray = false) {
        if (type === "address") {
          const address2 = value;
          assert4(address2);
          return padLeft(address2.toLowerCase(), isArray ? 32 : 0);
        }
        if (type === "string")
          return fromString2(value);
        if (type === "bytes")
          return value;
        if (type === "bool")
          return padLeft(fromBoolean(value), isArray ? 32 : 1);
        const intMatch = type.match(integerRegex3);
        if (intMatch) {
          const [_type, baseType, bits = "256"] = intMatch;
          const size5 = Number.parseInt(bits, 10) / 8;
          return fromNumber(value, {
            size: isArray ? 32 : size5,
            signed: baseType === "int"
          });
        }
        const bytesMatch = type.match(bytesRegex3);
        if (bytesMatch) {
          const [_type, size5] = bytesMatch;
          if (Number.parseInt(size5, 10) !== (value.length - 2) / 2)
            throw new BytesSizeMismatchError2({
              expectedSize: Number.parseInt(size5, 10),
              value
            });
          return padRight(value, isArray ? 32 : 0);
        }
        const arrayMatch = type.match(arrayRegex);
        if (arrayMatch && Array.isArray(value)) {
          const [_type, childType] = arrayMatch;
          const data = [];
          for (let i = 0; i < value.length; i++) {
            data.push(encode4(childType, value[i], true));
          }
          if (data.length === 0)
            return "0x";
          return concat2(...data);
        }
        throw new InvalidTypeError(type);
      }
      encodePacked2.encode = encode4;
    })(encodePacked || (encodePacked = {}));
    DataSizeTooSmallError = class extends BaseError3 {
      constructor({ data, parameters, size: size5 }) {
        super(`Data size of ${size5} bytes is too small for given parameters.`, {
          metaMessages: [
            `Params: (${formatAbiParameters(parameters)})`,
            `Data:   ${data} (${size5} bytes)`
          ]
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "AbiParameters.DataSizeTooSmallError"
        });
      }
    };
    ZeroDataError = class extends BaseError3 {
      constructor() {
        super('Cannot decode zero data ("0x") with ABI parameters.');
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "AbiParameters.ZeroDataError"
        });
      }
    };
    ArrayLengthMismatchError = class extends BaseError3 {
      constructor({ expectedLength, givenLength, type }) {
        super(`Array length mismatch for type \`${type}\`. Expected: \`${expectedLength}\`. Given: \`${givenLength}\`.`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "AbiParameters.ArrayLengthMismatchError"
        });
      }
    };
    BytesSizeMismatchError2 = class extends BaseError3 {
      constructor({ expectedSize, value }) {
        super(`Size of bytes "${value}" (bytes${size3(value)}) does not match expected size (bytes${expectedSize}).`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "AbiParameters.BytesSizeMismatchError"
        });
      }
    };
    LengthMismatchError = class extends BaseError3 {
      constructor({ expectedLength, givenLength }) {
        super([
          "ABI encoding parameters/values length mismatch.",
          `Expected length (parameters): ${expectedLength}`,
          `Given length (values): ${givenLength}`
        ].join("\n"));
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "AbiParameters.LengthMismatchError"
        });
      }
    };
    InvalidArrayError2 = class extends BaseError3 {
      constructor(value) {
        super(`Value \`${value}\` is not a valid array.`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "AbiParameters.InvalidArrayError"
        });
      }
    };
    InvalidTypeError = class extends BaseError3 {
      constructor(type) {
        super(`Type \`${type}\` is not a valid ABI Type.`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "AbiParameters.InvalidTypeError"
        });
      }
    };
  }
});

// node_modules/ox/_esm/core/Rlp.js
function from6(value, options) {
  const { as } = options;
  const encodable = getEncodable2(value);
  const cursor = create(new Uint8Array(encodable.length));
  encodable.encode(cursor);
  if (as === "Hex")
    return fromBytes(cursor.bytes);
  return cursor.bytes;
}
function fromHex3(hex, options = {}) {
  const { as = "Hex" } = options;
  return from6(hex, { as });
}
function getEncodable2(bytes) {
  if (Array.isArray(bytes))
    return getEncodableList2(bytes.map((x) => getEncodable2(x)));
  return getEncodableBytes2(bytes);
}
function getEncodableList2(list) {
  const bodyLength = list.reduce((acc, x) => acc + x.length, 0);
  const sizeOfBodyLength = getSizeOfLength2(bodyLength);
  const length = (() => {
    if (bodyLength <= 55)
      return 1 + bodyLength;
    return 1 + sizeOfBodyLength + bodyLength;
  })();
  return {
    length,
    encode(cursor) {
      if (bodyLength <= 55) {
        cursor.pushByte(192 + bodyLength);
      } else {
        cursor.pushByte(192 + 55 + sizeOfBodyLength);
        if (sizeOfBodyLength === 1)
          cursor.pushUint8(bodyLength);
        else if (sizeOfBodyLength === 2)
          cursor.pushUint16(bodyLength);
        else if (sizeOfBodyLength === 3)
          cursor.pushUint24(bodyLength);
        else
          cursor.pushUint32(bodyLength);
      }
      for (const { encode: encode4 } of list) {
        encode4(cursor);
      }
    }
  };
}
function getEncodableBytes2(bytesOrHex) {
  const bytes = typeof bytesOrHex === "string" ? fromHex(bytesOrHex) : bytesOrHex;
  const sizeOfBytesLength = getSizeOfLength2(bytes.length);
  const length = (() => {
    if (bytes.length === 1 && bytes[0] < 128)
      return 1;
    if (bytes.length <= 55)
      return 1 + bytes.length;
    return 1 + sizeOfBytesLength + bytes.length;
  })();
  return {
    length,
    encode(cursor) {
      if (bytes.length === 1 && bytes[0] < 128) {
        cursor.pushBytes(bytes);
      } else if (bytes.length <= 55) {
        cursor.pushByte(128 + bytes.length);
        cursor.pushBytes(bytes);
      } else {
        cursor.pushByte(128 + 55 + sizeOfBytesLength);
        if (sizeOfBytesLength === 1)
          cursor.pushUint8(bytes.length);
        else if (sizeOfBytesLength === 2)
          cursor.pushUint16(bytes.length);
        else if (sizeOfBytesLength === 3)
          cursor.pushUint24(bytes.length);
        else
          cursor.pushUint32(bytes.length);
        cursor.pushBytes(bytes);
      }
    }
  };
}
function getSizeOfLength2(length) {
  if (length <= 255)
    return 1;
  if (length <= 65535)
    return 2;
  if (length <= 16777215)
    return 3;
  if (length <= 4294967295)
    return 4;
  throw new BaseError3("Length is too large.");
}
var init_Rlp = __esm({
  "node_modules/ox/_esm/core/Rlp.js"() {
    "use strict";
    init_Bytes();
    init_Errors();
    init_Hex();
    init_cursor3();
  }
});

// node_modules/ox/node_modules/@noble/curves/esm/abstract/modular.js
function mod2(a, b) {
  const result = a % b;
  return result >= _0n9 ? result : b + result;
}
function pow22(x, power, modulo2) {
  let res = x;
  while (power-- > _0n9) {
    res *= res;
    res %= modulo2;
  }
  return res;
}
function invert2(number, modulo2) {
  if (number === _0n9)
    throw new Error("invert: expected non-zero number");
  if (modulo2 <= _0n9)
    throw new Error("invert: expected positive modulus, got " + modulo2);
  let a = mod2(number, modulo2);
  let b = modulo2;
  let x = _0n9, y = _1n9, u = _1n9, v = _0n9;
  while (a !== _0n9) {
    const q = b / a;
    const r = b % a;
    const m = x - u * q;
    const n = y - v * q;
    b = a, a = r, x = u, y = v, u = m, v = n;
  }
  const gcd2 = b;
  if (gcd2 !== _1n9)
    throw new Error("invert: does not exist");
  return mod2(x, modulo2);
}
function sqrt3mod42(Fp, n) {
  const p1div4 = (Fp.ORDER + _1n9) / _4n3;
  const root = Fp.pow(n, p1div4);
  if (!Fp.eql(Fp.sqr(root), n))
    throw new Error("Cannot find square root");
  return root;
}
function sqrt5mod82(Fp, n) {
  const p5div8 = (Fp.ORDER - _5n2) / _8n2;
  const n2 = Fp.mul(n, _2n6);
  const v = Fp.pow(n2, p5div8);
  const nv = Fp.mul(n, v);
  const i = Fp.mul(Fp.mul(nv, _2n6), v);
  const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
  if (!Fp.eql(Fp.sqr(root), n))
    throw new Error("Cannot find square root");
  return root;
}
function tonelliShanks2(P2) {
  if (P2 < BigInt(3))
    throw new Error("sqrt is not defined for small field");
  let Q = P2 - _1n9;
  let S = 0;
  while (Q % _2n6 === _0n9) {
    Q /= _2n6;
    S++;
  }
  let Z = _2n6;
  const _Fp = Field2(P2);
  while (FpLegendre2(_Fp, Z) === 1) {
    if (Z++ > 1e3)
      throw new Error("Cannot find square root: probably non-prime P");
  }
  if (S === 1)
    return sqrt3mod42;
  let cc = _Fp.pow(Z, Q);
  const Q1div2 = (Q + _1n9) / _2n6;
  return function tonelliSlow(Fp, n) {
    if (Fp.is0(n))
      return n;
    if (FpLegendre2(Fp, n) !== 1)
      throw new Error("Cannot find square root");
    let M = S;
    let c = Fp.mul(Fp.ONE, cc);
    let t = Fp.pow(n, Q);
    let R = Fp.pow(n, Q1div2);
    while (!Fp.eql(t, Fp.ONE)) {
      if (Fp.is0(t))
        return Fp.ZERO;
      let i = 1;
      let t_tmp = Fp.sqr(t);
      while (!Fp.eql(t_tmp, Fp.ONE)) {
        i++;
        t_tmp = Fp.sqr(t_tmp);
        if (i === M)
          throw new Error("Cannot find square root");
      }
      const exponent = _1n9 << BigInt(M - i - 1);
      const b = Fp.pow(c, exponent);
      M = i;
      c = Fp.sqr(b);
      t = Fp.mul(t, c);
      R = Fp.mul(R, b);
    }
    return R;
  };
}
function FpSqrt2(P2) {
  if (P2 % _4n3 === _3n3)
    return sqrt3mod42;
  if (P2 % _8n2 === _5n2)
    return sqrt5mod82;
  return tonelliShanks2(P2);
}
function validateField2(field) {
  const initial = {
    ORDER: "bigint",
    MASK: "bigint",
    BYTES: "isSafeInteger",
    BITS: "isSafeInteger"
  };
  const opts = FIELD_FIELDS2.reduce((map, val) => {
    map[val] = "function";
    return map;
  }, initial);
  return validateObject2(field, opts);
}
function FpPow2(Fp, num2, power) {
  if (power < _0n9)
    throw new Error("invalid exponent, negatives unsupported");
  if (power === _0n9)
    return Fp.ONE;
  if (power === _1n9)
    return num2;
  let p = Fp.ONE;
  let d = num2;
  while (power > _0n9) {
    if (power & _1n9)
      p = Fp.mul(p, d);
    d = Fp.sqr(d);
    power >>= _1n9;
  }
  return p;
}
function FpInvertBatch2(Fp, nums, passZero = false) {
  const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
  const multipliedAcc = nums.reduce((acc, num2, i) => {
    if (Fp.is0(num2))
      return acc;
    inverted[i] = acc;
    return Fp.mul(acc, num2);
  }, Fp.ONE);
  const invertedAcc = Fp.inv(multipliedAcc);
  nums.reduceRight((acc, num2, i) => {
    if (Fp.is0(num2))
      return acc;
    inverted[i] = Fp.mul(acc, inverted[i]);
    return Fp.mul(acc, num2);
  }, invertedAcc);
  return inverted;
}
function FpLegendre2(Fp, n) {
  const p1mod2 = (Fp.ORDER - _1n9) / _2n6;
  const powered = Fp.pow(n, p1mod2);
  const yes = Fp.eql(powered, Fp.ONE);
  const zero = Fp.eql(powered, Fp.ZERO);
  const no = Fp.eql(powered, Fp.neg(Fp.ONE));
  if (!yes && !zero && !no)
    throw new Error("invalid Legendre symbol result");
  return yes ? 1 : zero ? 0 : -1;
}
function nLength2(n, nBitLength) {
  if (nBitLength !== void 0)
    anumber2(nBitLength);
  const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
  const nByteLength = Math.ceil(_nBitLength / 8);
  return { nBitLength: _nBitLength, nByteLength };
}
function Field2(ORDER, bitLen4, isLE3 = false, redef = {}) {
  if (ORDER <= _0n9)
    throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
  const { nBitLength: BITS, nByteLength: BYTES } = nLength2(ORDER, bitLen4);
  if (BYTES > 2048)
    throw new Error("invalid field: expected ORDER of <= 2048 bytes");
  let sqrtP;
  const f = Object.freeze({
    ORDER,
    isLE: isLE3,
    BITS,
    BYTES,
    MASK: bitMask2(BITS),
    ZERO: _0n9,
    ONE: _1n9,
    create: (num2) => mod2(num2, ORDER),
    isValid: (num2) => {
      if (typeof num2 !== "bigint")
        throw new Error("invalid field element: expected bigint, got " + typeof num2);
      return _0n9 <= num2 && num2 < ORDER;
    },
    is0: (num2) => num2 === _0n9,
    isOdd: (num2) => (num2 & _1n9) === _1n9,
    neg: (num2) => mod2(-num2, ORDER),
    eql: (lhs, rhs) => lhs === rhs,
    sqr: (num2) => mod2(num2 * num2, ORDER),
    add: (lhs, rhs) => mod2(lhs + rhs, ORDER),
    sub: (lhs, rhs) => mod2(lhs - rhs, ORDER),
    mul: (lhs, rhs) => mod2(lhs * rhs, ORDER),
    pow: (num2, power) => FpPow2(f, num2, power),
    div: (lhs, rhs) => mod2(lhs * invert2(rhs, ORDER), ORDER),
    // Same as above, but doesn't normalize
    sqrN: (num2) => num2 * num2,
    addN: (lhs, rhs) => lhs + rhs,
    subN: (lhs, rhs) => lhs - rhs,
    mulN: (lhs, rhs) => lhs * rhs,
    inv: (num2) => invert2(num2, ORDER),
    sqrt: redef.sqrt || ((n) => {
      if (!sqrtP)
        sqrtP = FpSqrt2(ORDER);
      return sqrtP(f, n);
    }),
    toBytes: (num2) => isLE3 ? numberToBytesLE2(num2, BYTES) : numberToBytesBE2(num2, BYTES),
    fromBytes: (bytes) => {
      if (bytes.length !== BYTES)
        throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
      return isLE3 ? bytesToNumberLE2(bytes) : bytesToNumberBE2(bytes);
    },
    // TODO: we don't need it here, move out to separate fn
    invertBatch: (lst) => FpInvertBatch2(f, lst),
    // We can't move this out because Fp6, Fp12 implement it
    // and it's unclear what to return in there.
    cmov: (a, b, c) => c ? b : a
  });
  return Object.freeze(f);
}
function getFieldBytesLength2(fieldOrder) {
  if (typeof fieldOrder !== "bigint")
    throw new Error("field order must be bigint");
  const bitLength = fieldOrder.toString(2).length;
  return Math.ceil(bitLength / 8);
}
function getMinHashLength2(fieldOrder) {
  const length = getFieldBytesLength2(fieldOrder);
  return length + Math.ceil(length / 2);
}
function mapHashToField2(key, fieldOrder, isLE3 = false) {
  const len = key.length;
  const fieldLen = getFieldBytesLength2(fieldOrder);
  const minLen = getMinHashLength2(fieldOrder);
  if (len < 16 || len < minLen || len > 1024)
    throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
  const num2 = isLE3 ? bytesToNumberLE2(key) : bytesToNumberBE2(key);
  const reduced = mod2(num2, fieldOrder - _1n9) + _1n9;
  return isLE3 ? numberToBytesLE2(reduced, fieldLen) : numberToBytesBE2(reduced, fieldLen);
}
var _0n9, _1n9, _2n6, _3n3, _4n3, _5n2, _8n2, FIELD_FIELDS2;
var init_modular2 = __esm({
  "node_modules/ox/node_modules/@noble/curves/esm/abstract/modular.js"() {
    "use strict";
    init_utils7();
    init_utils5();
    _0n9 = BigInt(0);
    _1n9 = BigInt(1);
    _2n6 = /* @__PURE__ */ BigInt(2);
    _3n3 = /* @__PURE__ */ BigInt(3);
    _4n3 = /* @__PURE__ */ BigInt(4);
    _5n2 = /* @__PURE__ */ BigInt(5);
    _8n2 = /* @__PURE__ */ BigInt(8);
    FIELD_FIELDS2 = [
      "create",
      "isValid",
      "is0",
      "neg",
      "inv",
      "sqrt",
      "sqr",
      "eql",
      "add",
      "sub",
      "mul",
      "pow",
      "div",
      "addN",
      "subN",
      "mulN",
      "sqrN"
    ];
  }
});

// node_modules/ox/node_modules/@noble/curves/esm/abstract/curve.js
function constTimeNegate2(condition, item) {
  const neg = item.negate();
  return condition ? neg : item;
}
function validateW2(W, bits) {
  if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
    throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
}
function calcWOpts2(W, scalarBits) {
  validateW2(W, scalarBits);
  const windows = Math.ceil(scalarBits / W) + 1;
  const windowSize = 2 ** (W - 1);
  const maxNumber = 2 ** W;
  const mask = bitMask2(W);
  const shiftBy = BigInt(W);
  return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets2(n, window, wOpts) {
  const { windowSize, mask, maxNumber, shiftBy } = wOpts;
  let wbits = Number(n & mask);
  let nextN = n >> shiftBy;
  if (wbits > windowSize) {
    wbits -= maxNumber;
    nextN += _1n10;
  }
  const offsetStart = window * windowSize;
  const offset = offsetStart + Math.abs(wbits) - 1;
  const isZero = wbits === 0;
  const isNeg = wbits < 0;
  const isNegF = window % 2 !== 0;
  const offsetF = offsetStart;
  return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
function validateMSMPoints2(points, c) {
  if (!Array.isArray(points))
    throw new Error("array expected");
  points.forEach((p, i) => {
    if (!(p instanceof c))
      throw new Error("invalid point at index " + i);
  });
}
function validateMSMScalars2(scalars, field) {
  if (!Array.isArray(scalars))
    throw new Error("array of scalars expected");
  scalars.forEach((s3, i) => {
    if (!field.isValid(s3))
      throw new Error("invalid scalar at index " + i);
  });
}
function getW2(P2) {
  return pointWindowSizes2.get(P2) || 1;
}
function wNAF2(c, bits) {
  return {
    constTimeNegate: constTimeNegate2,
    hasPrecomputes(elm) {
      return getW2(elm) !== 1;
    },
    // non-const time multiplication ladder
    unsafeLadder(elm, n, p = c.ZERO) {
      let d = elm;
      while (n > _0n10) {
        if (n & _1n10)
          p = p.add(d);
        d = d.double();
        n >>= _1n10;
      }
      return p;
    },
    /**
     * Creates a wNAF precomputation window. Used for caching.
     * Default window size is set by `utils.precompute()` and is equal to 8.
     * Number of precomputed points depends on the curve size:
     * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
     * - 𝑊 is the window size
     * - 𝑛 is the bitlength of the curve order.
     * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
     * @param elm Point instance
     * @param W window size
     * @returns precomputed point tables flattened to a single array
     */
    precomputeWindow(elm, W) {
      const { windows, windowSize } = calcWOpts2(W, bits);
      const points = [];
      let p = elm;
      let base2 = p;
      for (let window = 0; window < windows; window++) {
        base2 = p;
        points.push(base2);
        for (let i = 1; i < windowSize; i++) {
          base2 = base2.add(p);
          points.push(base2);
        }
        p = base2.double();
      }
      return points;
    },
    /**
     * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
     * @param W window size
     * @param precomputes precomputed tables
     * @param n scalar (we don't check here, but should be less than curve order)
     * @returns real and fake (for const-time) points
     */
    wNAF(W, precomputes, n) {
      let p = c.ZERO;
      let f = c.BASE;
      const wo = calcWOpts2(W, bits);
      for (let window = 0; window < wo.windows; window++) {
        const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets2(n, window, wo);
        n = nextN;
        if (isZero) {
          f = f.add(constTimeNegate2(isNegF, precomputes[offsetF]));
        } else {
          p = p.add(constTimeNegate2(isNeg, precomputes[offset]));
        }
      }
      return { p, f };
    },
    /**
     * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
     * @param W window size
     * @param precomputes precomputed tables
     * @param n scalar (we don't check here, but should be less than curve order)
     * @param acc accumulator point to add result of multiplication
     * @returns point
     */
    wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {
      const wo = calcWOpts2(W, bits);
      for (let window = 0; window < wo.windows; window++) {
        if (n === _0n10)
          break;
        const { nextN, offset, isZero, isNeg } = calcOffsets2(n, window, wo);
        n = nextN;
        if (isZero) {
          continue;
        } else {
          const item = precomputes[offset];
          acc = acc.add(isNeg ? item.negate() : item);
        }
      }
      return acc;
    },
    getPrecomputes(W, P2, transform2) {
      let comp = pointPrecomputes2.get(P2);
      if (!comp) {
        comp = this.precomputeWindow(P2, W);
        if (W !== 1)
          pointPrecomputes2.set(P2, transform2(comp));
      }
      return comp;
    },
    wNAFCached(P2, n, transform2) {
      const W = getW2(P2);
      return this.wNAF(W, this.getPrecomputes(W, P2, transform2), n);
    },
    wNAFCachedUnsafe(P2, n, transform2, prev) {
      const W = getW2(P2);
      if (W === 1)
        return this.unsafeLadder(P2, n, prev);
      return this.wNAFUnsafe(W, this.getPrecomputes(W, P2, transform2), n, prev);
    },
    // We calculate precomputes for elliptic curve point multiplication
    // using windowed method. This specifies window size and
    // stores precomputed values. Usually only base point would be precomputed.
    setWindowSize(P2, W) {
      validateW2(W, bits);
      pointWindowSizes2.set(P2, W);
      pointPrecomputes2.delete(P2);
    }
  };
}
function pippenger2(c, fieldN, points, scalars) {
  validateMSMPoints2(points, c);
  validateMSMScalars2(scalars, fieldN);
  const plength = points.length;
  const slength = scalars.length;
  if (plength !== slength)
    throw new Error("arrays of points and scalars must have equal length");
  const zero = c.ZERO;
  const wbits = bitLen2(BigInt(plength));
  let windowSize = 1;
  if (wbits > 12)
    windowSize = wbits - 3;
  else if (wbits > 4)
    windowSize = wbits - 2;
  else if (wbits > 0)
    windowSize = 2;
  const MASK = bitMask2(windowSize);
  const buckets = new Array(Number(MASK) + 1).fill(zero);
  const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
  let sum = zero;
  for (let i = lastBits; i >= 0; i -= windowSize) {
    buckets.fill(zero);
    for (let j = 0; j < slength; j++) {
      const scalar = scalars[j];
      const wbits2 = Number(scalar >> BigInt(i) & MASK);
      buckets[wbits2] = buckets[wbits2].add(points[j]);
    }
    let resI = zero;
    for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
      sumI = sumI.add(buckets[j]);
      resI = resI.add(sumI);
    }
    sum = sum.add(resI);
    if (i !== 0)
      for (let j = 0; j < windowSize; j++)
        sum = sum.double();
  }
  return sum;
}
function validateBasic2(curve) {
  validateField2(curve.Fp);
  validateObject2(curve, {
    n: "bigint",
    h: "bigint",
    Gx: "field",
    Gy: "field"
  }, {
    nBitLength: "isSafeInteger",
    nByteLength: "isSafeInteger"
  });
  return Object.freeze({
    ...nLength2(curve.n, curve.nBitLength),
    ...curve,
    ...{ p: curve.Fp.ORDER }
  });
}
var _0n10, _1n10, pointPrecomputes2, pointWindowSizes2;
var init_curve2 = __esm({
  "node_modules/ox/node_modules/@noble/curves/esm/abstract/curve.js"() {
    "use strict";
    init_modular2();
    init_utils5();
    _0n10 = BigInt(0);
    _1n10 = BigInt(1);
    pointPrecomputes2 = /* @__PURE__ */ new WeakMap();
    pointWindowSizes2 = /* @__PURE__ */ new WeakMap();
  }
});

// node_modules/ox/node_modules/@noble/curves/esm/abstract/weierstrass.js
function validateSigVerOpts2(opts) {
  if (opts.lowS !== void 0)
    abool2("lowS", opts.lowS);
  if (opts.prehash !== void 0)
    abool2("prehash", opts.prehash);
}
function validatePointOpts2(curve) {
  const opts = validateBasic2(curve);
  validateObject2(opts, {
    a: "field",
    b: "field"
  }, {
    allowInfinityPoint: "boolean",
    allowedPrivateKeyLengths: "array",
    clearCofactor: "function",
    fromBytes: "function",
    isTorsionFree: "function",
    toBytes: "function",
    wrapPrivateKey: "boolean"
  });
  const { endo, Fp, a } = opts;
  if (endo) {
    if (!Fp.eql(a, Fp.ZERO)) {
      throw new Error("invalid endo: CURVE.a must be 0");
    }
    if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") {
      throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');
    }
  }
  return Object.freeze({ ...opts });
}
function numToSizedHex2(num2, size5) {
  return bytesToHex3(numberToBytesBE2(num2, size5));
}
function weierstrassPoints2(opts) {
  const CURVE = validatePointOpts2(opts);
  const { Fp } = CURVE;
  const Fn2 = Field2(CURVE.n, CURVE.nBitLength);
  const toBytes6 = CURVE.toBytes || ((_c, point, _isCompressed) => {
    const a = point.toAffine();
    return concatBytes4(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y));
  });
  const fromBytes4 = CURVE.fromBytes || ((bytes) => {
    const tail = bytes.subarray(1);
    const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
    const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
    return { x, y };
  });
  function weierstrassEquation(x) {
    const { a, b } = CURVE;
    const x2 = Fp.sqr(x);
    const x3 = Fp.mul(x2, x);
    return Fp.add(Fp.add(x3, Fp.mul(x, a)), b);
  }
  function isValidXY(x, y) {
    const left = Fp.sqr(y);
    const right = weierstrassEquation(x);
    return Fp.eql(left, right);
  }
  if (!isValidXY(CURVE.Gx, CURVE.Gy))
    throw new Error("bad curve params: generator point");
  const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n4), _4n4);
  const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
  if (Fp.is0(Fp.add(_4a3, _27b2)))
    throw new Error("bad curve params: a or b");
  function isWithinCurveOrder(num2) {
    return inRange2(num2, _1n11, CURVE.n);
  }
  function normPrivateKeyToScalar(key) {
    const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;
    if (lengths && typeof key !== "bigint") {
      if (isBytes3(key))
        key = bytesToHex3(key);
      if (typeof key !== "string" || !lengths.includes(key.length))
        throw new Error("invalid private key");
      key = key.padStart(nByteLength * 2, "0");
    }
    let num2;
    try {
      num2 = typeof key === "bigint" ? key : bytesToNumberBE2(ensureBytes2("private key", key, nByteLength));
    } catch (error) {
      throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key);
    }
    if (wrapPrivateKey)
      num2 = mod2(num2, N);
    aInRange2("private key", num2, _1n11, N);
    return num2;
  }
  function aprjpoint(other) {
    if (!(other instanceof Point3))
      throw new Error("ProjectivePoint expected");
  }
  const toAffineMemo = memoized2((p, iz) => {
    const { px: x, py: y, pz: z } = p;
    if (Fp.eql(z, Fp.ONE))
      return { x, y };
    const is0 = p.is0();
    if (iz == null)
      iz = is0 ? Fp.ONE : Fp.inv(z);
    const ax = Fp.mul(x, iz);
    const ay = Fp.mul(y, iz);
    const zz = Fp.mul(z, iz);
    if (is0)
      return { x: Fp.ZERO, y: Fp.ZERO };
    if (!Fp.eql(zz, Fp.ONE))
      throw new Error("invZ was invalid");
    return { x: ax, y: ay };
  });
  const assertValidMemo = memoized2((p) => {
    if (p.is0()) {
      if (CURVE.allowInfinityPoint && !Fp.is0(p.py))
        return;
      throw new Error("bad point: ZERO");
    }
    const { x, y } = p.toAffine();
    if (!Fp.isValid(x) || !Fp.isValid(y))
      throw new Error("bad point: x or y not FE");
    if (!isValidXY(x, y))
      throw new Error("bad point: equation left != right");
    if (!p.isTorsionFree())
      throw new Error("bad point: not in prime-order subgroup");
    return true;
  });
  class Point3 {
    constructor(px, py, pz) {
      if (px == null || !Fp.isValid(px))
        throw new Error("x required");
      if (py == null || !Fp.isValid(py) || Fp.is0(py))
        throw new Error("y required");
      if (pz == null || !Fp.isValid(pz))
        throw new Error("z required");
      this.px = px;
      this.py = py;
      this.pz = pz;
      Object.freeze(this);
    }
    // Does not validate if the point is on-curve.
    // Use fromHex instead, or call assertValidity() later.
    static fromAffine(p) {
      const { x, y } = p || {};
      if (!p || !Fp.isValid(x) || !Fp.isValid(y))
        throw new Error("invalid affine point");
      if (p instanceof Point3)
        throw new Error("projective point not allowed");
      const is0 = (i) => Fp.eql(i, Fp.ZERO);
      if (is0(x) && is0(y))
        return Point3.ZERO;
      return new Point3(x, y, Fp.ONE);
    }
    get x() {
      return this.toAffine().x;
    }
    get y() {
      return this.toAffine().y;
    }
    /**
     * Takes a bunch of Projective Points but executes only one
     * inversion on all of them. Inversion is very slow operation,
     * so this improves performance massively.
     * Optimization: converts a list of projective points to a list of identical points with Z=1.
     */
    static normalizeZ(points) {
      const toInv = FpInvertBatch2(Fp, points.map((p) => p.pz));
      return points.map((p, i) => p.toAffine(toInv[i])).map(Point3.fromAffine);
    }
    /**
     * Converts hash string or Uint8Array to Point.
     * @param hex short/long ECDSA hex
     */
    static fromHex(hex) {
      const P2 = Point3.fromAffine(fromBytes4(ensureBytes2("pointHex", hex)));
      P2.assertValidity();
      return P2;
    }
    // Multiplies generator point by privateKey.
    static fromPrivateKey(privateKey) {
      return Point3.BASE.multiply(normPrivateKeyToScalar(privateKey));
    }
    // Multiscalar Multiplication
    static msm(points, scalars) {
      return pippenger2(Point3, Fn2, points, scalars);
    }
    // "Private method", don't use it directly
    _setWindowSize(windowSize) {
      wnaf.setWindowSize(this, windowSize);
    }
    // A point on curve is valid if it conforms to equation.
    assertValidity() {
      assertValidMemo(this);
    }
    hasEvenY() {
      const { y } = this.toAffine();
      if (Fp.isOdd)
        return !Fp.isOdd(y);
      throw new Error("Field doesn't support isOdd");
    }
    /**
     * Compare one point to another.
     */
    equals(other) {
      aprjpoint(other);
      const { px: X1, py: Y1, pz: Z1 } = this;
      const { px: X2, py: Y2, pz: Z2 } = other;
      const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
      const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
      return U1 && U2;
    }
    /**
     * Flips point to one corresponding to (x, -y) in Affine coordinates.
     */
    negate() {
      return new Point3(this.px, Fp.neg(this.py), this.pz);
    }
    // Renes-Costello-Batina exception-free doubling formula.
    // There is 30% faster Jacobian formula, but it is not complete.
    // https://eprint.iacr.org/2015/1060, algorithm 3
    // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
    double() {
      const { a, b } = CURVE;
      const b3 = Fp.mul(b, _3n4);
      const { px: X1, py: Y1, pz: Z1 } = this;
      let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
      let t0 = Fp.mul(X1, X1);
      let t1 = Fp.mul(Y1, Y1);
      let t2 = Fp.mul(Z1, Z1);
      let t3 = Fp.mul(X1, Y1);
      t3 = Fp.add(t3, t3);
      Z3 = Fp.mul(X1, Z1);
      Z3 = Fp.add(Z3, Z3);
      X3 = Fp.mul(a, Z3);
      Y3 = Fp.mul(b3, t2);
      Y3 = Fp.add(X3, Y3);
      X3 = Fp.sub(t1, Y3);
      Y3 = Fp.add(t1, Y3);
      Y3 = Fp.mul(X3, Y3);
      X3 = Fp.mul(t3, X3);
      Z3 = Fp.mul(b3, Z3);
      t2 = Fp.mul(a, t2);
      t3 = Fp.sub(t0, t2);
      t3 = Fp.mul(a, t3);
      t3 = Fp.add(t3, Z3);
      Z3 = Fp.add(t0, t0);
      t0 = Fp.add(Z3, t0);
      t0 = Fp.add(t0, t2);
      t0 = Fp.mul(t0, t3);
      Y3 = Fp.add(Y3, t0);
      t2 = Fp.mul(Y1, Z1);
      t2 = Fp.add(t2, t2);
      t0 = Fp.mul(t2, t3);
      X3 = Fp.sub(X3, t0);
      Z3 = Fp.mul(t2, t1);
      Z3 = Fp.add(Z3, Z3);
      Z3 = Fp.add(Z3, Z3);
      return new Point3(X3, Y3, Z3);
    }
    // Renes-Costello-Batina exception-free addition formula.
    // There is 30% faster Jacobian formula, but it is not complete.
    // https://eprint.iacr.org/2015/1060, algorithm 1
    // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
    add(other) {
      aprjpoint(other);
      const { px: X1, py: Y1, pz: Z1 } = this;
      const { px: X2, py: Y2, pz: Z2 } = other;
      let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
      const a = CURVE.a;
      const b3 = Fp.mul(CURVE.b, _3n4);
      let t0 = Fp.mul(X1, X2);
      let t1 = Fp.mul(Y1, Y2);
      let t2 = Fp.mul(Z1, Z2);
      let t3 = Fp.add(X1, Y1);
      let t4 = Fp.add(X2, Y2);
      t3 = Fp.mul(t3, t4);
      t4 = Fp.add(t0, t1);
      t3 = Fp.sub(t3, t4);
      t4 = Fp.add(X1, Z1);
      let t5 = Fp.add(X2, Z2);
      t4 = Fp.mul(t4, t5);
      t5 = Fp.add(t0, t2);
      t4 = Fp.sub(t4, t5);
      t5 = Fp.add(Y1, Z1);
      X3 = Fp.add(Y2, Z2);
      t5 = Fp.mul(t5, X3);
      X3 = Fp.add(t1, t2);
      t5 = Fp.sub(t5, X3);
      Z3 = Fp.mul(a, t4);
      X3 = Fp.mul(b3, t2);
      Z3 = Fp.add(X3, Z3);
      X3 = Fp.sub(t1, Z3);
      Z3 = Fp.add(t1, Z3);
      Y3 = Fp.mul(X3, Z3);
      t1 = Fp.add(t0, t0);
      t1 = Fp.add(t1, t0);
      t2 = Fp.mul(a, t2);
      t4 = Fp.mul(b3, t4);
      t1 = Fp.add(t1, t2);
      t2 = Fp.sub(t0, t2);
      t2 = Fp.mul(a, t2);
      t4 = Fp.add(t4, t2);
      t0 = Fp.mul(t1, t4);
      Y3 = Fp.add(Y3, t0);
      t0 = Fp.mul(t5, t4);
      X3 = Fp.mul(t3, X3);
      X3 = Fp.sub(X3, t0);
      t0 = Fp.mul(t3, t1);
      Z3 = Fp.mul(t5, Z3);
      Z3 = Fp.add(Z3, t0);
      return new Point3(X3, Y3, Z3);
    }
    subtract(other) {
      return this.add(other.negate());
    }
    is0() {
      return this.equals(Point3.ZERO);
    }
    wNAF(n) {
      return wnaf.wNAFCached(this, n, Point3.normalizeZ);
    }
    /**
     * Non-constant-time multiplication. Uses double-and-add algorithm.
     * It's faster, but should only be used when you don't care about
     * an exposed private key e.g. sig verification, which works over *public* keys.
     */
    multiplyUnsafe(sc) {
      const { endo: endo2, n: N } = CURVE;
      aInRange2("scalar", sc, _0n11, N);
      const I = Point3.ZERO;
      if (sc === _0n11)
        return I;
      if (this.is0() || sc === _1n11)
        return this;
      if (!endo2 || wnaf.hasPrecomputes(this))
        return wnaf.wNAFCachedUnsafe(this, sc, Point3.normalizeZ);
      let { k1neg, k1, k2neg, k2 } = endo2.splitScalar(sc);
      let k1p = I;
      let k2p = I;
      let d = this;
      while (k1 > _0n11 || k2 > _0n11) {
        if (k1 & _1n11)
          k1p = k1p.add(d);
        if (k2 & _1n11)
          k2p = k2p.add(d);
        d = d.double();
        k1 >>= _1n11;
        k2 >>= _1n11;
      }
      if (k1neg)
        k1p = k1p.negate();
      if (k2neg)
        k2p = k2p.negate();
      k2p = new Point3(Fp.mul(k2p.px, endo2.beta), k2p.py, k2p.pz);
      return k1p.add(k2p);
    }
    /**
     * Constant time multiplication.
     * Uses wNAF method. Windowed method may be 10% faster,
     * but takes 2x longer to generate and consumes 2x memory.
     * Uses precomputes when available.
     * Uses endomorphism for Koblitz curves.
     * @param scalar by which the point would be multiplied
     * @returns New point
     */
    multiply(scalar) {
      const { endo: endo2, n: N } = CURVE;
      aInRange2("scalar", scalar, _1n11, N);
      let point, fake;
      if (endo2) {
        const { k1neg, k1, k2neg, k2 } = endo2.splitScalar(scalar);
        let { p: k1p, f: f1p } = this.wNAF(k1);
        let { p: k2p, f: f2p } = this.wNAF(k2);
        k1p = wnaf.constTimeNegate(k1neg, k1p);
        k2p = wnaf.constTimeNegate(k2neg, k2p);
        k2p = new Point3(Fp.mul(k2p.px, endo2.beta), k2p.py, k2p.pz);
        point = k1p.add(k2p);
        fake = f1p.add(f2p);
      } else {
        const { p, f } = this.wNAF(scalar);
        point = p;
        fake = f;
      }
      return Point3.normalizeZ([point, fake])[0];
    }
    /**
     * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
     * Not using Strauss-Shamir trick: precomputation tables are faster.
     * The trick could be useful if both P and Q are not G (not in our case).
     * @returns non-zero affine point
     */
    multiplyAndAddUnsafe(Q, a, b) {
      const G = Point3.BASE;
      const mul = (P2, a2) => a2 === _0n11 || a2 === _1n11 || !P2.equals(G) ? P2.multiplyUnsafe(a2) : P2.multiply(a2);
      const sum = mul(this, a).add(mul(Q, b));
      return sum.is0() ? void 0 : sum;
    }
    // Converts Projective point to affine (x, y) coordinates.
    // Can accept precomputed Z^-1 - for example, from invertBatch.
    // (x, y, z) ∋ (x=x/z, y=y/z)
    toAffine(iz) {
      return toAffineMemo(this, iz);
    }
    isTorsionFree() {
      const { h: cofactor, isTorsionFree } = CURVE;
      if (cofactor === _1n11)
        return true;
      if (isTorsionFree)
        return isTorsionFree(Point3, this);
      throw new Error("isTorsionFree() has not been declared for the elliptic curve");
    }
    clearCofactor() {
      const { h: cofactor, clearCofactor } = CURVE;
      if (cofactor === _1n11)
        return this;
      if (clearCofactor)
        return clearCofactor(Point3, this);
      return this.multiplyUnsafe(CURVE.h);
    }
    toRawBytes(isCompressed = true) {
      abool2("isCompressed", isCompressed);
      this.assertValidity();
      return toBytes6(Point3, this, isCompressed);
    }
    toHex(isCompressed = true) {
      abool2("isCompressed", isCompressed);
      return bytesToHex3(this.toRawBytes(isCompressed));
    }
  }
  Point3.BASE = new Point3(CURVE.Gx, CURVE.Gy, Fp.ONE);
  Point3.ZERO = new Point3(Fp.ZERO, Fp.ONE, Fp.ZERO);
  const { endo, nBitLength } = CURVE;
  const wnaf = wNAF2(Point3, endo ? Math.ceil(nBitLength / 2) : nBitLength);
  return {
    CURVE,
    ProjectivePoint: Point3,
    normPrivateKeyToScalar,
    weierstrassEquation,
    isWithinCurveOrder
  };
}
function validateOpts2(curve) {
  const opts = validateBasic2(curve);
  validateObject2(opts, {
    hash: "hash",
    hmac: "function",
    randomBytes: "function"
  }, {
    bits2int: "function",
    bits2int_modN: "function",
    lowS: "boolean"
  });
  return Object.freeze({ lowS: true, ...opts });
}
function weierstrass2(curveDef) {
  const CURVE = validateOpts2(curveDef);
  const { Fp, n: CURVE_ORDER, nByteLength, nBitLength } = CURVE;
  const compressedLen = Fp.BYTES + 1;
  const uncompressedLen = 2 * Fp.BYTES + 1;
  function modN2(a) {
    return mod2(a, CURVE_ORDER);
  }
  function invN(a) {
    return invert2(a, CURVE_ORDER);
  }
  const { ProjectivePoint: Point3, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints2({
    ...CURVE,
    toBytes(_c, point, isCompressed) {
      const a = point.toAffine();
      const x = Fp.toBytes(a.x);
      const cat = concatBytes4;
      abool2("isCompressed", isCompressed);
      if (isCompressed) {
        return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x);
      } else {
        return cat(Uint8Array.from([4]), x, Fp.toBytes(a.y));
      }
    },
    fromBytes(bytes) {
      const len = bytes.length;
      const head = bytes[0];
      const tail = bytes.subarray(1);
      if (len === compressedLen && (head === 2 || head === 3)) {
        const x = bytesToNumberBE2(tail);
        if (!inRange2(x, _1n11, Fp.ORDER))
          throw new Error("Point is not on curve");
        const y2 = weierstrassEquation(x);
        let y;
        try {
          y = Fp.sqrt(y2);
        } catch (sqrtError) {
          const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : "";
          throw new Error("Point is not on curve" + suffix);
        }
        const isYOdd = (y & _1n11) === _1n11;
        const isHeadOdd = (head & 1) === 1;
        if (isHeadOdd !== isYOdd)
          y = Fp.neg(y);
        return { x, y };
      } else if (len === uncompressedLen && head === 4) {
        const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
        const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
        return { x, y };
      } else {
        const cl = compressedLen;
        const ul = uncompressedLen;
        throw new Error("invalid Point, expected length of " + cl + ", or uncompressed " + ul + ", got " + len);
      }
    }
  });
  function isBiggerThanHalfOrder(number) {
    const HALF = CURVE_ORDER >> _1n11;
    return number > HALF;
  }
  function normalizeS(s3) {
    return isBiggerThanHalfOrder(s3) ? modN2(-s3) : s3;
  }
  const slcNum = (b, from14, to) => bytesToNumberBE2(b.slice(from14, to));
  class Signature {
    constructor(r, s3, recovery) {
      aInRange2("r", r, _1n11, CURVE_ORDER);
      aInRange2("s", s3, _1n11, CURVE_ORDER);
      this.r = r;
      this.s = s3;
      if (recovery != null)
        this.recovery = recovery;
      Object.freeze(this);
    }
    // pair (bytes of r, bytes of s)
    static fromCompact(hex) {
      const l2 = nByteLength;
      hex = ensureBytes2("compactSignature", hex, l2 * 2);
      return new Signature(slcNum(hex, 0, l2), slcNum(hex, l2, 2 * l2));
    }
    // DER encoded ECDSA signature
    // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
    static fromDER(hex) {
      const { r, s: s3 } = DER2.toSig(ensureBytes2("DER", hex));
      return new Signature(r, s3);
    }
    /**
     * @todo remove
     * @deprecated
     */
    assertValidity() {
    }
    addRecoveryBit(recovery) {
      return new Signature(this.r, this.s, recovery);
    }
    recoverPublicKey(msgHash) {
      const { r, s: s3, recovery: rec } = this;
      const h = bits2int_modN(ensureBytes2("msgHash", msgHash));
      if (rec == null || ![0, 1, 2, 3].includes(rec))
        throw new Error("recovery id invalid");
      const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
      if (radj >= Fp.ORDER)
        throw new Error("recovery id 2 or 3 invalid");
      const prefix = (rec & 1) === 0 ? "02" : "03";
      const R = Point3.fromHex(prefix + numToSizedHex2(radj, Fp.BYTES));
      const ir = invN(radj);
      const u1 = modN2(-h * ir);
      const u2 = modN2(s3 * ir);
      const Q = Point3.BASE.multiplyAndAddUnsafe(R, u1, u2);
      if (!Q)
        throw new Error("point at infinify");
      Q.assertValidity();
      return Q;
    }
    // Signatures should be low-s, to prevent malleability.
    hasHighS() {
      return isBiggerThanHalfOrder(this.s);
    }
    normalizeS() {
      return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this;
    }
    // DER-encoded
    toDERRawBytes() {
      return hexToBytes3(this.toDERHex());
    }
    toDERHex() {
      return DER2.hexFromSig(this);
    }
    // padded bytes of r, then padded bytes of s
    toCompactRawBytes() {
      return hexToBytes3(this.toCompactHex());
    }
    toCompactHex() {
      const l2 = nByteLength;
      return numToSizedHex2(this.r, l2) + numToSizedHex2(this.s, l2);
    }
  }
  const utils2 = {
    isValidPrivateKey(privateKey) {
      try {
        normPrivateKeyToScalar(privateKey);
        return true;
      } catch (error) {
        return false;
      }
    },
    normPrivateKeyToScalar,
    /**
     * Produces cryptographically secure private key from random of size
     * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
     */
    randomPrivateKey: () => {
      const length = getMinHashLength2(CURVE.n);
      return mapHashToField2(CURVE.randomBytes(length), CURVE.n);
    },
    /**
     * Creates precompute table for an arbitrary EC point. Makes point "cached".
     * Allows to massively speed-up `point.multiply(scalar)`.
     * @returns cached point
     * @example
     * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
     * fast.multiply(privKey); // much faster ECDH now
     */
    precompute(windowSize = 8, point = Point3.BASE) {
      point._setWindowSize(windowSize);
      point.multiply(BigInt(3));
      return point;
    }
  };
  function getPublicKey(privateKey, isCompressed = true) {
    return Point3.fromPrivateKey(privateKey).toRawBytes(isCompressed);
  }
  function isProbPub(item) {
    if (typeof item === "bigint")
      return false;
    if (item instanceof Point3)
      return true;
    const arr = ensureBytes2("key", item);
    const len = arr.length;
    const fpl = Fp.BYTES;
    const compLen = fpl + 1;
    const uncompLen = 2 * fpl + 1;
    if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {
      return void 0;
    } else {
      return len === compLen || len === uncompLen;
    }
  }
  function getSharedSecret(privateA, publicB, isCompressed = true) {
    if (isProbPub(privateA) === true)
      throw new Error("first arg must be private key");
    if (isProbPub(publicB) === false)
      throw new Error("second arg must be public key");
    const b = Point3.fromHex(publicB);
    return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
  }
  const bits2int = CURVE.bits2int || function(bytes) {
    if (bytes.length > 8192)
      throw new Error("input is too large");
    const num2 = bytesToNumberBE2(bytes);
    const delta = bytes.length * 8 - nBitLength;
    return delta > 0 ? num2 >> BigInt(delta) : num2;
  };
  const bits2int_modN = CURVE.bits2int_modN || function(bytes) {
    return modN2(bits2int(bytes));
  };
  const ORDER_MASK = bitMask2(nBitLength);
  function int2octets(num2) {
    aInRange2("num < 2^" + nBitLength, num2, _0n11, ORDER_MASK);
    return numberToBytesBE2(num2, nByteLength);
  }
  function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
    if (["recovered", "canonical"].some((k) => k in opts))
      throw new Error("sign() legacy options not supported");
    const { hash: hash3, randomBytes: randomBytes8 } = CURVE;
    let { lowS, prehash, extraEntropy: ent } = opts;
    if (lowS == null)
      lowS = true;
    msgHash = ensureBytes2("msgHash", msgHash);
    validateSigVerOpts2(opts);
    if (prehash)
      msgHash = ensureBytes2("prehashed msgHash", hash3(msgHash));
    const h1int = bits2int_modN(msgHash);
    const d = normPrivateKeyToScalar(privateKey);
    const seedArgs = [int2octets(d), int2octets(h1int)];
    if (ent != null && ent !== false) {
      const e7 = ent === true ? randomBytes8(Fp.BYTES) : ent;
      seedArgs.push(ensureBytes2("extraEntropy", e7));
    }
    const seed = concatBytes4(...seedArgs);
    const m = h1int;
    function k2sig(kBytes) {
      const k = bits2int(kBytes);
      if (!isWithinCurveOrder(k))
        return;
      const ik = invN(k);
      const q = Point3.BASE.multiply(k).toAffine();
      const r = modN2(q.x);
      if (r === _0n11)
        return;
      const s3 = modN2(ik * modN2(m + r * d));
      if (s3 === _0n11)
        return;
      let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n11);
      let normS = s3;
      if (lowS && isBiggerThanHalfOrder(s3)) {
        normS = normalizeS(s3);
        recovery ^= 1;
      }
      return new Signature(r, normS, recovery);
    }
    return { seed, k2sig };
  }
  const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };
  const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };
  function sign2(msgHash, privKey, opts = defaultSigOpts) {
    const { seed, k2sig } = prepSig(msgHash, privKey, opts);
    const C = CURVE;
    const drbg = createHmacDrbg2(C.hash.outputLen, C.nByteLength, C.hmac);
    return drbg(seed, k2sig);
  }
  Point3.BASE._setWindowSize(8);
  function verify(signature2, msgHash, publicKey, opts = defaultVerOpts) {
    const sg = signature2;
    msgHash = ensureBytes2("msgHash", msgHash);
    publicKey = ensureBytes2("publicKey", publicKey);
    const { lowS, prehash, format } = opts;
    validateSigVerOpts2(opts);
    if ("strict" in opts)
      throw new Error("options.strict was renamed to lowS");
    if (format !== void 0 && format !== "compact" && format !== "der")
      throw new Error("format must be compact or der");
    const isHex2 = typeof sg === "string" || isBytes3(sg);
    const isObj = !isHex2 && !format && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint";
    if (!isHex2 && !isObj)
      throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
    let _sig = void 0;
    let P2;
    try {
      if (isObj)
        _sig = new Signature(sg.r, sg.s);
      if (isHex2) {
        try {
          if (format !== "compact")
            _sig = Signature.fromDER(sg);
        } catch (derError) {
          if (!(derError instanceof DER2.Err))
            throw derError;
        }
        if (!_sig && format !== "der")
          _sig = Signature.fromCompact(sg);
      }
      P2 = Point3.fromHex(publicKey);
    } catch (error) {
      return false;
    }
    if (!_sig)
      return false;
    if (lowS && _sig.hasHighS())
      return false;
    if (prehash)
      msgHash = CURVE.hash(msgHash);
    const { r, s: s3 } = _sig;
    const h = bits2int_modN(msgHash);
    const is = invN(s3);
    const u1 = modN2(h * is);
    const u2 = modN2(r * is);
    const R = Point3.BASE.multiplyAndAddUnsafe(P2, u1, u2)?.toAffine();
    if (!R)
      return false;
    const v = modN2(R.x);
    return v === r;
  }
  return {
    CURVE,
    getPublicKey,
    getSharedSecret,
    sign: sign2,
    verify,
    ProjectivePoint: Point3,
    Signature,
    utils: utils2
  };
}
var DERErr2, DER2, _0n11, _1n11, _2n7, _3n4, _4n4;
var init_weierstrass2 = __esm({
  "node_modules/ox/node_modules/@noble/curves/esm/abstract/weierstrass.js"() {
    "use strict";
    init_curve2();
    init_modular2();
    init_utils5();
    DERErr2 = class extends Error {
      constructor(m = "") {
        super(m);
      }
    };
    DER2 = {
      // asn.1 DER encoding utils
      Err: DERErr2,
      // Basic building block is TLV (Tag-Length-Value)
      _tlv: {
        encode: (tag, data) => {
          const { Err: E } = DER2;
          if (tag < 0 || tag > 256)
            throw new E("tlv.encode: wrong tag");
          if (data.length & 1)
            throw new E("tlv.encode: unpadded data");
          const dataLen = data.length / 2;
          const len = numberToHexUnpadded2(dataLen);
          if (len.length / 2 & 128)
            throw new E("tlv.encode: long form length too big");
          const lenLen = dataLen > 127 ? numberToHexUnpadded2(len.length / 2 | 128) : "";
          const t = numberToHexUnpadded2(tag);
          return t + lenLen + len + data;
        },
        // v - value, l - left bytes (unparsed)
        decode(tag, data) {
          const { Err: E } = DER2;
          let pos = 0;
          if (tag < 0 || tag > 256)
            throw new E("tlv.encode: wrong tag");
          if (data.length < 2 || data[pos++] !== tag)
            throw new E("tlv.decode: wrong tlv");
          const first = data[pos++];
          const isLong = !!(first & 128);
          let length = 0;
          if (!isLong)
            length = first;
          else {
            const lenLen = first & 127;
            if (!lenLen)
              throw new E("tlv.decode(long): indefinite length not supported");
            if (lenLen > 4)
              throw new E("tlv.decode(long): byte length is too big");
            const lengthBytes = data.subarray(pos, pos + lenLen);
            if (lengthBytes.length !== lenLen)
              throw new E("tlv.decode: length bytes not complete");
            if (lengthBytes[0] === 0)
              throw new E("tlv.decode(long): zero leftmost byte");
            for (const b of lengthBytes)
              length = length << 8 | b;
            pos += lenLen;
            if (length < 128)
              throw new E("tlv.decode(long): not minimal encoding");
          }
          const v = data.subarray(pos, pos + length);
          if (v.length !== length)
            throw new E("tlv.decode: wrong value length");
          return { v, l: data.subarray(pos + length) };
        }
      },
      // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
      // since we always use positive integers here. It must always be empty:
      // - add zero byte if exists
      // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
      _int: {
        encode(num2) {
          const { Err: E } = DER2;
          if (num2 < _0n11)
            throw new E("integer: negative integers are not allowed");
          let hex = numberToHexUnpadded2(num2);
          if (Number.parseInt(hex[0], 16) & 8)
            hex = "00" + hex;
          if (hex.length & 1)
            throw new E("unexpected DER parsing assertion: unpadded hex");
          return hex;
        },
        decode(data) {
          const { Err: E } = DER2;
          if (data[0] & 128)
            throw new E("invalid signature integer: negative");
          if (data[0] === 0 && !(data[1] & 128))
            throw new E("invalid signature integer: unnecessary leading zero");
          return bytesToNumberBE2(data);
        }
      },
      toSig(hex) {
        const { Err: E, _int: int, _tlv: tlv } = DER2;
        const data = ensureBytes2("signature", hex);
        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
        if (seqLeftBytes.length)
          throw new E("invalid signature: left bytes after parsing");
        const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
        const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
        if (sLeftBytes.length)
          throw new E("invalid signature: left bytes after parsing");
        return { r: int.decode(rBytes), s: int.decode(sBytes) };
      },
      hexFromSig(sig) {
        const { _tlv: tlv, _int: int } = DER2;
        const rs = tlv.encode(2, int.encode(sig.r));
        const ss = tlv.encode(2, int.encode(sig.s));
        const seq = rs + ss;
        return tlv.encode(48, seq);
      }
    };
    _0n11 = BigInt(0);
    _1n11 = BigInt(1);
    _2n7 = BigInt(2);
    _3n4 = BigInt(3);
    _4n4 = BigInt(4);
  }
});

// node_modules/ox/node_modules/@noble/curves/esm/_shortw_utils.js
function getHash2(hash3) {
  return {
    hash: hash3,
    hmac: (key, ...msgs) => hmac2(hash3, key, concatBytes5(...msgs)),
    randomBytes: randomBytes2
  };
}
function createCurve2(curveDef, defHash) {
  const create2 = (hash3) => weierstrass2({ ...curveDef, ...getHash2(hash3) });
  return { ...create2(defHash), create: create2 };
}
var init_shortw_utils2 = __esm({
  "node_modules/ox/node_modules/@noble/curves/esm/_shortw_utils.js"() {
    "use strict";
    init_hmac2();
    init_utils7();
    init_weierstrass2();
  }
});

// node_modules/ox/node_modules/@noble/curves/esm/secp256k1.js
function sqrtMod2(y) {
  const P2 = secp256k1P2;
  const _3n7 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
  const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
  const b2 = y * y * y % P2;
  const b3 = b2 * b2 * y % P2;
  const b6 = pow22(b3, _3n7, P2) * b3 % P2;
  const b9 = pow22(b6, _3n7, P2) * b3 % P2;
  const b11 = pow22(b9, _2n8, P2) * b2 % P2;
  const b22 = pow22(b11, _11n, P2) * b11 % P2;
  const b44 = pow22(b22, _22n, P2) * b22 % P2;
  const b88 = pow22(b44, _44n, P2) * b44 % P2;
  const b176 = pow22(b88, _88n, P2) * b88 % P2;
  const b220 = pow22(b176, _44n, P2) * b44 % P2;
  const b223 = pow22(b220, _3n7, P2) * b3 % P2;
  const t1 = pow22(b223, _23n, P2) * b22 % P2;
  const t2 = pow22(t1, _6n, P2) * b2 % P2;
  const root = pow22(t2, _2n8, P2);
  if (!Fpk12.eql(Fpk12.sqr(root), y))
    throw new Error("Cannot find square root");
  return root;
}
var secp256k1P2, secp256k1N2, _0n12, _1n12, _2n8, divNearest2, Fpk12, secp256k12;
var init_secp256k12 = __esm({
  "node_modules/ox/node_modules/@noble/curves/esm/secp256k1.js"() {
    "use strict";
    init_sha22();
    init_shortw_utils2();
    init_modular2();
    secp256k1P2 = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f");
    secp256k1N2 = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
    _0n12 = BigInt(0);
    _1n12 = BigInt(1);
    _2n8 = BigInt(2);
    divNearest2 = (a, b) => (a + b / _2n8) / b;
    Fpk12 = Field2(secp256k1P2, void 0, void 0, { sqrt: sqrtMod2 });
    secp256k12 = createCurve2({
      a: _0n12,
      b: BigInt(7),
      Fp: Fpk12,
      n: secp256k1N2,
      Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),
      Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),
      h: BigInt(1),
      lowS: true,
      // Allow only low-S signatures by default in sign() and verify()
      endo: {
        // Endomorphism, see above
        beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
        splitScalar: (k) => {
          const n = secp256k1N2;
          const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15");
          const b1 = -_1n12 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3");
          const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");
          const b2 = a1;
          const POW_2_128 = BigInt("0x100000000000000000000000000000000");
          const c1 = divNearest2(b2 * k, n);
          const c2 = divNearest2(-b1 * k, n);
          let k1 = mod2(k - c1 * a1 - c2 * a2, n);
          let k2 = mod2(-c1 * b1 - c2 * b2, n);
          const k1neg = k1 > POW_2_128;
          const k2neg = k2 > POW_2_128;
          if (k1neg)
            k1 = n - k1;
          if (k2neg)
            k2 = n - k2;
          if (k1 > POW_2_128 || k2 > POW_2_128) {
            throw new Error("splitScalar: Endomorphism failed, k=" + k);
          }
          return { k1neg, k1, k2neg, k2 };
        }
      }
    }, sha2564);
  }
});

// node_modules/ox/_esm/core/Signature.js
function assert5(signature2, options = {}) {
  const { recovered } = options;
  if (typeof signature2.r === "undefined")
    throw new MissingPropertiesError({ signature: signature2 });
  if (typeof signature2.s === "undefined")
    throw new MissingPropertiesError({ signature: signature2 });
  if (recovered && typeof signature2.yParity === "undefined")
    throw new MissingPropertiesError({ signature: signature2 });
  if (signature2.r < 0n || signature2.r > maxUint2562)
    throw new InvalidRError({ value: signature2.r });
  if (signature2.s < 0n || signature2.s > maxUint2562)
    throw new InvalidSError({ value: signature2.s });
  if (typeof signature2.yParity === "number" && signature2.yParity !== 0 && signature2.yParity !== 1)
    throw new InvalidYParityError({ value: signature2.yParity });
}
function fromBytes3(signature2) {
  return fromHex4(fromBytes(signature2));
}
function fromHex4(signature2) {
  if (signature2.length !== 130 && signature2.length !== 132)
    throw new InvalidSerializedSizeError2({ signature: signature2 });
  const r = BigInt(slice3(signature2, 0, 32));
  const s3 = BigInt(slice3(signature2, 32, 64));
  const yParity = (() => {
    const yParity2 = Number(`0x${signature2.slice(130)}`);
    if (Number.isNaN(yParity2))
      return void 0;
    try {
      return vToYParity(yParity2);
    } catch {
      throw new InvalidYParityError({ value: yParity2 });
    }
  })();
  if (typeof yParity === "undefined")
    return {
      r,
      s: s3
    };
  return {
    r,
    s: s3,
    yParity
  };
}
function extract2(value) {
  if (typeof value.r === "undefined")
    return void 0;
  if (typeof value.s === "undefined")
    return void 0;
  return from7(value);
}
function from7(signature2) {
  const signature_ = (() => {
    if (typeof signature2 === "string")
      return fromHex4(signature2);
    if (signature2 instanceof Uint8Array)
      return fromBytes3(signature2);
    if (typeof signature2.r === "string")
      return fromRpc2(signature2);
    if (signature2.v)
      return fromLegacy(signature2);
    return {
      r: signature2.r,
      s: signature2.s,
      ...typeof signature2.yParity !== "undefined" ? { yParity: signature2.yParity } : {}
    };
  })();
  assert5(signature_);
  return signature_;
}
function fromLegacy(signature2) {
  return {
    r: signature2.r,
    s: signature2.s,
    yParity: vToYParity(signature2.v)
  };
}
function fromRpc2(signature2) {
  const yParity = (() => {
    const v = signature2.v ? Number(signature2.v) : void 0;
    let yParity2 = signature2.yParity ? Number(signature2.yParity) : void 0;
    if (typeof v === "number" && typeof yParity2 !== "number")
      yParity2 = vToYParity(v);
    if (typeof yParity2 !== "number")
      throw new InvalidYParityError({ value: signature2.yParity });
    return yParity2;
  })();
  return {
    r: BigInt(signature2.r),
    s: BigInt(signature2.s),
    yParity
  };
}
function toTuple(signature2) {
  const { r, s: s3, yParity } = signature2;
  return [
    yParity ? "0x01" : "0x",
    r === 0n ? "0x" : trimLeft2(fromNumber(r)),
    s3 === 0n ? "0x" : trimLeft2(fromNumber(s3))
  ];
}
function vToYParity(v) {
  if (v === 0 || v === 27)
    return 0;
  if (v === 1 || v === 28)
    return 1;
  if (v >= 35)
    return v % 2 === 0 ? 1 : 0;
  throw new InvalidVError({ value: v });
}
var InvalidSerializedSizeError2, MissingPropertiesError, InvalidRError, InvalidSError, InvalidYParityError, InvalidVError;
var init_Signature = __esm({
  "node_modules/ox/_esm/core/Signature.js"() {
    "use strict";
    init_Errors();
    init_Hex();
    init_Json();
    init_Solidity();
    InvalidSerializedSizeError2 = class extends BaseError3 {
      constructor({ signature: signature2 }) {
        super(`Value \`${signature2}\` is an invalid signature size.`, {
          metaMessages: [
            "Expected: 64 bytes or 65 bytes.",
            `Received ${size3(from2(signature2))} bytes.`
          ]
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Signature.InvalidSerializedSizeError"
        });
      }
    };
    MissingPropertiesError = class extends BaseError3 {
      constructor({ signature: signature2 }) {
        super(`Signature \`${stringify2(signature2)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Signature.MissingPropertiesError"
        });
      }
    };
    InvalidRError = class extends BaseError3 {
      constructor({ value }) {
        super(`Value \`${value}\` is an invalid r value. r must be a positive integer less than 2^256.`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Signature.InvalidRError"
        });
      }
    };
    InvalidSError = class extends BaseError3 {
      constructor({ value }) {
        super(`Value \`${value}\` is an invalid s value. s must be a positive integer less than 2^256.`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Signature.InvalidSError"
        });
      }
    };
    InvalidYParityError = class extends BaseError3 {
      constructor({ value }) {
        super(`Value \`${value}\` is an invalid y-parity value. Y-parity must be 0 or 1.`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Signature.InvalidYParityError"
        });
      }
    };
    InvalidVError = class extends BaseError3 {
      constructor({ value }) {
        super(`Value \`${value}\` is an invalid v value. v must be 27, 28 or >=35.`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "Signature.InvalidVError"
        });
      }
    };
  }
});

// node_modules/ox/_esm/core/Authorization.js
function from8(authorization, options = {}) {
  if (typeof authorization.chainId === "string")
    return fromRpc3(authorization);
  return { ...authorization, ...options.signature };
}
function fromRpc3(authorization) {
  const { address: address2, chainId, nonce } = authorization;
  const signature2 = extract2(authorization);
  return {
    address: address2,
    chainId: Number(chainId),
    nonce: BigInt(nonce),
    ...signature2
  };
}
function getSignPayload(authorization) {
  return hash2(authorization, { presign: true });
}
function hash2(authorization, options = {}) {
  const { presign } = options;
  return keccak2562(concat2("0x05", fromHex3(toTuple2(presign ? {
    address: authorization.address,
    chainId: authorization.chainId,
    nonce: authorization.nonce
  } : authorization))));
}
function toTuple2(authorization) {
  const { address: address2, chainId, nonce } = authorization;
  const signature2 = extract2(authorization);
  return [
    chainId ? fromNumber(chainId) : "0x",
    address2,
    nonce ? fromNumber(nonce) : "0x",
    ...signature2 ? toTuple(signature2) : []
  ];
}
var init_Authorization = __esm({
  "node_modules/ox/_esm/core/Authorization.js"() {
    "use strict";
    init_Hash();
    init_Hex();
    init_Rlp();
    init_Signature();
  }
});

// node_modules/ox/_esm/core/Secp256k1.js
function recoverAddress2(options) {
  return fromPublicKey(recoverPublicKey2(options));
}
function recoverPublicKey2(options) {
  const { payload, signature: signature2 } = options;
  const { r, s: s3, yParity } = signature2;
  const signature_ = new secp256k12.Signature(BigInt(r), BigInt(s3)).addRecoveryBit(yParity);
  const point = signature_.recoverPublicKey(from2(payload).substring(2));
  return from3(point);
}
var init_Secp256k1 = __esm({
  "node_modules/ox/_esm/core/Secp256k1.js"() {
    "use strict";
    init_secp256k12();
    init_Address();
    init_Hex();
    init_PublicKey();
  }
});

// node_modules/ox/_esm/erc8010/SignatureErc8010.js
var SignatureErc8010_exports = {};
__export(SignatureErc8010_exports, {
  InvalidWrappedSignatureError: () => InvalidWrappedSignatureError,
  assert: () => assert6,
  from: () => from9,
  magicBytes: () => magicBytes,
  suffixParameters: () => suffixParameters,
  unwrap: () => unwrap,
  validate: () => validate4,
  wrap: () => wrap
});
function assert6(value) {
  if (typeof value === "string") {
    if (slice3(value, -32) !== magicBytes)
      throw new InvalidWrappedSignatureError(value);
  } else
    assert5(value.authorization);
}
function from9(value) {
  if (typeof value === "string")
    return unwrap(value);
  return value;
}
function unwrap(wrapped) {
  assert6(wrapped);
  const suffixLength = toNumber(slice3(wrapped, -64, -32));
  const suffix = slice3(wrapped, -suffixLength - 64, -64);
  const signature2 = slice3(wrapped, 0, -suffixLength - 64);
  const [auth, to, data] = decode(suffixParameters, suffix);
  const authorization = from8({
    address: auth.delegation,
    chainId: Number(auth.chainId),
    nonce: auth.nonce,
    yParity: auth.yParity,
    r: auth.r,
    s: auth.s
  });
  return {
    authorization,
    signature: signature2,
    ...data && data !== "0x" ? { data, to } : {}
  };
}
function wrap(value) {
  const { data, signature: signature2 } = value;
  assert6(value);
  const self = recoverAddress2({
    payload: getSignPayload(value.authorization),
    signature: from7(value.authorization)
  });
  const suffix = encode2(suffixParameters, [
    {
      ...value.authorization,
      delegation: value.authorization.address,
      chainId: BigInt(value.authorization.chainId)
    },
    value.to ?? self,
    data ?? "0x"
  ]);
  const suffixLength = fromNumber(size3(suffix), { size: 32 });
  return concat2(signature2, suffix, suffixLength, magicBytes);
}
function validate4(value) {
  try {
    assert6(value);
    return true;
  } catch {
    return false;
  }
}
var magicBytes, suffixParameters, InvalidWrappedSignatureError;
var init_SignatureErc8010 = __esm({
  "node_modules/ox/_esm/erc8010/SignatureErc8010.js"() {
    "use strict";
    init_AbiParameters();
    init_Authorization();
    init_Errors();
    init_Hex();
    init_Secp256k1();
    init_Signature();
    magicBytes = "0x8010801080108010801080108010801080108010801080108010801080108010";
    suffixParameters = from5("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data");
    InvalidWrappedSignatureError = class extends BaseError3 {
      constructor(wrapped) {
        super(`Value \`${wrapped}\` is an invalid ERC-8010 wrapped signature.`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "SignatureErc8010.InvalidWrappedSignatureError"
        });
      }
    };
  }
});

// node_modules/ox/_esm/erc8010/index.js
var init_erc8010 = __esm({
  "node_modules/ox/_esm/erc8010/index.js"() {
    "use strict";
    init_SignatureErc8010();
  }
});

// node_modules/viem/_esm/utils/index.js
var init_utils8 = __esm({
  "node_modules/viem/_esm/utils/index.js"() {
    "use strict";
    init_fromHex();
  }
});

// node_modules/viem/_esm/utils/formatters/proof.js
function formatStorageProof(storageProof) {
  return storageProof.map((proof) => ({
    ...proof,
    value: BigInt(proof.value)
  }));
}
function formatProof(proof) {
  return {
    ...proof,
    balance: proof.balance ? BigInt(proof.balance) : void 0,
    nonce: proof.nonce ? hexToNumber(proof.nonce) : void 0,
    storageProof: proof.storageProof ? formatStorageProof(proof.storageProof) : void 0
  };
}
var init_proof = __esm({
  "node_modules/viem/_esm/utils/formatters/proof.js"() {
    "use strict";
    init_utils8();
  }
});

// node_modules/viem/_esm/actions/public/getProof.js
async function getProof(client, { address: address2, blockNumber, blockTag: blockTag_, storageKeys }) {
  const blockTag = blockTag_ ?? "latest";
  const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
  const proof = await client.request({
    method: "eth_getProof",
    params: [address2, storageKeys, blockNumberHex || blockTag]
  });
  return formatProof(proof);
}
var init_getProof = __esm({
  "node_modules/viem/_esm/actions/public/getProof.js"() {
    "use strict";
    init_toHex();
    init_proof();
  }
});

// node_modules/viem/_esm/actions/public/getStorageAt.js
async function getStorageAt(client, { address: address2, blockNumber, blockTag = "latest", slot }) {
  const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
  const data = await client.request({
    method: "eth_getStorageAt",
    params: [address2, slot, blockNumberHex || blockTag]
  });
  return data;
}
var init_getStorageAt = __esm({
  "node_modules/viem/_esm/actions/public/getStorageAt.js"() {
    "use strict";
    init_toHex();
  }
});

// node_modules/viem/_esm/actions/public/getTransaction.js
async function getTransaction(client, { blockHash, blockNumber, blockTag: blockTag_, hash: hash3, index: index2, sender, nonce }) {
  const blockTag = blockTag_ || "latest";
  const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
  let transaction = null;
  if (hash3) {
    transaction = await client.request({
      method: "eth_getTransactionByHash",
      params: [hash3]
    }, { dedupe: true });
  } else if (blockHash) {
    transaction = await client.request({
      method: "eth_getTransactionByBlockHashAndIndex",
      params: [blockHash, numberToHex(index2)]
    }, { dedupe: true });
  } else if ((blockNumberHex || blockTag) && typeof index2 === "number") {
    transaction = await client.request({
      method: "eth_getTransactionByBlockNumberAndIndex",
      params: [blockNumberHex || blockTag, numberToHex(index2)]
    }, { dedupe: Boolean(blockNumberHex) });
  } else if (sender && typeof nonce === "number") {
    transaction = await client.request({
      method: "eth_getTransactionBySenderAndNonce",
      params: [sender, numberToHex(nonce)]
    }, { dedupe: true });
  }
  if (!transaction)
    throw new TransactionNotFoundError({
      blockHash,
      blockNumber,
      blockTag,
      hash: hash3,
      index: index2
    });
  const format = client.chain?.formatters?.transaction?.format || formatTransaction;
  return format(transaction, "getTransaction");
}
var init_getTransaction = __esm({
  "node_modules/viem/_esm/actions/public/getTransaction.js"() {
    "use strict";
    init_transaction();
    init_toHex();
    init_transaction2();
  }
});

// node_modules/viem/_esm/actions/public/getTransactionConfirmations.js
async function getTransactionConfirmations(client, { hash: hash3, transactionReceipt }) {
  const [blockNumber, transaction] = await Promise.all([
    getAction(client, getBlockNumber, "getBlockNumber")({}),
    hash3 ? getAction(client, getTransaction, "getTransaction")({ hash: hash3 }) : void 0
  ]);
  const transactionBlockNumber = transactionReceipt?.blockNumber || transaction?.blockNumber;
  if (!transactionBlockNumber)
    return 0n;
  return blockNumber - transactionBlockNumber + 1n;
}
var init_getTransactionConfirmations = __esm({
  "node_modules/viem/_esm/actions/public/getTransactionConfirmations.js"() {
    "use strict";
    init_getAction();
    init_getBlockNumber();
    init_getTransaction();
  }
});

// node_modules/viem/_esm/actions/public/getTransactionReceipt.js
async function getTransactionReceipt(client, { hash: hash3 }) {
  const receipt = await client.request({
    method: "eth_getTransactionReceipt",
    params: [hash3]
  }, { dedupe: true });
  if (!receipt)
    throw new TransactionReceiptNotFoundError({ hash: hash3 });
  const format = client.chain?.formatters?.transactionReceipt?.format || formatTransactionReceipt;
  return format(receipt, "getTransactionReceipt");
}
var init_getTransactionReceipt = __esm({
  "node_modules/viem/_esm/actions/public/getTransactionReceipt.js"() {
    "use strict";
    init_transaction();
    init_transactionReceipt();
  }
});

// node_modules/viem/_esm/actions/public/multicall.js
async function multicall(client, parameters) {
  const { account, authorizationList, allowFailure = true, blockNumber, blockOverrides, blockTag, stateOverride } = parameters;
  const contracts2 = parameters.contracts;
  const { batchSize = parameters.batchSize ?? 1024, deployless = parameters.deployless ?? false } = typeof client.batch?.multicall === "object" ? client.batch.multicall : {};
  const multicallAddress = (() => {
    if (parameters.multicallAddress)
      return parameters.multicallAddress;
    if (deployless)
      return null;
    if (client.chain) {
      return getChainContractAddress({
        blockNumber,
        chain: client.chain,
        contract: "multicall3"
      });
    }
    throw new Error("client chain not configured. multicallAddress is required.");
  })();
  const chunkedCalls = [[]];
  let currentChunk = 0;
  let currentChunkSize = 0;
  for (let i = 0; i < contracts2.length; i++) {
    const { abi: abi2, address: address2, args, functionName } = contracts2[i];
    try {
      const callData = encodeFunctionData({ abi: abi2, args, functionName });
      currentChunkSize += (callData.length - 2) / 2;
      if (
        // Check if batching is enabled.
        batchSize > 0 && // Check if the current size of the batch exceeds the size limit.
        currentChunkSize > batchSize && // Check if the current chunk is not already empty.
        chunkedCalls[currentChunk].length > 0
      ) {
        currentChunk++;
        currentChunkSize = (callData.length - 2) / 2;
        chunkedCalls[currentChunk] = [];
      }
      chunkedCalls[currentChunk] = [
        ...chunkedCalls[currentChunk],
        {
          allowFailure: true,
          callData,
          target: address2
        }
      ];
    } catch (err) {
      const error = getContractError(err, {
        abi: abi2,
        address: address2,
        args,
        docsPath: "/docs/contract/multicall",
        functionName,
        sender: account
      });
      if (!allowFailure)
        throw error;
      chunkedCalls[currentChunk] = [
        ...chunkedCalls[currentChunk],
        {
          allowFailure: true,
          callData: "0x",
          target: address2
        }
      ];
    }
  }
  const aggregate3Results = await Promise.allSettled(chunkedCalls.map((calls) => getAction(client, readContract, "readContract")({
    ...multicallAddress === null ? { code: multicall3Bytecode } : { address: multicallAddress },
    abi: multicall3Abi,
    account,
    args: [calls],
    authorizationList,
    blockNumber,
    blockOverrides,
    blockTag,
    functionName: "aggregate3",
    stateOverride
  })));
  const results = [];
  for (let i = 0; i < aggregate3Results.length; i++) {
    const result = aggregate3Results[i];
    if (result.status === "rejected") {
      if (!allowFailure)
        throw result.reason;
      for (let j = 0; j < chunkedCalls[i].length; j++) {
        results.push({
          status: "failure",
          error: result.reason,
          result: void 0
        });
      }
      continue;
    }
    const aggregate3Result = result.value;
    for (let j = 0; j < aggregate3Result.length; j++) {
      const { returnData, success } = aggregate3Result[j];
      const { callData } = chunkedCalls[i][j];
      const { abi: abi2, address: address2, functionName, args } = contracts2[results.length];
      try {
        if (callData === "0x")
          throw new AbiDecodingZeroDataError();
        if (!success)
          throw new RawContractError({ data: returnData });
        const result2 = decodeFunctionResult({
          abi: abi2,
          args,
          data: returnData,
          functionName
        });
        results.push(allowFailure ? { result: result2, status: "success" } : result2);
      } catch (err) {
        const error = getContractError(err, {
          abi: abi2,
          address: address2,
          args,
          docsPath: "/docs/contract/multicall",
          functionName
        });
        if (!allowFailure)
          throw error;
        results.push({ error, result: void 0, status: "failure" });
      }
    }
  }
  if (results.length !== contracts2.length)
    throw new BaseError2("multicall results mismatch");
  return results;
}
var init_multicall = __esm({
  "node_modules/viem/_esm/actions/public/multicall.js"() {
    "use strict";
    init_abis();
    init_contracts();
    init_abi();
    init_base();
    init_contract();
    init_decodeFunctionResult();
    init_encodeFunctionData();
    init_getChainContractAddress();
    init_getContractError();
    init_getAction();
    init_readContract();
  }
});

// node_modules/viem/_esm/actions/public/simulateBlocks.js
async function simulateBlocks(client, parameters) {
  const { blockNumber, blockTag = client.experimental_blockTag ?? "latest", blocks, returnFullTransactions, traceTransfers, validation } = parameters;
  try {
    const blockStateCalls = [];
    for (const block2 of blocks) {
      const blockOverrides = block2.blockOverrides ? toRpc2(block2.blockOverrides) : void 0;
      const calls = block2.calls.map((call_) => {
        const call2 = call_;
        const account = call2.account ? parseAccount(call2.account) : void 0;
        const data = call2.abi ? encodeFunctionData(call2) : call2.data;
        const request = {
          ...call2,
          account,
          data: call2.dataSuffix ? concat([data || "0x", call2.dataSuffix]) : data,
          from: call2.from ?? account?.address
        };
        assertRequest(request);
        return formatTransactionRequest(request);
      });
      const stateOverrides = block2.stateOverrides ? serializeStateOverride(block2.stateOverrides) : void 0;
      blockStateCalls.push({
        blockOverrides,
        calls,
        stateOverrides
      });
    }
    const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : void 0;
    const block = blockNumberHex || blockTag;
    const result = await client.request({
      method: "eth_simulateV1",
      params: [
        { blockStateCalls, returnFullTransactions, traceTransfers, validation },
        block
      ]
    });
    return result.map((block2, i) => ({
      ...formatBlock(block2),
      calls: block2.calls.map((call2, j) => {
        const { abi: abi2, args, functionName, to } = blocks[i].calls[j];
        const data = call2.error?.data ?? call2.returnData;
        const gasUsed = BigInt(call2.gasUsed);
        const logs = call2.logs?.map((log) => formatLog(log));
        const status = call2.status === "0x1" ? "success" : "failure";
        const result2 = abi2 && status === "success" && data !== "0x" ? decodeFunctionResult({
          abi: abi2,
          data,
          functionName
        }) : null;
        const error = (() => {
          if (status === "success")
            return void 0;
          let error2;
          if (data === "0x")
            error2 = new AbiDecodingZeroDataError();
          else if (data)
            error2 = new RawContractError({ data });
          if (!error2)
            return void 0;
          return getContractError(error2, {
            abi: abi2 ?? [],
            address: to ?? "0x",
            args,
            functionName: functionName ?? "<unknown>"
          });
        })();
        return {
          data,
          gasUsed,
          logs,
          status,
          ...status === "success" ? {
            result: result2
          } : {
            error
          }
        };
      })
    }));
  } catch (e7) {
    const cause = e7;
    const error = getNodeError(cause, {});
    if (error instanceof UnknownNodeError)
      throw cause;
    throw error;
  }
}
var init_simulateBlocks = __esm({
  "node_modules/viem/_esm/actions/public/simulateBlocks.js"() {
    "use strict";
    init_BlockOverrides();
    init_parseAccount();
    init_abi();
    init_contract();
    init_node();
    init_decodeFunctionResult();
    init_encodeFunctionData();
    init_concat();
    init_toHex();
    init_getContractError();
    init_getNodeError();
    init_block2();
    init_log2();
    init_transactionRequest();
    init_stateOverride2();
    init_assertRequest();
  }
});

// node_modules/ox/_esm/core/internal/abiItem.js
function normalizeSignature2(signature2) {
  let active = true;
  let current = "";
  let level = 0;
  let result = "";
  let valid = false;
  for (let i = 0; i < signature2.length; i++) {
    const char = signature2[i];
    if (["(", ")", ","].includes(char))
      active = true;
    if (char === "(")
      level++;
    if (char === ")")
      level--;
    if (!active)
      continue;
    if (level === 0) {
      if (char === " " && ["event", "function", "error", ""].includes(result))
        result = "";
      else {
        result += char;
        if (char === ")") {
          valid = true;
          break;
        }
      }
      continue;
    }
    if (char === " ") {
      if (signature2[i - 1] !== "," && current !== "," && current !== ",(") {
        current = "";
        active = false;
      }
      continue;
    }
    result += char;
    current += char;
  }
  if (!valid)
    throw new BaseError3("Unable to normalize signature.");
  return result;
}
function isArgOfType2(arg, abiParameter) {
  const argType = typeof arg;
  const abiParameterType = abiParameter.type;
  switch (abiParameterType) {
    case "address":
      return validate3(arg, { strict: false });
    case "bool":
      return argType === "boolean";
    case "function":
      return argType === "string";
    case "string":
      return argType === "string";
    default: {
      if (abiParameterType === "tuple" && "components" in abiParameter)
        return Object.values(abiParameter.components).every((component, index2) => {
          return isArgOfType2(Object.values(arg)[index2], component);
        });
      if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType))
        return argType === "number" || argType === "bigint";
      if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType))
        return argType === "string" || arg instanceof Uint8Array;
      if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) {
        return Array.isArray(arg) && arg.every((x) => isArgOfType2(x, {
          ...abiParameter,
          // Pop off `[]` or `[M]` from end of type
          type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "")
        }));
      }
      return false;
    }
  }
}
function getAmbiguousTypes2(sourceParameters, targetParameters, args) {
  for (const parameterIndex in sourceParameters) {
    const sourceParameter = sourceParameters[parameterIndex];
    const targetParameter = targetParameters[parameterIndex];
    if (sourceParameter.type === "tuple" && targetParameter.type === "tuple" && "components" in sourceParameter && "components" in targetParameter)
      return getAmbiguousTypes2(sourceParameter.components, targetParameter.components, args[parameterIndex]);
    const types = [sourceParameter.type, targetParameter.type];
    const ambiguous = (() => {
      if (types.includes("address") && types.includes("bytes20"))
        return true;
      if (types.includes("address") && types.includes("string"))
        return validate3(args[parameterIndex], {
          strict: false
        });
      if (types.includes("address") && types.includes("bytes"))
        return validate3(args[parameterIndex], {
          strict: false
        });
      return false;
    })();
    if (ambiguous)
      return types;
  }
  return;
}
var init_abiItem2 = __esm({
  "node_modules/ox/_esm/core/internal/abiItem.js"() {
    "use strict";
    init_Address();
    init_Errors();
  }
});

// node_modules/ox/_esm/core/AbiItem.js
function from10(abiItem, options = {}) {
  const { prepare = true } = options;
  const item = (() => {
    if (Array.isArray(abiItem))
      return parseAbiItem(abiItem);
    if (typeof abiItem === "string")
      return parseAbiItem(abiItem);
    return abiItem;
  })();
  return {
    ...item,
    ...prepare ? { hash: getSignatureHash(item) } : {}
  };
}
function fromAbi(abi2, name, options) {
  const { args = [], prepare = true } = options ?? {};
  const isSelector = validate2(name, { strict: false });
  const abiItems = abi2.filter((abiItem2) => {
    if (isSelector) {
      if (abiItem2.type === "function" || abiItem2.type === "error")
        return getSelector(abiItem2) === slice3(name, 0, 4);
      if (abiItem2.type === "event")
        return getSignatureHash(abiItem2) === name;
      return false;
    }
    return "name" in abiItem2 && abiItem2.name === name;
  });
  if (abiItems.length === 0)
    throw new NotFoundError({ name });
  if (abiItems.length === 1)
    return {
      ...abiItems[0],
      ...prepare ? { hash: getSignatureHash(abiItems[0]) } : {}
    };
  let matchedAbiItem;
  for (const abiItem2 of abiItems) {
    if (!("inputs" in abiItem2))
      continue;
    if (!args || args.length === 0) {
      if (!abiItem2.inputs || abiItem2.inputs.length === 0)
        return {
          ...abiItem2,
          ...prepare ? { hash: getSignatureHash(abiItem2) } : {}
        };
      continue;
    }
    if (!abiItem2.inputs)
      continue;
    if (abiItem2.inputs.length === 0)
      continue;
    if (abiItem2.inputs.length !== args.length)
      continue;
    const matched = args.every((arg, index2) => {
      const abiParameter = "inputs" in abiItem2 && abiItem2.inputs[index2];
      if (!abiParameter)
        return false;
      return isArgOfType2(arg, abiParameter);
    });
    if (matched) {
      if (matchedAbiItem && "inputs" in matchedAbiItem && matchedAbiItem.inputs) {
        const ambiguousTypes = getAmbiguousTypes2(abiItem2.inputs, matchedAbiItem.inputs, args);
        if (ambiguousTypes)
          throw new AmbiguityError({
            abiItem: abiItem2,
            type: ambiguousTypes[0]
          }, {
            abiItem: matchedAbiItem,
            type: ambiguousTypes[1]
          });
      }
      matchedAbiItem = abiItem2;
    }
  }
  const abiItem = (() => {
    if (matchedAbiItem)
      return matchedAbiItem;
    const [abiItem2, ...overloads] = abiItems;
    return { ...abiItem2, overloads };
  })();
  if (!abiItem)
    throw new NotFoundError({ name });
  return {
    ...abiItem,
    ...prepare ? { hash: getSignatureHash(abiItem) } : {}
  };
}
function getSelector(...parameters) {
  const abiItem = (() => {
    if (Array.isArray(parameters[0])) {
      const [abi2, name] = parameters;
      return fromAbi(abi2, name);
    }
    return parameters[0];
  })();
  return slice3(getSignatureHash(abiItem), 0, 4);
}
function getSignature(...parameters) {
  const abiItem = (() => {
    if (Array.isArray(parameters[0])) {
      const [abi2, name] = parameters;
      return fromAbi(abi2, name);
    }
    return parameters[0];
  })();
  const signature2 = (() => {
    if (typeof abiItem === "string")
      return abiItem;
    return formatAbiItem(abiItem);
  })();
  return normalizeSignature2(signature2);
}
function getSignatureHash(...parameters) {
  const abiItem = (() => {
    if (Array.isArray(parameters[0])) {
      const [abi2, name] = parameters;
      return fromAbi(abi2, name);
    }
    return parameters[0];
  })();
  if (typeof abiItem !== "string" && "hash" in abiItem && abiItem.hash)
    return abiItem.hash;
  return keccak2562(fromString2(getSignature(abiItem)));
}
var AmbiguityError, NotFoundError;
var init_AbiItem = __esm({
  "node_modules/ox/_esm/core/AbiItem.js"() {
    "use strict";
    init_exports();
    init_Errors();
    init_Hash();
    init_Hex();
    init_abiItem2();
    AmbiguityError = class extends BaseError3 {
      constructor(x, y) {
        super("Found ambiguous types in overloaded ABI Items.", {
          metaMessages: [
            // TODO: abitype to add support for signature-formatted ABI items.
            `\`${x.type}\` in \`${normalizeSignature2(formatAbiItem(x.abiItem))}\`, and`,
            `\`${y.type}\` in \`${normalizeSignature2(formatAbiItem(y.abiItem))}\``,
            "",
            "These types encode differently and cannot be distinguished at runtime.",
            "Remove one of the ambiguous items in the ABI."
          ]
        });
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "AbiItem.AmbiguityError"
        });
      }
    };
    NotFoundError = class extends BaseError3 {
      constructor({ name, data, type = "item" }) {
        const selector = (() => {
          if (name)
            return ` with name "${name}"`;
          if (data)
            return ` with data "${data}"`;
          return "";
        })();
        super(`ABI ${type}${selector} not found.`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "AbiItem.NotFoundError"
        });
      }
    };
  }
});

// node_modules/ox/_esm/core/AbiConstructor.js
function encode3(...parameters) {
  const [abiConstructor, options] = (() => {
    if (Array.isArray(parameters[0])) {
      const [abi2, options2] = parameters;
      return [fromAbi2(abi2), options2];
    }
    return parameters;
  })();
  const { bytecode, args } = options;
  return concat2(bytecode, abiConstructor.inputs?.length && args?.length ? encode2(abiConstructor.inputs, args) : "0x");
}
function from11(abiConstructor) {
  return from10(abiConstructor);
}
function fromAbi2(abi2) {
  const item = abi2.find((item2) => item2.type === "constructor");
  if (!item)
    throw new NotFoundError({ name: "constructor" });
  return item;
}
var init_AbiConstructor = __esm({
  "node_modules/ox/_esm/core/AbiConstructor.js"() {
    "use strict";
    init_AbiItem();
    init_AbiParameters();
    init_Hex();
  }
});

// node_modules/ox/_esm/core/AbiFunction.js
function encodeData2(...parameters) {
  const [abiFunction, args = []] = (() => {
    if (Array.isArray(parameters[0])) {
      const [abi2, name, args3] = parameters;
      return [fromAbi3(abi2, name, { args: args3 }), args3];
    }
    const [abiFunction2, args2] = parameters;
    return [abiFunction2, args2];
  })();
  const { overloads } = abiFunction;
  const item = overloads ? fromAbi3([abiFunction, ...overloads], abiFunction.name, {
    args
  }) : abiFunction;
  const selector = getSelector2(item);
  const data = args.length > 0 ? encode2(item.inputs, args) : void 0;
  return data ? concat2(selector, data) : selector;
}
function from12(abiFunction, options = {}) {
  return from10(abiFunction, options);
}
function fromAbi3(abi2, name, options) {
  const item = fromAbi(abi2, name, options);
  if (item.type !== "function")
    throw new NotFoundError({ name, type: "function" });
  return item;
}
function getSelector2(abiItem) {
  return getSelector(abiItem);
}
var init_AbiFunction = __esm({
  "node_modules/ox/_esm/core/AbiFunction.js"() {
    "use strict";
    init_AbiItem();
    init_AbiParameters();
    init_Hex();
  }
});

// node_modules/viem/_esm/constants/address.js
var ethAddress, zeroAddress;
var init_address2 = __esm({
  "node_modules/viem/_esm/constants/address.js"() {
    "use strict";
    ethAddress = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
    zeroAddress = "0x0000000000000000000000000000000000000000";
  }
});

// node_modules/viem/_esm/actions/public/simulateCalls.js
async function simulateCalls(client, parameters) {
  const { blockNumber, blockTag, calls, stateOverrides, traceAssetChanges, traceTransfers, validation } = parameters;
  const account = parameters.account ? parseAccount(parameters.account) : void 0;
  if (traceAssetChanges && !account)
    throw new BaseError2("`account` is required when `traceAssetChanges` is true");
  const getBalanceData = account ? encode3(from11("constructor(bytes, bytes)"), {
    bytecode: deploylessCallViaBytecodeBytecode,
    args: [
      getBalanceCode,
      encodeData2(from12("function getBalance(address)"), [account.address])
    ]
  }) : void 0;
  const assetAddresses = traceAssetChanges ? await Promise.all(parameters.calls.map(async (call2) => {
    if (!call2.data && !call2.abi)
      return;
    const { accessList } = await createAccessList(client, {
      account: account.address,
      ...call2,
      data: call2.abi ? encodeFunctionData(call2) : call2.data
    });
    return accessList.map(({ address: address2, storageKeys }) => storageKeys.length > 0 ? address2 : null);
  })).then((x) => x.flat().filter(Boolean)) : [];
  const blocks = await simulateBlocks(client, {
    blockNumber,
    blockTag,
    blocks: [
      ...traceAssetChanges ? [
        // ETH pre balances
        {
          calls: [{ data: getBalanceData }],
          stateOverrides
        },
        // Asset pre balances
        {
          calls: assetAddresses.map((address2, i) => ({
            abi: [
              from12("function balanceOf(address) returns (uint256)")
            ],
            functionName: "balanceOf",
            args: [account.address],
            to: address2,
            from: zeroAddress,
            nonce: i
          })),
          stateOverrides: [
            {
              address: zeroAddress,
              nonce: 0
            }
          ]
        }
      ] : [],
      {
        calls: [...calls, { to: zeroAddress }].map((call2) => ({
          ...call2,
          from: account?.address
        })),
        stateOverrides
      },
      ...traceAssetChanges ? [
        // ETH post balances
        {
          calls: [{ data: getBalanceData }]
        },
        // Asset post balances
        {
          calls: assetAddresses.map((address2, i) => ({
            abi: [
              from12("function balanceOf(address) returns (uint256)")
            ],
            functionName: "balanceOf",
            args: [account.address],
            to: address2,
            from: zeroAddress,
            nonce: i
          })),
          stateOverrides: [
            {
              address: zeroAddress,
              nonce: 0
            }
          ]
        },
        // Decimals
        {
          calls: assetAddresses.map((address2, i) => ({
            to: address2,
            abi: [
              from12("function decimals() returns (uint256)")
            ],
            functionName: "decimals",
            from: zeroAddress,
            nonce: i
          })),
          stateOverrides: [
            {
              address: zeroAddress,
              nonce: 0
            }
          ]
        },
        // Token URI
        {
          calls: assetAddresses.map((address2, i) => ({
            to: address2,
            abi: [
              from12("function tokenURI(uint256) returns (string)")
            ],
            functionName: "tokenURI",
            args: [0n],
            from: zeroAddress,
            nonce: i
          })),
          stateOverrides: [
            {
              address: zeroAddress,
              nonce: 0
            }
          ]
        },
        // Symbols
        {
          calls: assetAddresses.map((address2, i) => ({
            to: address2,
            abi: [from12("function symbol() returns (string)")],
            functionName: "symbol",
            from: zeroAddress,
            nonce: i
          })),
          stateOverrides: [
            {
              address: zeroAddress,
              nonce: 0
            }
          ]
        }
      ] : []
    ],
    traceTransfers,
    validation
  });
  const block_results = traceAssetChanges ? blocks[2] : blocks[0];
  const [block_ethPre, block_assetsPre, , block_ethPost, block_assetsPost, block_decimals, block_tokenURI, block_symbols] = traceAssetChanges ? blocks : [];
  const { calls: block_calls, ...block } = block_results;
  const results = block_calls.slice(0, -1) ?? [];
  const ethPre = block_ethPre?.calls ?? [];
  const assetsPre = block_assetsPre?.calls ?? [];
  const balancesPre = [...ethPre, ...assetsPre].map((call2) => call2.status === "success" ? hexToBigInt(call2.data) : null);
  const ethPost = block_ethPost?.calls ?? [];
  const assetsPost = block_assetsPost?.calls ?? [];
  const balancesPost = [...ethPost, ...assetsPost].map((call2) => call2.status === "success" ? hexToBigInt(call2.data) : null);
  const decimals = (block_decimals?.calls ?? []).map((x) => x.status === "success" ? x.result : null);
  const symbols = (block_symbols?.calls ?? []).map((x) => x.status === "success" ? x.result : null);
  const tokenURI = (block_tokenURI?.calls ?? []).map((x) => x.status === "success" ? x.result : null);
  const changes = [];
  for (const [i, balancePost] of balancesPost.entries()) {
    const balancePre = balancesPre[i];
    if (typeof balancePost !== "bigint")
      continue;
    if (typeof balancePre !== "bigint")
      continue;
    const decimals_ = decimals[i - 1];
    const symbol_ = symbols[i - 1];
    const tokenURI_ = tokenURI[i - 1];
    const token = (() => {
      if (i === 0)
        return {
          address: ethAddress,
          decimals: 18,
          symbol: "ETH"
        };
      return {
        address: assetAddresses[i - 1],
        decimals: tokenURI_ || decimals_ ? Number(decimals_ ?? 1) : void 0,
        symbol: symbol_ ?? void 0
      };
    })();
    if (changes.some((change) => change.token.address === token.address))
      continue;
    changes.push({
      token,
      value: {
        pre: balancePre,
        post: balancePost,
        diff: balancePost - balancePre
      }
    });
  }
  return {
    assetChanges: changes,
    block,
    results
  };
}
var getBalanceCode;
var init_simulateCalls = __esm({
  "node_modules/viem/_esm/actions/public/simulateCalls.js"() {
    "use strict";
    init_AbiConstructor();
    init_AbiFunction();
    init_parseAccount();
    init_address2();
    init_contracts();
    init_base();
    init_encodeFunctionData();
    init_utils8();
    init_createAccessList();
    init_simulateBlocks();
    getBalanceCode = "0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033";
  }
});

// node_modules/ox/_esm/erc6492/SignatureErc6492.js
var SignatureErc6492_exports = {};
__export(SignatureErc6492_exports, {
  InvalidWrappedSignatureError: () => InvalidWrappedSignatureError2,
  assert: () => assert7,
  from: () => from13,
  magicBytes: () => magicBytes2,
  universalSignatureValidatorAbi: () => universalSignatureValidatorAbi,
  universalSignatureValidatorBytecode: () => universalSignatureValidatorBytecode,
  unwrap: () => unwrap2,
  validate: () => validate5,
  wrap: () => wrap2
});
function assert7(wrapped) {
  if (slice3(wrapped, -32) !== magicBytes2)
    throw new InvalidWrappedSignatureError2(wrapped);
}
function from13(wrapped) {
  if (typeof wrapped === "string")
    return unwrap2(wrapped);
  return wrapped;
}
function unwrap2(wrapped) {
  assert7(wrapped);
  const [to, data, signature2] = decode(from5("address, bytes, bytes"), wrapped);
  return { data, signature: signature2, to };
}
function wrap2(value) {
  const { data, signature: signature2, to } = value;
  return concat2(encode2(from5("address, bytes, bytes"), [
    to,
    data,
    signature2
  ]), magicBytes2);
}
function validate5(wrapped) {
  try {
    assert7(wrapped);
    return true;
  } catch {
    return false;
  }
}
var magicBytes2, universalSignatureValidatorBytecode, universalSignatureValidatorAbi, InvalidWrappedSignatureError2;
var init_SignatureErc6492 = __esm({
  "node_modules/ox/_esm/erc6492/SignatureErc6492.js"() {
    "use strict";
    init_AbiParameters();
    init_Errors();
    init_Hex();
    magicBytes2 = "0x6492649264926492649264926492649264926492649264926492649264926492";
    universalSignatureValidatorBytecode = "0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572";
    universalSignatureValidatorAbi = [
      {
        inputs: [
          {
            name: "_signer",
            type: "address"
          },
          {
            name: "_hash",
            type: "bytes32"
          },
          {
            name: "_signature",
            type: "bytes"
          }
        ],
        stateMutability: "nonpayable",
        type: "constructor"
      },
      {
        inputs: [
          {
            name: "_signer",
            type: "address"
          },
          {
            name: "_hash",
            type: "bytes32"
          },
          {
            name: "_signature",
            type: "bytes"
          }
        ],
        outputs: [
          {
            type: "bool"
          }
        ],
        stateMutability: "nonpayable",
        type: "function",
        name: "isValidSig"
      }
    ];
    InvalidWrappedSignatureError2 = class extends BaseError3 {
      constructor(wrapped) {
        super(`Value \`${wrapped}\` is an invalid ERC-6492 wrapped signature.`);
        Object.defineProperty(this, "name", {
          enumerable: true,
          configurable: true,
          writable: true,
          value: "SignatureErc6492.InvalidWrappedSignatureError"
        });
      }
    };
  }
});

// node_modules/ox/_esm/erc6492/index.js
var init_erc6492 = __esm({
  "node_modules/ox/_esm/erc6492/index.js"() {
    "use strict";
    init_SignatureErc6492();
  }
});

// node_modules/viem/_esm/utils/signature/serializeSignature.js
function serializeSignature({ r, s: s3, to = "hex", v, yParity }) {
  const yParity_ = (() => {
    if (yParity === 0 || yParity === 1)
      return yParity;
    if (v && (v === 27n || v === 28n || v >= 35n))
      return v % 2n === 0n ? 1 : 0;
    throw new Error("Invalid `v` or `yParity` value");
  })();
  const signature2 = `0x${new secp256k1.Signature(hexToBigInt(r), hexToBigInt(s3)).toCompactHex()}${yParity_ === 0 ? "1b" : "1c"}`;
  if (to === "hex")
    return signature2;
  return hexToBytes(signature2);
}
var init_serializeSignature = __esm({
  "node_modules/viem/_esm/utils/signature/serializeSignature.js"() {
    "use strict";
    init_secp256k1();
    init_fromHex();
    init_toBytes();
  }
});

// node_modules/viem/_esm/actions/public/verifyHash.js
async function verifyHash(client, parameters) {
  const { address: address2, chain: chain3 = client.chain, hash: hash3, erc6492VerifierAddress: verifierAddress = parameters.universalSignatureVerifierAddress ?? chain3?.contracts?.erc6492Verifier?.address, multicallAddress = parameters.multicallAddress ?? chain3?.contracts?.multicall3?.address, mode = "auto" } = parameters;
  if (chain3?.verifyHash)
    return await chain3.verifyHash(client, parameters);
  const signature2 = (() => {
    const signature3 = parameters.signature;
    if (isHex(signature3))
      return signature3;
    if (typeof signature3 === "object" && "r" in signature3 && "s" in signature3)
      return serializeSignature(signature3);
    return bytesToHex(signature3);
  })();
  try {
    if (mode === "eoa") {
      try {
        const verified = isAddressEqual(getAddress(address2), await recoverAddress({ hash: hash3, signature: signature2 }));
        if (verified)
          return true;
      } catch {
      }
    }
    if (SignatureErc8010_exports.validate(signature2))
      return await verifyErc8010(client, {
        ...parameters,
        multicallAddress,
        signature: signature2
      });
    return await verifyErc6492(client, {
      ...parameters,
      verifierAddress,
      signature: signature2
    });
  } catch (error) {
    if (mode !== "eoa") {
      try {
        const verified = isAddressEqual(getAddress(address2), await recoverAddress({ hash: hash3, signature: signature2 }));
        if (verified)
          return true;
      } catch {
      }
    }
    if (error instanceof VerificationError) {
      return false;
    }
    throw error;
  }
}
async function verifyErc8010(client, parameters) {
  const { address: address2, blockNumber, blockTag, hash: hash3, multicallAddress } = parameters;
  const { authorization: authorization_ox, data: initData, signature: signature2, to } = SignatureErc8010_exports.unwrap(parameters.signature);
  const code = await getCode(client, {
    address: address2,
    blockNumber,
    blockTag
  });
  if (code === concatHex(["0xef0100", authorization_ox.address]))
    return await verifyErc1271(client, {
      address: address2,
      blockNumber,
      blockTag,
      hash: hash3,
      signature: signature2
    });
  const authorization = {
    address: authorization_ox.address,
    chainId: Number(authorization_ox.chainId),
    nonce: Number(authorization_ox.nonce),
    r: numberToHex(authorization_ox.r, { size: 32 }),
    s: numberToHex(authorization_ox.s, { size: 32 }),
    yParity: authorization_ox.yParity
  };
  const valid = await verifyAuthorization({
    address: address2,
    authorization
  });
  if (!valid)
    throw new VerificationError();
  const results = await getAction(client, readContract, "readContract")({
    ...multicallAddress ? { address: multicallAddress } : { code: multicall3Bytecode },
    authorizationList: [authorization],
    abi: multicall3Abi,
    blockNumber,
    blockTag: "pending",
    functionName: "aggregate3",
    args: [
      [
        ...initData ? [
          {
            allowFailure: true,
            target: to ?? address2,
            callData: initData
          }
        ] : [],
        {
          allowFailure: true,
          target: address2,
          callData: encodeFunctionData({
            abi: erc1271Abi,
            functionName: "isValidSignature",
            args: [hash3, signature2]
          })
        }
      ]
    ]
  });
  const data = results[results.length - 1]?.returnData;
  if (data?.startsWith("0x1626ba7e"))
    return true;
  throw new VerificationError();
}
async function verifyErc6492(client, parameters) {
  const { address: address2, factory, factoryData, hash: hash3, signature: signature2, verifierAddress, ...rest } = parameters;
  const wrappedSignature = await (async () => {
    if (!factory && !factoryData)
      return signature2;
    if (SignatureErc6492_exports.validate(signature2))
      return signature2;
    return SignatureErc6492_exports.wrap({
      data: factoryData,
      signature: signature2,
      to: factory
    });
  })();
  const args = verifierAddress ? {
    to: verifierAddress,
    data: encodeFunctionData({
      abi: erc6492SignatureValidatorAbi,
      functionName: "isValidSig",
      args: [address2, hash3, wrappedSignature]
    }),
    ...rest
  } : {
    data: encodeDeployData({
      abi: erc6492SignatureValidatorAbi,
      args: [address2, hash3, wrappedSignature],
      bytecode: erc6492SignatureValidatorByteCode
    }),
    ...rest
  };
  const { data } = await getAction(client, call, "call")(args).catch((error) => {
    if (error instanceof CallExecutionError)
      throw new VerificationError();
    throw error;
  });
  if (hexToBool(data ?? "0x0"))
    return true;
  throw new VerificationError();
}
async function verifyErc1271(client, parameters) {
  const { address: address2, blockNumber, blockTag, hash: hash3, signature: signature2 } = parameters;
  const result = await getAction(client, readContract, "readContract")({
    address: address2,
    abi: erc1271Abi,
    args: [hash3, signature2],
    blockNumber,
    blockTag,
    functionName: "isValidSignature"
  }).catch((error) => {
    if (error instanceof ContractFunctionExecutionError)
      throw new VerificationError();
    throw error;
  });
  if (result.startsWith("0x1626ba7e"))
    return true;
  throw new VerificationError();
}
var VerificationError;
var init_verifyHash = __esm({
  "node_modules/viem/_esm/actions/public/verifyHash.js"() {
    "use strict";
    init_erc6492();
    init_erc8010();
    init_abis();
    init_contracts();
    init_contract();
    init_encodeDeployData();
    init_encodeFunctionData();
    init_getAddress();
    init_isAddressEqual();
    init_verifyAuthorization();
    init_concat();
    init_isHex();
    init_fromHex();
    init_toHex();
    init_getAction();
    init_recoverAddress();
    init_serializeSignature();
    init_call();
    init_getCode();
    init_readContract();
    VerificationError = class extends Error {
    };
  }
});

// node_modules/viem/_esm/actions/public/verifyMessage.js
async function verifyMessage(client, { address: address2, message, factory, factoryData, signature: signature2, ...callRequest }) {
  const hash3 = hashMessage(message);
  return getAction(client, verifyHash, "verifyHash")({
    address: address2,
    factory,
    factoryData,
    hash: hash3,
    signature: signature2,
    ...callRequest
  });
}
var init_verifyMessage = __esm({
  "node_modules/viem/_esm/actions/public/verifyMessage.js"() {
    "use strict";
    init_getAction();
    init_hashMessage();
    init_verifyHash();
  }
});

// node_modules/viem/_esm/actions/public/verifyTypedData.js
async function verifyTypedData(client, parameters) {
  const { address: address2, factory, factoryData, signature: signature2, message, primaryType, types, domain, ...callRequest } = parameters;
  const hash3 = hashTypedData({ message, primaryType, types, domain });
  return getAction(client, verifyHash, "verifyHash")({
    address: address2,
    factory,
    factoryData,
    hash: hash3,
    signature: signature2,
    ...callRequest
  });
}
var init_verifyTypedData = __esm({
  "node_modules/viem/_esm/actions/public/verifyTypedData.js"() {
    "use strict";
    init_getAction();
    init_hashTypedData();
    init_verifyHash();
  }
});

// node_modules/viem/_esm/actions/public/watchBlockNumber.js
function watchBlockNumber(client, { emitOnBegin = false, emitMissed = false, onBlockNumber, onError, poll: poll_, pollingInterval = client.pollingInterval }) {
  const enablePolling = (() => {
    if (typeof poll_ !== "undefined")
      return poll_;
    if (client.transport.type === "webSocket" || client.transport.type === "ipc")
      return false;
    if (client.transport.type === "fallback" && (client.transport.transports[0].config.type === "webSocket" || client.transport.transports[0].config.type === "ipc"))
      return false;
    return true;
  })();
  let prevBlockNumber;
  const pollBlockNumber = () => {
    const observerId = stringify([
      "watchBlockNumber",
      client.uid,
      emitOnBegin,
      emitMissed,
      pollingInterval
    ]);
    return observe(observerId, { onBlockNumber, onError }, (emit) => poll(async () => {
      try {
        const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({ cacheTime: 0 });
        if (prevBlockNumber !== void 0) {
          if (blockNumber === prevBlockNumber)
            return;
          if (blockNumber - prevBlockNumber > 1 && emitMissed) {
            for (let i = prevBlockNumber + 1n; i < blockNumber; i++) {
              emit.onBlockNumber(i, prevBlockNumber);
              prevBlockNumber = i;
            }
          }
        }
        if (prevBlockNumber === void 0 || blockNumber > prevBlockNumber) {
          emit.onBlockNumber(blockNumber, prevBlockNumber);
          prevBlockNumber = blockNumber;
        }
      } catch (err) {
        emit.onError?.(err);
      }
    }, {
      emitOnBegin,
      interval: pollingInterval
    }));
  };
  const subscribeBlockNumber = () => {
    const observerId = stringify([
      "watchBlockNumber",
      client.uid,
      emitOnBegin,
      emitMissed
    ]);
    return observe(observerId, { onBlockNumber, onError }, (emit) => {
      let active = true;
      let unsubscribe = () => active = false;
      (async () => {
        try {
          const transport = (() => {
            if (client.transport.type === "fallback") {
              const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc");
              if (!transport2)
                return client.transport;
              return transport2.value;
            }
            return client.transport;
          })();
          const { unsubscribe: unsubscribe_ } = await transport.subscribe({
            params: ["newHeads"],
            onData(data) {
              if (!active)
                return;
              const blockNumber = hexToBigInt(data.result?.number);
              emit.onBlockNumber(blockNumber, prevBlockNumber);
              prevBlockNumber = blockNumber;
            },
            onError(error) {
              emit.onError?.(error);
            }
          });
          unsubscribe = unsubscribe_;
          if (!active)
            unsubscribe();
        } catch (err) {
          onError?.(err);
        }
      })();
      return () => unsubscribe();
    });
  };
  return enablePolling ? pollBlockNumber() : subscribeBlockNumber();
}
var init_watchBlockNumber = __esm({
  "node_modules/viem/_esm/actions/public/watchBlockNumber.js"() {
    "use strict";
    init_fromHex();
    init_getAction();
    init_observe();
    init_poll();
    init_stringify();
    init_getBlockNumber();
  }
});

// node_modules/viem/_esm/actions/public/waitForTransactionReceipt.js
async function waitForTransactionReceipt(client, parameters) {
  const {
    checkReplacement = true,
    confirmations = 1,
    hash: hash3,
    onReplaced,
    retryCount = 6,
    retryDelay = ({ count }) => ~~(1 << count) * 200,
    // exponential backoff
    timeout = 18e4
  } = parameters;
  const observerId = stringify(["waitForTransactionReceipt", client.uid, hash3]);
  const pollingInterval = (() => {
    if (parameters.pollingInterval)
      return parameters.pollingInterval;
    if (client.chain?.experimental_preconfirmationTime)
      return client.chain.experimental_preconfirmationTime;
    return client.pollingInterval;
  })();
  let transaction;
  let replacedTransaction;
  let receipt;
  let retrying = false;
  let _unobserve;
  let _unwatch;
  const { promise, resolve, reject } = withResolvers();
  const timer = timeout ? setTimeout(() => {
    _unwatch?.();
    _unobserve?.();
    reject(new WaitForTransactionReceiptTimeoutError({ hash: hash3 }));
  }, timeout) : void 0;
  _unobserve = observe(observerId, { onReplaced, resolve, reject }, async (emit) => {
    receipt = await getAction(client, getTransactionReceipt, "getTransactionReceipt")({ hash: hash3 }).catch(() => void 0);
    if (receipt && confirmations <= 1) {
      clearTimeout(timer);
      emit.resolve(receipt);
      _unobserve?.();
      return;
    }
    _unwatch = getAction(client, watchBlockNumber, "watchBlockNumber")({
      emitMissed: true,
      emitOnBegin: true,
      poll: true,
      pollingInterval,
      async onBlockNumber(blockNumber_) {
        const done = (fn) => {
          clearTimeout(timer);
          _unwatch?.();
          fn();
          _unobserve?.();
        };
        let blockNumber = blockNumber_;
        if (retrying)
          return;
        try {
          if (receipt) {
            if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations))
              return;
            done(() => emit.resolve(receipt));
            return;
          }
          if (checkReplacement && !transaction) {
            retrying = true;
            await withRetry(async () => {
              transaction = await getAction(client, getTransaction, "getTransaction")({ hash: hash3 });
              if (transaction.blockNumber)
                blockNumber = transaction.blockNumber;
            }, {
              delay: retryDelay,
              retryCount
            });
            retrying = false;
          }
          receipt = await getAction(client, getTransactionReceipt, "getTransactionReceipt")({ hash: hash3 });
          if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations))
            return;
          done(() => emit.resolve(receipt));
        } catch (err) {
          if (err instanceof TransactionNotFoundError || err instanceof TransactionReceiptNotFoundError) {
            if (!transaction) {
              retrying = false;
              return;
            }
            try {
              replacedTransaction = transaction;
              retrying = true;
              const block = await withRetry(() => getAction(client, getBlock, "getBlock")({
                blockNumber,
                includeTransactions: true
              }), {
                delay: retryDelay,
                retryCount,
                shouldRetry: ({ error }) => error instanceof BlockNotFoundError
              });
              retrying = false;
              const replacementTransaction = block.transactions.find(({ from: from14, nonce }) => from14 === replacedTransaction.from && nonce === replacedTransaction.nonce);
              if (!replacementTransaction)
                return;
              receipt = await getAction(client, getTransactionReceipt, "getTransactionReceipt")({
                hash: replacementTransaction.hash
              });
              if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations))
                return;
              let reason = "replaced";
              if (replacementTransaction.to === replacedTransaction.to && replacementTransaction.value === replacedTransaction.value && replacementTransaction.input === replacedTransaction.input) {
                reason = "repriced";
              } else if (replacementTransaction.from === replacementTransaction.to && replacementTransaction.value === 0n) {
                reason = "cancelled";
              }
              done(() => {
                emit.onReplaced?.({
                  reason,
                  replacedTransaction,
                  transaction: replacementTransaction,
                  transactionReceipt: receipt
                });
                emit.resolve(receipt);
              });
            } catch (err_) {
              done(() => emit.reject(err_));
            }
          } else {
            done(() => emit.reject(err));
          }
        }
      }
    });
  });
  return promise;
}
var init_waitForTransactionReceipt = __esm({
  "node_modules/viem/_esm/actions/public/waitForTransactionReceipt.js"() {
    "use strict";
    init_block();
    init_transaction();
    init_getAction();
    init_observe();
    init_withResolvers();
    init_withRetry();
    init_stringify();
    init_getBlock();
    init_getTransaction();
    init_getTransactionReceipt();
    init_watchBlockNumber();
  }
});

// node_modules/viem/_esm/actions/public/watchBlocks.js
function watchBlocks(client, { blockTag = client.experimental_blockTag ?? "latest", emitMissed = false, emitOnBegin = false, onBlock, onError, includeTransactions: includeTransactions_, poll: poll_, pollingInterval = client.pollingInterval }) {
  const enablePolling = (() => {
    if (typeof poll_ !== "undefined")
      return poll_;
    if (client.transport.type === "webSocket" || client.transport.type === "ipc")
      return false;
    if (client.transport.type === "fallback" && (client.transport.transports[0].config.type === "webSocket" || client.transport.transports[0].config.type === "ipc"))
      return false;
    return true;
  })();
  const includeTransactions = includeTransactions_ ?? false;
  let prevBlock;
  const pollBlocks = () => {
    const observerId = stringify([
      "watchBlocks",
      client.uid,
      blockTag,
      emitMissed,
      emitOnBegin,
      includeTransactions,
      pollingInterval
    ]);
    return observe(observerId, { onBlock, onError }, (emit) => poll(async () => {
      try {
        const block = await getAction(client, getBlock, "getBlock")({
          blockTag,
          includeTransactions
        });
        if (block.number !== null && prevBlock?.number != null) {
          if (block.number === prevBlock.number)
            return;
          if (block.number - prevBlock.number > 1 && emitMissed) {
            for (let i = prevBlock?.number + 1n; i < block.number; i++) {
              const block2 = await getAction(client, getBlock, "getBlock")({
                blockNumber: i,
                includeTransactions
              });
              emit.onBlock(block2, prevBlock);
              prevBlock = block2;
            }
          }
        }
        if (
          // If no previous block exists, emit.
          prevBlock?.number == null || // If the block tag is "pending" with no block number, emit.
          blockTag === "pending" && block?.number == null || // If the next block number is greater than the previous block number, emit.
          // We don't want to emit blocks in the past.
          block.number !== null && block.number > prevBlock.number
        ) {
          emit.onBlock(block, prevBlock);
          prevBlock = block;
        }
      } catch (err) {
        emit.onError?.(err);
      }
    }, {
      emitOnBegin,
      interval: pollingInterval
    }));
  };
  const subscribeBlocks = () => {
    let active = true;
    let emitFetched = true;
    let unsubscribe = () => active = false;
    (async () => {
      try {
        if (emitOnBegin) {
          getAction(client, getBlock, "getBlock")({
            blockTag,
            includeTransactions
          }).then((block) => {
            if (!active)
              return;
            if (!emitFetched)
              return;
            onBlock(block, void 0);
            emitFetched = false;
          }).catch(onError);
        }
        const transport = (() => {
          if (client.transport.type === "fallback") {
            const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc");
            if (!transport2)
              return client.transport;
            return transport2.value;
          }
          return client.transport;
        })();
        const { unsubscribe: unsubscribe_ } = await transport.subscribe({
          params: ["newHeads"],
          async onData(data) {
            if (!active)
              return;
            const block = await getAction(client, getBlock, "getBlock")({
              blockNumber: data.result?.number,
              includeTransactions
            }).catch(() => {
            });
            if (!active)
              return;
            onBlock(block, prevBlock);
            emitFetched = false;
            prevBlock = block;
          },
          onError(error) {
            onError?.(error);
          }
        });
        unsubscribe = unsubscribe_;
        if (!active)
          unsubscribe();
      } catch (err) {
        onError?.(err);
      }
    })();
    return () => unsubscribe();
  };
  return enablePolling ? pollBlocks() : subscribeBlocks();
}
var init_watchBlocks = __esm({
  "node_modules/viem/_esm/actions/public/watchBlocks.js"() {
    "use strict";
    init_getAction();
    init_observe();
    init_poll();
    init_stringify();
    init_getBlock();
  }
});

// node_modules/viem/_esm/actions/public/watchEvent.js
function watchEvent(client, { address: address2, args, batch = true, event, events, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client.pollingInterval, strict: strict_ }) {
  const enablePolling = (() => {
    if (typeof poll_ !== "undefined")
      return poll_;
    if (typeof fromBlock === "bigint")
      return true;
    if (client.transport.type === "webSocket" || client.transport.type === "ipc")
      return false;
    if (client.transport.type === "fallback" && (client.transport.transports[0].config.type === "webSocket" || client.transport.transports[0].config.type === "ipc"))
      return false;
    return true;
  })();
  const strict = strict_ ?? false;
  const pollEvent = () => {
    const observerId = stringify([
      "watchEvent",
      address2,
      args,
      batch,
      client.uid,
      event,
      pollingInterval,
      fromBlock
    ]);
    return observe(observerId, { onLogs, onError }, (emit) => {
      let previousBlockNumber;
      if (fromBlock !== void 0)
        previousBlockNumber = fromBlock - 1n;
      let filter;
      let initialized = false;
      const unwatch = poll(async () => {
        if (!initialized) {
          try {
            filter = await getAction(client, createEventFilter, "createEventFilter")({
              address: address2,
              args,
              event,
              events,
              strict,
              fromBlock
            });
          } catch {
          }
          initialized = true;
          return;
        }
        try {
          let logs;
          if (filter) {
            logs = await getAction(client, getFilterChanges, "getFilterChanges")({ filter });
          } else {
            const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({});
            if (previousBlockNumber && previousBlockNumber !== blockNumber) {
              logs = await getAction(client, getLogs, "getLogs")({
                address: address2,
                args,
                event,
                events,
                fromBlock: previousBlockNumber + 1n,
                toBlock: blockNumber
              });
            } else {
              logs = [];
            }
            previousBlockNumber = blockNumber;
          }
          if (logs.length === 0)
            return;
          if (batch)
            emit.onLogs(logs);
          else
            for (const log of logs)
              emit.onLogs([log]);
        } catch (err) {
          if (filter && err instanceof InvalidInputRpcError)
            initialized = false;
          emit.onError?.(err);
        }
      }, {
        emitOnBegin: true,
        interval: pollingInterval
      });
      return async () => {
        if (filter)
          await getAction(client, uninstallFilter, "uninstallFilter")({ filter });
        unwatch();
      };
    });
  };
  const subscribeEvent = () => {
    let active = true;
    let unsubscribe = () => active = false;
    (async () => {
      try {
        const transport = (() => {
          if (client.transport.type === "fallback") {
            const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc");
            if (!transport2)
              return client.transport;
            return transport2.value;
          }
          return client.transport;
        })();
        const events_ = events ?? (event ? [event] : void 0);
        let topics = [];
        if (events_) {
          const encoded = events_.flatMap((event2) => encodeEventTopics({
            abi: [event2],
            eventName: event2.name,
            args
          }));
          topics = [encoded];
          if (event)
            topics = topics[0];
        }
        const { unsubscribe: unsubscribe_ } = await transport.subscribe({
          params: ["logs", { address: address2, topics }],
          onData(data) {
            if (!active)
              return;
            const log = data.result;
            try {
              const { eventName, args: args2 } = decodeEventLog({
                abi: events_ ?? [],
                data: log.data,
                topics: log.topics,
                strict
              });
              const formatted = formatLog(log, { args: args2, eventName });
              onLogs([formatted]);
            } catch (err) {
              let eventName;
              let isUnnamed;
              if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) {
                if (strict_)
                  return;
                eventName = err.abiItem.name;
                isUnnamed = err.abiItem.inputs?.some((x) => !("name" in x && x.name));
              }
              const formatted = formatLog(log, {
                args: isUnnamed ? [] : {},
                eventName
              });
              onLogs([formatted]);
            }
          },
          onError(error) {
            onError?.(error);
          }
        });
        unsubscribe = unsubscribe_;
        if (!active)
          unsubscribe();
      } catch (err) {
        onError?.(err);
      }
    })();
    return () => unsubscribe();
  };
  return enablePolling ? pollEvent() : subscribeEvent();
}
var init_watchEvent = __esm({
  "node_modules/viem/_esm/actions/public/watchEvent.js"() {
    "use strict";
    init_abi();
    init_rpc();
    init_decodeEventLog();
    init_encodeEventTopics();
    init_log2();
    init_getAction();
    init_observe();
    init_poll();
    init_stringify();
    init_createEventFilter();
    init_getBlockNumber();
    init_getFilterChanges();
    init_getLogs();
    init_uninstallFilter();
  }
});

// node_modules/viem/_esm/actions/public/watchPendingTransactions.js
function watchPendingTransactions(client, { batch = true, onError, onTransactions, poll: poll_, pollingInterval = client.pollingInterval }) {
  const enablePolling = typeof poll_ !== "undefined" ? poll_ : client.transport.type !== "webSocket" && client.transport.type !== "ipc";
  const pollPendingTransactions = () => {
    const observerId = stringify([
      "watchPendingTransactions",
      client.uid,
      batch,
      pollingInterval
    ]);
    return observe(observerId, { onTransactions, onError }, (emit) => {
      let filter;
      const unwatch = poll(async () => {
        try {
          if (!filter) {
            try {
              filter = await getAction(client, createPendingTransactionFilter, "createPendingTransactionFilter")({});
              return;
            } catch (err) {
              unwatch();
              throw err;
            }
          }
          const hashes = await getAction(client, getFilterChanges, "getFilterChanges")({ filter });
          if (hashes.length === 0)
            return;
          if (batch)
            emit.onTransactions(hashes);
          else
            for (const hash3 of hashes)
              emit.onTransactions([hash3]);
        } catch (err) {
          emit.onError?.(err);
        }
      }, {
        emitOnBegin: true,
        interval: pollingInterval
      });
      return async () => {
        if (filter)
          await getAction(client, uninstallFilter, "uninstallFilter")({ filter });
        unwatch();
      };
    });
  };
  const subscribePendingTransactions = () => {
    let active = true;
    let unsubscribe = () => active = false;
    (async () => {
      try {
        const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({
          params: ["newPendingTransactions"],
          onData(data) {
            if (!active)
              return;
            const transaction = data.result;
            onTransactions([transaction]);
          },
          onError(error) {
            onError?.(error);
          }
        });
        unsubscribe = unsubscribe_;
        if (!active)
          unsubscribe();
      } catch (err) {
        onError?.(err);
      }
    })();
    return () => unsubscribe();
  };
  return enablePolling ? pollPendingTransactions() : subscribePendingTransactions();
}
var init_watchPendingTransactions = __esm({
  "node_modules/viem/_esm/actions/public/watchPendingTransactions.js"() {
    "use strict";
    init_getAction();
    init_observe();
    init_poll();
    init_stringify();
    init_createPendingTransactionFilter();
    init_getFilterChanges();
    init_uninstallFilter();
  }
});

// node_modules/viem/_esm/utils/siwe/parseSiweMessage.js
function parseSiweMessage(message) {
  const { scheme, statement, ...prefix } = message.match(prefixRegex)?.groups ?? {};
  const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } = message.match(suffixRegex)?.groups ?? {};
  const resources = message.split("Resources:")[1]?.split("\n- ").slice(1);
  return {
    ...prefix,
    ...suffix,
    ...chainId ? { chainId: Number(chainId) } : {},
    ...expirationTime ? { expirationTime: new Date(expirationTime) } : {},
    ...issuedAt ? { issuedAt: new Date(issuedAt) } : {},
    ...notBefore ? { notBefore: new Date(notBefore) } : {},
    ...requestId ? { requestId } : {},
    ...resources ? { resources } : {},
    ...scheme ? { scheme } : {},
    ...statement ? { statement } : {}
  };
}
var prefixRegex, suffixRegex;
var init_parseSiweMessage = __esm({
  "node_modules/viem/_esm/utils/siwe/parseSiweMessage.js"() {
    "use strict";
    prefixRegex = /^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?<address>0x[a-fA-F0-9]{40})\n\n(?:(?<statement>.*)\n\n)?/;
    suffixRegex = /(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.+))?/;
  }
});

// node_modules/viem/_esm/utils/siwe/validateSiweMessage.js
function validateSiweMessage(parameters) {
  const { address: address2, domain, message, nonce, scheme, time = /* @__PURE__ */ new Date() } = parameters;
  if (domain && message.domain !== domain)
    return false;
  if (nonce && message.nonce !== nonce)
    return false;
  if (scheme && message.scheme !== scheme)
    return false;
  if (message.expirationTime && time >= message.expirationTime)
    return false;
  if (message.notBefore && time < message.notBefore)
    return false;
  try {
    if (!message.address)
      return false;
    if (!isAddress(message.address, { strict: false }))
      return false;
    if (address2 && !isAddressEqual(message.address, address2))
      return false;
  } catch {
    return false;
  }
  return true;
}
var init_validateSiweMessage = __esm({
  "node_modules/viem/_esm/utils/siwe/validateSiweMessage.js"() {
    "use strict";
    init_isAddress();
    init_isAddressEqual();
  }
});

// node_modules/viem/_esm/actions/siwe/verifySiweMessage.js
async function verifySiweMessage(client, parameters) {
  const { address: address2, domain, message, nonce, scheme, signature: signature2, time = /* @__PURE__ */ new Date(), ...callRequest } = parameters;
  const parsed = parseSiweMessage(message);
  if (!parsed.address)
    return false;
  const isValid2 = validateSiweMessage({
    address: address2,
    domain,
    message: parsed,
    nonce,
    scheme,
    time
  });
  if (!isValid2)
    return false;
  const hash3 = hashMessage(message);
  return verifyHash(client, {
    address: parsed.address,
    hash: hash3,
    signature: signature2,
    ...callRequest
  });
}
var init_verifySiweMessage = __esm({
  "node_modules/viem/_esm/actions/siwe/verifySiweMessage.js"() {
    "use strict";
    init_hashMessage();
    init_parseSiweMessage();
    init_validateSiweMessage();
    init_verifyHash();
  }
});

// node_modules/viem/_esm/actions/wallet/sendRawTransactionSync.js
async function sendRawTransactionSync(client, { serializedTransaction, throwOnReceiptRevert, timeout }) {
  const receipt = await client.request({
    method: "eth_sendRawTransactionSync",
    params: timeout ? [serializedTransaction, timeout] : [serializedTransaction]
  }, { retryCount: 0 });
  const format = client.chain?.formatters?.transactionReceipt?.format || formatTransactionReceipt;
  const formatted = format(receipt);
  if (formatted.status === "reverted" && throwOnReceiptRevert)
    throw new TransactionReceiptRevertedError({ receipt: formatted });
  return formatted;
}
var init_sendRawTransactionSync = __esm({
  "node_modules/viem/_esm/actions/wallet/sendRawTransactionSync.js"() {
    "use strict";
    init_transaction();
    init_transactionReceipt();
  }
});

// node_modules/viem/_esm/clients/decorators/public.js
function publicActions(client) {
  return {
    call: (args) => call(client, args),
    createAccessList: (args) => createAccessList(client, args),
    createBlockFilter: () => createBlockFilter(client),
    createContractEventFilter: (args) => createContractEventFilter(client, args),
    createEventFilter: (args) => createEventFilter(client, args),
    createPendingTransactionFilter: () => createPendingTransactionFilter(client),
    estimateContractGas: (args) => estimateContractGas(client, args),
    estimateGas: (args) => estimateGas(client, args),
    getBalance: (args) => getBalance(client, args),
    getBlobBaseFee: () => getBlobBaseFee(client),
    getBlock: (args) => getBlock(client, args),
    getBlockNumber: (args) => getBlockNumber(client, args),
    getBlockTransactionCount: (args) => getBlockTransactionCount(client, args),
    getBytecode: (args) => getCode(client, args),
    getChainId: () => getChainId(client),
    getCode: (args) => getCode(client, args),
    getContractEvents: (args) => getContractEvents(client, args),
    getDelegation: (args) => getDelegation(client, args),
    getEip712Domain: (args) => getEip712Domain(client, args),
    getEnsAddress: (args) => getEnsAddress(client, args),
    getEnsAvatar: (args) => getEnsAvatar(client, args),
    getEnsName: (args) => getEnsName(client, args),
    getEnsResolver: (args) => getEnsResolver(client, args),
    getEnsText: (args) => getEnsText(client, args),
    getFeeHistory: (args) => getFeeHistory(client, args),
    estimateFeesPerGas: (args) => estimateFeesPerGas(client, args),
    getFilterChanges: (args) => getFilterChanges(client, args),
    getFilterLogs: (args) => getFilterLogs(client, args),
    getGasPrice: () => getGasPrice(client),
    getLogs: (args) => getLogs(client, args),
    getProof: (args) => getProof(client, args),
    estimateMaxPriorityFeePerGas: (args) => estimateMaxPriorityFeePerGas(client, args),
    fillTransaction: (args) => fillTransaction(client, args),
    getStorageAt: (args) => getStorageAt(client, args),
    getTransaction: (args) => getTransaction(client, args),
    getTransactionConfirmations: (args) => getTransactionConfirmations(client, args),
    getTransactionCount: (args) => getTransactionCount(client, args),
    getTransactionReceipt: (args) => getTransactionReceipt(client, args),
    multicall: (args) => multicall(client, args),
    prepareTransactionRequest: (args) => prepareTransactionRequest(client, args),
    readContract: (args) => readContract(client, args),
    sendRawTransaction: (args) => sendRawTransaction(client, args),
    sendRawTransactionSync: (args) => sendRawTransactionSync(client, args),
    simulate: (args) => simulateBlocks(client, args),
    simulateBlocks: (args) => simulateBlocks(client, args),
    simulateCalls: (args) => simulateCalls(client, args),
    simulateContract: (args) => simulateContract(client, args),
    verifyHash: (args) => verifyHash(client, args),
    verifyMessage: (args) => verifyMessage(client, args),
    verifySiweMessage: (args) => verifySiweMessage(client, args),
    verifyTypedData: (args) => verifyTypedData(client, args),
    uninstallFilter: (args) => uninstallFilter(client, args),
    waitForTransactionReceipt: (args) => waitForTransactionReceipt(client, args),
    watchBlocks: (args) => watchBlocks(client, args),
    watchBlockNumber: (args) => watchBlockNumber(client, args),
    watchContractEvent: (args) => watchContractEvent(client, args),
    watchEvent: (args) => watchEvent(client, args),
    watchPendingTransactions: (args) => watchPendingTransactions(client, args)
  };
}
var init_public = __esm({
  "node_modules/viem/_esm/clients/decorators/public.js"() {
    "use strict";
    init_getEnsAddress();
    init_getEnsAvatar();
    init_getEnsName();
    init_getEnsResolver();
    init_getEnsText();
    init_call();
    init_createAccessList();
    init_createBlockFilter();
    init_createContractEventFilter();
    init_createEventFilter();
    init_createPendingTransactionFilter();
    init_estimateContractGas();
    init_estimateFeesPerGas();
    init_estimateGas2();
    init_estimateMaxPriorityFeePerGas();
    init_fillTransaction();
    init_getBalance();
    init_getBlobBaseFee();
    init_getBlock();
    init_getBlockNumber();
    init_getBlockTransactionCount();
    init_getChainId();
    init_getCode();
    init_getContractEvents();
    init_getDelegation();
    init_getEip712Domain();
    init_getFeeHistory();
    init_getFilterChanges();
    init_getFilterLogs();
    init_getGasPrice();
    init_getLogs();
    init_getProof();
    init_getStorageAt();
    init_getTransaction();
    init_getTransactionConfirmations();
    init_getTransactionCount();
    init_getTransactionReceipt();
    init_multicall();
    init_readContract();
    init_simulateBlocks();
    init_simulateCalls();
    init_simulateContract();
    init_uninstallFilter();
    init_verifyHash();
    init_verifyMessage();
    init_verifyTypedData();
    init_waitForTransactionReceipt();
    init_watchBlockNumber();
    init_watchBlocks();
    init_watchContractEvent();
    init_watchEvent();
    init_watchPendingTransactions();
    init_verifySiweMessage();
    init_prepareTransactionRequest();
    init_sendRawTransaction();
    init_sendRawTransactionSync();
  }
});

// node_modules/viem/_esm/clients/createPublicClient.js
function createPublicClient(parameters) {
  const { key = "public", name = "Public Client" } = parameters;
  const client = createClient({
    ...parameters,
    key,
    name,
    type: "publicClient"
  });
  return client.extend(publicActions);
}
var init_createPublicClient = __esm({
  "node_modules/viem/_esm/clients/createPublicClient.js"() {
    "use strict";
    init_createClient();
    init_public();
  }
});

// node_modules/viem/_esm/clients/transports/createTransport.js
function createTransport({ key, methods, name, request, retryCount = 3, retryDelay = 150, timeout, type }, value) {
  const uid2 = uid();
  return {
    config: {
      key,
      methods,
      name,
      request,
      retryCount,
      retryDelay,
      timeout,
      type
    },
    request: buildRequest(request, { methods, retryCount, retryDelay, uid: uid2 }),
    value
  };
}
var init_createTransport = __esm({
  "node_modules/viem/_esm/clients/transports/createTransport.js"() {
    "use strict";
    init_buildRequest();
    init_uid();
  }
});

// node_modules/viem/_esm/errors/transport.js
var UrlRequiredError;
var init_transport = __esm({
  "node_modules/viem/_esm/errors/transport.js"() {
    "use strict";
    init_base();
    UrlRequiredError = class extends BaseError2 {
      constructor() {
        super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.", {
          docsPath: "/docs/clients/intro",
          name: "UrlRequiredError"
        });
      }
    };
  }
});

// node_modules/viem/_esm/clients/transports/http.js
function http(url, config = {}) {
  const { batch, fetchFn, fetchOptions, key = "http", methods, name = "HTTP JSON-RPC", onFetchRequest, onFetchResponse, retryDelay, raw } = config;
  return ({ chain: chain3, retryCount: retryCount_, timeout: timeout_ }) => {
    const { batchSize = 1e3, wait: wait2 = 0 } = typeof batch === "object" ? batch : {};
    const retryCount = config.retryCount ?? retryCount_;
    const timeout = timeout_ ?? config.timeout ?? 1e4;
    const url_ = url || chain3?.rpcUrls.default.http[0];
    if (!url_)
      throw new UrlRequiredError();
    const rpcClient = getHttpRpcClient(url_, {
      fetchFn,
      fetchOptions,
      onRequest: onFetchRequest,
      onResponse: onFetchResponse,
      timeout
    });
    return createTransport({
      key,
      methods,
      name,
      async request({ method, params }) {
        const body = { method, params };
        const { schedule } = createBatchScheduler({
          id: url_,
          wait: wait2,
          shouldSplitBatch(requests) {
            return requests.length > batchSize;
          },
          fn: (body2) => rpcClient.request({
            body: body2
          }),
          sort: (a, b) => a.id - b.id
        });
        const fn = async (body2) => batch ? schedule(body2) : [
          await rpcClient.request({
            body: body2
          })
        ];
        const [{ error, result }] = await fn(body);
        if (raw)
          return { error, result };
        if (error)
          throw new RpcRequestError({
            body,
            error,
            url: url_
          });
        return result;
      },
      retryCount,
      retryDelay,
      timeout,
      type: "http"
    }, {
      fetchOptions,
      url: url_
    });
  };
}
var init_http2 = __esm({
  "node_modules/viem/_esm/clients/transports/http.js"() {
    "use strict";
    init_request();
    init_transport();
    init_createBatchScheduler();
    init_http();
    init_createTransport();
  }
});

// node_modules/viem/_esm/index.js
var init_esm = __esm({
  "node_modules/viem/_esm/index.js"() {
    "use strict";
    init_createPublicClient();
    init_http2();
    init_abis();
    init_number();
    init_encodeFunctionData();
    init_getAddress();
    init_toHex();
  }
});

// node_modules/viem/_esm/op-stack/contracts.js
var contracts;
var init_contracts2 = __esm({
  "node_modules/viem/_esm/op-stack/contracts.js"() {
    "use strict";
    contracts = {
      gasPriceOracle: { address: "0x420000000000000000000000000000000000000F" },
      l1Block: { address: "0x4200000000000000000000000000000000000015" },
      l2CrossDomainMessenger: {
        address: "0x4200000000000000000000000000000000000007"
      },
      l2Erc721Bridge: { address: "0x4200000000000000000000000000000000000014" },
      l2StandardBridge: { address: "0x4200000000000000000000000000000000000010" },
      l2ToL1MessagePasser: {
        address: "0x4200000000000000000000000000000000000016"
      }
    };
  }
});

// node_modules/viem/_esm/op-stack/formatters.js
var formatters;
var init_formatters = __esm({
  "node_modules/viem/_esm/op-stack/formatters.js"() {
    "use strict";
    init_fromHex();
    init_block2();
    init_transaction2();
    init_transactionReceipt();
    formatters = {
      block: /* @__PURE__ */ defineBlock({
        format(args) {
          const transactions = args.transactions?.map((transaction) => {
            if (typeof transaction === "string")
              return transaction;
            const formatted = formatTransaction(transaction);
            if (formatted.typeHex === "0x7e") {
              formatted.isSystemTx = transaction.isSystemTx;
              formatted.mint = transaction.mint ? hexToBigInt(transaction.mint) : void 0;
              formatted.sourceHash = transaction.sourceHash;
              formatted.type = "deposit";
            }
            return formatted;
          });
          return {
            transactions,
            stateRoot: args.stateRoot
          };
        }
      }),
      transaction: /* @__PURE__ */ defineTransaction({
        format(args) {
          const transaction = {};
          if (args.type === "0x7e") {
            transaction.isSystemTx = args.isSystemTx;
            transaction.mint = args.mint ? hexToBigInt(args.mint) : void 0;
            transaction.sourceHash = args.sourceHash;
            transaction.type = "deposit";
          }
          return transaction;
        }
      }),
      transactionReceipt: /* @__PURE__ */ defineTransactionReceipt({
        format(args) {
          return {
            l1GasPrice: args.l1GasPrice ? hexToBigInt(args.l1GasPrice) : null,
            l1GasUsed: args.l1GasUsed ? hexToBigInt(args.l1GasUsed) : null,
            l1Fee: args.l1Fee ? hexToBigInt(args.l1Fee) : null,
            l1FeeScalar: args.l1FeeScalar ? Number(args.l1FeeScalar) : null
          };
        }
      })
    };
  }
});

// node_modules/viem/_esm/op-stack/serializers.js
function serializeTransaction2(transaction, signature2) {
  if (isDeposit(transaction))
    return serializeTransactionDeposit(transaction);
  return serializeTransaction(transaction, signature2);
}
function serializeTransactionDeposit(transaction) {
  assertTransactionDeposit(transaction);
  const { sourceHash, data, from: from14, gas, isSystemTx, mint, to, value } = transaction;
  const serializedTransaction = [
    sourceHash,
    from14,
    to ?? "0x",
    mint ? toHex(mint) : "0x",
    value ? toHex(value) : "0x",
    gas ? toHex(gas) : "0x",
    isSystemTx ? "0x1" : "0x",
    data ?? "0x"
  ];
  return concatHex([
    "0x7e",
    toRlp(serializedTransaction)
  ]);
}
function isDeposit(transaction) {
  if (transaction.type === "deposit")
    return true;
  if (typeof transaction.sourceHash !== "undefined")
    return true;
  return false;
}
function assertTransactionDeposit(transaction) {
  const { from: from14, to } = transaction;
  if (from14 && !isAddress(from14))
    throw new InvalidAddressError({ address: from14 });
  if (to && !isAddress(to))
    throw new InvalidAddressError({ address: to });
}
var serializers;
var init_serializers = __esm({
  "node_modules/viem/_esm/op-stack/serializers.js"() {
    "use strict";
    init_address();
    init_isAddress();
    init_concat();
    init_toHex();
    init_toRlp();
    init_serializeTransaction();
    serializers = {
      transaction: serializeTransaction2
    };
  }
});

// node_modules/viem/_esm/op-stack/chainConfig.js
var chainConfig;
var init_chainConfig = __esm({
  "node_modules/viem/_esm/op-stack/chainConfig.js"() {
    "use strict";
    init_contracts2();
    init_formatters();
    init_serializers();
    chainConfig = {
      blockTime: 2e3,
      contracts,
      formatters,
      serializers
    };
  }
});

// node_modules/viem/_esm/chains/definitions/base.js
var sourceId, base, basePreconf;
var init_base2 = __esm({
  "node_modules/viem/_esm/chains/definitions/base.js"() {
    "use strict";
    init_chainConfig();
    init_defineChain();
    sourceId = 1;
    base = /* @__PURE__ */ defineChain({
      ...chainConfig,
      id: 8453,
      name: "Base",
      nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
      rpcUrls: {
        default: {
          http: ["https://mainnet.base.org"]
        }
      },
      blockExplorers: {
        default: {
          name: "Basescan",
          url: "https://basescan.org",
          apiUrl: "https://api.basescan.org/api"
        }
      },
      contracts: {
        ...chainConfig.contracts,
        disputeGameFactory: {
          [sourceId]: {
            address: "0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"
          }
        },
        l2OutputOracle: {
          [sourceId]: {
            address: "0x56315b90c40730925ec5485cf004d835058518A0"
          }
        },
        multicall3: {
          address: "0xca11bde05977b3631167028862be2a173976ca11",
          blockCreated: 5022
        },
        portal: {
          [sourceId]: {
            address: "0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",
            blockCreated: 17482143
          }
        },
        l1StandardBridge: {
          [sourceId]: {
            address: "0x3154Cf16ccdb4C6d922629664174b904d80F2C35",
            blockCreated: 17482143
          }
        }
      },
      sourceId
    });
    basePreconf = /* @__PURE__ */ defineChain({
      ...base,
      experimental_preconfirmationTime: 200,
      rpcUrls: {
        default: {
          http: ["https://mainnet-preconf.base.org"]
        }
      }
    });
  }
});

// node_modules/viem/_esm/chains/index.js
var init_chains = __esm({
  "node_modules/viem/_esm/chains/index.js"() {
    "use strict";
    init_base2();
  }
});

// node_modules/@scure/bip39/node_modules/@noble/hashes/esm/cryptoNode.js
import * as nc3 from "crypto";
var crypto4;
var init_cryptoNode3 = __esm({
  "node_modules/@scure/bip39/node_modules/@noble/hashes/esm/cryptoNode.js"() {
    "use strict";
    crypto4 = nc3 && typeof nc3 === "object" && "webcrypto" in nc3 ? nc3.webcrypto : nc3 && typeof nc3 === "object" && "randomBytes" in nc3 ? nc3 : void 0;
  }
});

// node_modules/@scure/bip39/node_modules/@noble/hashes/esm/utils.js
function isBytes5(a) {
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
function anumber3(n) {
  if (!Number.isSafeInteger(n) || n < 0)
    throw new Error("positive integer expected, got " + n);
}
function abytes5(b, ...lengths) {
  if (!isBytes5(b))
    throw new Error("Uint8Array expected");
  if (lengths.length > 0 && !lengths.includes(b.length))
    throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
}
function ahash3(h) {
  if (typeof h !== "function" || typeof h.create !== "function")
    throw new Error("Hash should be wrapped by utils.createHasher");
  anumber3(h.outputLen);
  anumber3(h.blockLen);
}
function aexists3(instance, checkFinished = true) {
  if (instance.destroyed)
    throw new Error("Hash instance has been destroyed");
  if (checkFinished && instance.finished)
    throw new Error("Hash#digest() has already been called");
}
function aoutput3(out, instance) {
  abytes5(out);
  const min = instance.outputLen;
  if (out.length < min) {
    throw new Error("digestInto() expects output buffer of length at least " + min);
  }
}
function clean3(...arrays) {
  for (let i = 0; i < arrays.length; i++) {
    arrays[i].fill(0);
  }
}
function createView3(arr) {
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
function rotr3(word, shift) {
  return word << 32 - shift | word >>> shift;
}
function utf8ToBytes4(str) {
  if (typeof str !== "string")
    throw new Error("string expected");
  return new Uint8Array(new TextEncoder().encode(str));
}
function toBytes5(data) {
  if (typeof data === "string")
    data = utf8ToBytes4(data);
  abytes5(data);
  return data;
}
function kdfInputToBytes(data) {
  if (typeof data === "string")
    data = utf8ToBytes4(data);
  abytes5(data);
  return data;
}
function checkOpts(defaults, opts) {
  if (opts !== void 0 && {}.toString.call(opts) !== "[object Object]")
    throw new Error("options should be object or undefined");
  const merged = Object.assign(defaults, opts);
  return merged;
}
function createHasher4(hashCons) {
  const hashC = (msg) => hashCons().update(toBytes5(msg)).digest();
  const tmp = hashCons();
  hashC.outputLen = tmp.outputLen;
  hashC.blockLen = tmp.blockLen;
  hashC.create = () => hashCons();
  return hashC;
}
function randomBytes3(bytesLength = 32) {
  if (crypto4 && typeof crypto4.getRandomValues === "function") {
    return crypto4.getRandomValues(new Uint8Array(bytesLength));
  }
  if (crypto4 && typeof crypto4.randomBytes === "function") {
    return Uint8Array.from(crypto4.randomBytes(bytesLength));
  }
  throw new Error("crypto.getRandomValues must be defined");
}
var Hash3;
var init_utils9 = __esm({
  "node_modules/@scure/bip39/node_modules/@noble/hashes/esm/utils.js"() {
    "use strict";
    init_cryptoNode3();
    Hash3 = class {
    };
  }
});

// node_modules/@scure/bip39/node_modules/@noble/hashes/esm/hmac.js
var HMAC3, hmac3;
var init_hmac3 = __esm({
  "node_modules/@scure/bip39/node_modules/@noble/hashes/esm/hmac.js"() {
    "use strict";
    init_utils9();
    HMAC3 = class extends Hash3 {
      constructor(hash3, _key) {
        super();
        this.finished = false;
        this.destroyed = false;
        ahash3(hash3);
        const key = toBytes5(_key);
        this.iHash = hash3.create();
        if (typeof this.iHash.update !== "function")
          throw new Error("Expected instance of class which extends utils.Hash");
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad4 = new Uint8Array(blockLen);
        pad4.set(key.length > blockLen ? hash3.create().update(key).digest() : key);
        for (let i = 0; i < pad4.length; i++)
          pad4[i] ^= 54;
        this.iHash.update(pad4);
        this.oHash = hash3.create();
        for (let i = 0; i < pad4.length; i++)
          pad4[i] ^= 54 ^ 92;
        this.oHash.update(pad4);
        clean3(pad4);
      }
      update(buf) {
        aexists3(this);
        this.iHash.update(buf);
        return this;
      }
      digestInto(out) {
        aexists3(this);
        abytes5(out, this.outputLen);
        this.finished = true;
        this.iHash.digestInto(out);
        this.oHash.update(out);
        this.oHash.digestInto(out);
        this.destroy();
      }
      digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
      }
      _cloneInto(to) {
        to || (to = Object.create(Object.getPrototypeOf(this), {}));
        const { oHash, iHash, finished: finished2, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished2;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
      }
      clone() {
        return this._cloneInto();
      }
      destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
      }
    };
    hmac3 = (hash3, key, message) => new HMAC3(hash3, key).update(message).digest();
    hmac3.create = (hash3, key) => new HMAC3(hash3, key);
  }
});

// node_modules/@scure/bip39/node_modules/@noble/hashes/esm/pbkdf2.js
function pbkdf2Init(hash3, _password, _salt, _opts) {
  ahash3(hash3);
  const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
  const { c, dkLen, asyncTick } = opts;
  anumber3(c);
  anumber3(dkLen);
  anumber3(asyncTick);
  if (c < 1)
    throw new Error("iterations (c) should be >= 1");
  const password = kdfInputToBytes(_password);
  const salt = kdfInputToBytes(_salt);
  const DK = new Uint8Array(dkLen);
  const PRF = hmac3.create(hash3, password);
  const PRFSalt = PRF._cloneInto().update(salt);
  return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
}
function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
  PRF.destroy();
  PRFSalt.destroy();
  if (prfW)
    prfW.destroy();
  clean3(u);
  return DK;
}
function pbkdf2(hash3, password, salt, opts) {
  const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash3, password, salt, opts);
  let prfW;
  const arr = new Uint8Array(4);
  const view = createView3(arr);
  const u = new Uint8Array(PRF.outputLen);
  for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
    const Ti = DK.subarray(pos, pos + PRF.outputLen);
    view.setInt32(0, ti, false);
    (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
    Ti.set(u.subarray(0, Ti.length));
    for (let ui = 1; ui < c; ui++) {
      PRF._cloneInto(prfW).update(u).digestInto(u);
      for (let i = 0; i < Ti.length; i++)
        Ti[i] ^= u[i];
    }
  }
  return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
}
var init_pbkdf2 = __esm({
  "node_modules/@scure/bip39/node_modules/@noble/hashes/esm/pbkdf2.js"() {
    "use strict";
    init_hmac3();
    init_utils9();
  }
});

// node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_md.js
function setBigUint643(view, byteOffset, value, isLE3) {
  if (typeof view.setBigUint64 === "function")
    return view.setBigUint64(byteOffset, value, isLE3);
  const _32n5 = BigInt(32);
  const _u32_max = BigInt(4294967295);
  const wh = Number(value >> _32n5 & _u32_max);
  const wl = Number(value & _u32_max);
  const h = isLE3 ? 4 : 0;
  const l2 = isLE3 ? 0 : 4;
  view.setUint32(byteOffset + h, wh, isLE3);
  view.setUint32(byteOffset + l2, wl, isLE3);
}
function Chi3(a, b, c) {
  return a & b ^ ~a & c;
}
function Maj3(a, b, c) {
  return a & b ^ a & c ^ b & c;
}
var HashMD3, SHA256_IV3, SHA512_IV3;
var init_md3 = __esm({
  "node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_md.js"() {
    "use strict";
    init_utils9();
    HashMD3 = class extends Hash3 {
      constructor(blockLen, outputLen, padOffset, isLE3) {
        super();
        this.finished = false;
        this.length = 0;
        this.pos = 0;
        this.destroyed = false;
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE3;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView3(this.buffer);
      }
      update(data) {
        aexists3(this);
        data = toBytes5(data);
        abytes5(data);
        const { view, buffer: buffer2, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len; ) {
          const take = Math.min(blockLen - this.pos, len - pos);
          if (take === blockLen) {
            const dataView = createView3(data);
            for (; blockLen <= len - pos; pos += blockLen)
              this.process(dataView, pos);
            continue;
          }
          buffer2.set(data.subarray(pos, pos + take), this.pos);
          this.pos += take;
          pos += take;
          if (this.pos === blockLen) {
            this.process(view, 0);
            this.pos = 0;
          }
        }
        this.length += data.length;
        this.roundClean();
        return this;
      }
      digestInto(out) {
        aexists3(this);
        aoutput3(out, this);
        this.finished = true;
        const { buffer: buffer2, view, blockLen, isLE: isLE3 } = this;
        let { pos } = this;
        buffer2[pos++] = 128;
        clean3(this.buffer.subarray(pos));
        if (this.padOffset > blockLen - pos) {
          this.process(view, 0);
          pos = 0;
        }
        for (let i = pos; i < blockLen; i++)
          buffer2[i] = 0;
        setBigUint643(view, blockLen - 8, BigInt(this.length * 8), isLE3);
        this.process(view, 0);
        const oview = createView3(out);
        const len = this.outputLen;
        if (len % 4)
          throw new Error("_sha2: outputLen should be aligned to 32bit");
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
          throw new Error("_sha2: outputLen bigger than state");
        for (let i = 0; i < outLen; i++)
          oview.setUint32(4 * i, state[i], isLE3);
      }
      digest() {
        const { buffer: buffer2, outputLen } = this;
        this.digestInto(buffer2);
        const res = buffer2.slice(0, outputLen);
        this.destroy();
        return res;
      }
      _cloneInto(to) {
        to || (to = new this.constructor());
        to.set(...this.get());
        const { blockLen, buffer: buffer2, length, finished: finished2, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished2;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
          to.buffer.set(buffer2);
        return to;
      }
      clone() {
        return this._cloneInto();
      }
    };
    SHA256_IV3 = /* @__PURE__ */ Uint32Array.from([
      1779033703,
      3144134277,
      1013904242,
      2773480762,
      1359893119,
      2600822924,
      528734635,
      1541459225
    ]);
    SHA512_IV3 = /* @__PURE__ */ Uint32Array.from([
      1779033703,
      4089235720,
      3144134277,
      2227873595,
      1013904242,
      4271175723,
      2773480762,
      1595750129,
      1359893119,
      2917565137,
      2600822924,
      725511199,
      528734635,
      4215389547,
      1541459225,
      327033209
    ]);
  }
});

// node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_u64.js
function fromBig3(n, le = false) {
  if (le)
    return { h: Number(n & U32_MASK643), l: Number(n >> _32n3 & U32_MASK643) };
  return { h: Number(n >> _32n3 & U32_MASK643) | 0, l: Number(n & U32_MASK643) | 0 };
}
function split3(lst, le = false) {
  const len = lst.length;
  let Ah = new Uint32Array(len);
  let Al = new Uint32Array(len);
  for (let i = 0; i < len; i++) {
    const { h, l: l2 } = fromBig3(lst[i], le);
    [Ah[i], Al[i]] = [h, l2];
  }
  return [Ah, Al];
}
function add(Ah, Al, Bh, Bl) {
  const l2 = (Al >>> 0) + (Bl >>> 0);
  return { h: Ah + Bh + (l2 / 2 ** 32 | 0) | 0, l: l2 | 0 };
}
var U32_MASK643, _32n3, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, add3L, add3H, add4L, add4H, add5L, add5H;
var init_u643 = __esm({
  "node_modules/@scure/bip39/node_modules/@noble/hashes/esm/_u64.js"() {
    "use strict";
    U32_MASK643 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
    _32n3 = /* @__PURE__ */ BigInt(32);
    shrSH = (h, _l, s3) => h >>> s3;
    shrSL = (h, l2, s3) => h << 32 - s3 | l2 >>> s3;
    rotrSH = (h, l2, s3) => h >>> s3 | l2 << 32 - s3;
    rotrSL = (h, l2, s3) => h << 32 - s3 | l2 >>> s3;
    rotrBH = (h, l2, s3) => h << 64 - s3 | l2 >>> s3 - 32;
    rotrBL = (h, l2, s3) => h >>> s3 - 32 | l2 << 64 - s3;
    add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
    add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
    add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
    add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
    add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
    add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
  }
});

// node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha2.js
var SHA256_K3, SHA256_W3, SHA2563, K512, SHA512_Kh, SHA512_Kl, SHA512_W_H, SHA512_W_L, SHA512, sha2565, sha512;
var init_sha23 = __esm({
  "node_modules/@scure/bip39/node_modules/@noble/hashes/esm/sha2.js"() {
    "use strict";
    init_md3();
    init_u643();
    init_utils9();
    SHA256_K3 = /* @__PURE__ */ Uint32Array.from([
      1116352408,
      1899447441,
      3049323471,
      3921009573,
      961987163,
      1508970993,
      2453635748,
      2870763221,
      3624381080,
      310598401,
      607225278,
      1426881987,
      1925078388,
      2162078206,
      2614888103,
      3248222580,
      3835390401,
      4022224774,
      264347078,
      604807628,
      770255983,
      1249150122,
      1555081692,
      1996064986,
      2554220882,
      2821834349,
      2952996808,
      3210313671,
      3336571891,
      3584528711,
      113926993,
      338241895,
      666307205,
      773529912,
      1294757372,
      1396182291,
      1695183700,
      1986661051,
      2177026350,
      2456956037,
      2730485921,
      2820302411,
      3259730800,
      3345764771,
      3516065817,
      3600352804,
      4094571909,
      275423344,
      430227734,
      506948616,
      659060556,
      883997877,
      958139571,
      1322822218,
      1537002063,
      1747873779,
      1955562222,
      2024104815,
      2227730452,
      2361852424,
      2428436474,
      2756734187,
      3204031479,
      3329325298
    ]);
    SHA256_W3 = /* @__PURE__ */ new Uint32Array(64);
    SHA2563 = class extends HashMD3 {
      constructor(outputLen = 32) {
        super(64, outputLen, 8, false);
        this.A = SHA256_IV3[0] | 0;
        this.B = SHA256_IV3[1] | 0;
        this.C = SHA256_IV3[2] | 0;
        this.D = SHA256_IV3[3] | 0;
        this.E = SHA256_IV3[4] | 0;
        this.F = SHA256_IV3[5] | 0;
        this.G = SHA256_IV3[6] | 0;
        this.H = SHA256_IV3[7] | 0;
      }
      get() {
        const { A, B, C, D: D2, E, F, G, H } = this;
        return [A, B, C, D2, E, F, G, H];
      }
      // prettier-ignore
      set(A, B, C, D2, E, F, G, H) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D2 | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G | 0;
        this.H = H | 0;
      }
      process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
          SHA256_W3[i] = view.getUint32(offset, false);
        for (let i = 16; i < 64; i++) {
          const W15 = SHA256_W3[i - 15];
          const W2 = SHA256_W3[i - 2];
          const s0 = rotr3(W15, 7) ^ rotr3(W15, 18) ^ W15 >>> 3;
          const s1 = rotr3(W2, 17) ^ rotr3(W2, 19) ^ W2 >>> 10;
          SHA256_W3[i] = s1 + SHA256_W3[i - 7] + s0 + SHA256_W3[i - 16] | 0;
        }
        let { A, B, C, D: D2, E, F, G, H } = this;
        for (let i = 0; i < 64; i++) {
          const sigma1 = rotr3(E, 6) ^ rotr3(E, 11) ^ rotr3(E, 25);
          const T1 = H + sigma1 + Chi3(E, F, G) + SHA256_K3[i] + SHA256_W3[i] | 0;
          const sigma0 = rotr3(A, 2) ^ rotr3(A, 13) ^ rotr3(A, 22);
          const T2 = sigma0 + Maj3(A, B, C) | 0;
          H = G;
          G = F;
          F = E;
          E = D2 + T1 | 0;
          D2 = C;
          C = B;
          B = A;
          A = T1 + T2 | 0;
        }
        A = A + this.A | 0;
        B = B + this.B | 0;
        C = C + this.C | 0;
        D2 = D2 + this.D | 0;
        E = E + this.E | 0;
        F = F + this.F | 0;
        G = G + this.G | 0;
        H = H + this.H | 0;
        this.set(A, B, C, D2, E, F, G, H);
      }
      roundClean() {
        clean3(SHA256_W3);
      }
      destroy() {
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean3(this.buffer);
      }
    };
    K512 = /* @__PURE__ */ (() => split3([
      "0x428a2f98d728ae22",
      "0x7137449123ef65cd",
      "0xb5c0fbcfec4d3b2f",
      "0xe9b5dba58189dbbc",
      "0x3956c25bf348b538",
      "0x59f111f1b605d019",
      "0x923f82a4af194f9b",
      "0xab1c5ed5da6d8118",
      "0xd807aa98a3030242",
      "0x12835b0145706fbe",
      "0x243185be4ee4b28c",
      "0x550c7dc3d5ffb4e2",
      "0x72be5d74f27b896f",
      "0x80deb1fe3b1696b1",
      "0x9bdc06a725c71235",
      "0xc19bf174cf692694",
      "0xe49b69c19ef14ad2",
      "0xefbe4786384f25e3",
      "0x0fc19dc68b8cd5b5",
      "0x240ca1cc77ac9c65",
      "0x2de92c6f592b0275",
      "0x4a7484aa6ea6e483",
      "0x5cb0a9dcbd41fbd4",
      "0x76f988da831153b5",
      "0x983e5152ee66dfab",
      "0xa831c66d2db43210",
      "0xb00327c898fb213f",
      "0xbf597fc7beef0ee4",
      "0xc6e00bf33da88fc2",
      "0xd5a79147930aa725",
      "0x06ca6351e003826f",
      "0x142929670a0e6e70",
      "0x27b70a8546d22ffc",
      "0x2e1b21385c26c926",
      "0x4d2c6dfc5ac42aed",
      "0x53380d139d95b3df",
      "0x650a73548baf63de",
      "0x766a0abb3c77b2a8",
      "0x81c2c92e47edaee6",
      "0x92722c851482353b",
      "0xa2bfe8a14cf10364",
      "0xa81a664bbc423001",
      "0xc24b8b70d0f89791",
      "0xc76c51a30654be30",
      "0xd192e819d6ef5218",
      "0xd69906245565a910",
      "0xf40e35855771202a",
      "0x106aa07032bbd1b8",
      "0x19a4c116b8d2d0c8",
      "0x1e376c085141ab53",
      "0x2748774cdf8eeb99",
      "0x34b0bcb5e19b48a8",
      "0x391c0cb3c5c95a63",
      "0x4ed8aa4ae3418acb",
      "0x5b9cca4f7763e373",
      "0x682e6ff3d6b2b8a3",
      "0x748f82ee5defb2fc",
      "0x78a5636f43172f60",
      "0x84c87814a1f0ab72",
      "0x8cc702081a6439ec",
      "0x90befffa23631e28",
      "0xa4506cebde82bde9",
      "0xbef9a3f7b2c67915",
      "0xc67178f2e372532b",
      "0xca273eceea26619c",
      "0xd186b8c721c0c207",
      "0xeada7dd6cde0eb1e",
      "0xf57d4f7fee6ed178",
      "0x06f067aa72176fba",
      "0x0a637dc5a2c898a6",
      "0x113f9804bef90dae",
      "0x1b710b35131c471b",
      "0x28db77f523047d84",
      "0x32caab7b40c72493",
      "0x3c9ebe0a15c9bebc",
      "0x431d67c49c100d4c",
      "0x4cc5d4becb3e42b6",
      "0x597f299cfc657e2a",
      "0x5fcb6fab3ad6faec",
      "0x6c44198c4a475817"
    ].map((n) => BigInt(n))))();
    SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
    SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
    SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
    SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
    SHA512 = class extends HashMD3 {
      constructor(outputLen = 64) {
        super(128, outputLen, 16, false);
        this.Ah = SHA512_IV3[0] | 0;
        this.Al = SHA512_IV3[1] | 0;
        this.Bh = SHA512_IV3[2] | 0;
        this.Bl = SHA512_IV3[3] | 0;
        this.Ch = SHA512_IV3[4] | 0;
        this.Cl = SHA512_IV3[5] | 0;
        this.Dh = SHA512_IV3[6] | 0;
        this.Dl = SHA512_IV3[7] | 0;
        this.Eh = SHA512_IV3[8] | 0;
        this.El = SHA512_IV3[9] | 0;
        this.Fh = SHA512_IV3[10] | 0;
        this.Fl = SHA512_IV3[11] | 0;
        this.Gh = SHA512_IV3[12] | 0;
        this.Gl = SHA512_IV3[13] | 0;
        this.Hh = SHA512_IV3[14] | 0;
        this.Hl = SHA512_IV3[15] | 0;
      }
      // prettier-ignore
      get() {
        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
      }
      // prettier-ignore
      set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
        this.Ah = Ah | 0;
        this.Al = Al | 0;
        this.Bh = Bh | 0;
        this.Bl = Bl | 0;
        this.Ch = Ch | 0;
        this.Cl = Cl | 0;
        this.Dh = Dh | 0;
        this.Dl = Dl | 0;
        this.Eh = Eh | 0;
        this.El = El | 0;
        this.Fh = Fh | 0;
        this.Fl = Fl | 0;
        this.Gh = Gh | 0;
        this.Gl = Gl | 0;
        this.Hh = Hh | 0;
        this.Hl = Hl | 0;
      }
      process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4) {
          SHA512_W_H[i] = view.getUint32(offset);
          SHA512_W_L[i] = view.getUint32(offset += 4);
        }
        for (let i = 16; i < 80; i++) {
          const W15h = SHA512_W_H[i - 15] | 0;
          const W15l = SHA512_W_L[i - 15] | 0;
          const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
          const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
          const W2h = SHA512_W_H[i - 2] | 0;
          const W2l = SHA512_W_L[i - 2] | 0;
          const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
          const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
          const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
          const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
          SHA512_W_H[i] = SUMh | 0;
          SHA512_W_L[i] = SUMl | 0;
        }
        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        for (let i = 0; i < 80; i++) {
          const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
          const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
          const CHIh = Eh & Fh ^ ~Eh & Gh;
          const CHIl = El & Fl ^ ~El & Gl;
          const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
          const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
          const T1l = T1ll | 0;
          const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
          const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
          const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
          const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
          Hh = Gh | 0;
          Hl = Gl | 0;
          Gh = Fh | 0;
          Gl = Fl | 0;
          Fh = Eh | 0;
          Fl = El | 0;
          ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
          Dh = Ch | 0;
          Dl = Cl | 0;
          Ch = Bh | 0;
          Cl = Bl | 0;
          Bh = Ah | 0;
          Bl = Al | 0;
          const All = add3L(T1l, sigma0l, MAJl);
          Ah = add3H(All, T1h, sigma0h, MAJh);
          Al = All | 0;
        }
        ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
        ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
        ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
        ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
        ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
        ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
        ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
        ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
      }
      roundClean() {
        clean3(SHA512_W_H, SHA512_W_L);
      }
      destroy() {
        clean3(this.buffer);
        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
      }
    };
    sha2565 = /* @__PURE__ */ createHasher4(() => new SHA2563());
    sha512 = /* @__PURE__ */ createHasher4(() => new SHA512());
  }
});

// node_modules/@scure/bip39/node_modules/@scure/base/lib/esm/index.js
function isBytes6(a) {
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
function isArrayOf(isString, arr) {
  if (!Array.isArray(arr))
    return false;
  if (arr.length === 0)
    return true;
  if (isString) {
    return arr.every((item) => typeof item === "string");
  } else {
    return arr.every((item) => Number.isSafeInteger(item));
  }
}
function afn(input) {
  if (typeof input !== "function")
    throw new Error("function expected");
  return true;
}
function astr(label, input) {
  if (typeof input !== "string")
    throw new Error(`${label}: string expected`);
  return true;
}
function anumber4(n) {
  if (!Number.isSafeInteger(n))
    throw new Error(`invalid integer: ${n}`);
}
function aArr(input) {
  if (!Array.isArray(input))
    throw new Error("array expected");
}
function astrArr(label, input) {
  if (!isArrayOf(true, input))
    throw new Error(`${label}: array of strings expected`);
}
function anumArr(label, input) {
  if (!isArrayOf(false, input))
    throw new Error(`${label}: array of numbers expected`);
}
// @__NO_SIDE_EFFECTS__
function chain(...args) {
  const id = (a) => a;
  const wrap3 = (a, b) => (c) => a(b(c));
  const encode4 = args.map((x) => x.encode).reduceRight(wrap3, id);
  const decode2 = args.map((x) => x.decode).reduce(wrap3, id);
  return { encode: encode4, decode: decode2 };
}
// @__NO_SIDE_EFFECTS__
function alphabet(letters) {
  const lettersA = typeof letters === "string" ? letters.split("") : letters;
  const len = lettersA.length;
  astrArr("alphabet", lettersA);
  const indexes = new Map(lettersA.map((l2, i) => [l2, i]));
  return {
    encode: (digits) => {
      aArr(digits);
      return digits.map((i) => {
        if (!Number.isSafeInteger(i) || i < 0 || i >= len)
          throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
        return lettersA[i];
      });
    },
    decode: (input) => {
      aArr(input);
      return input.map((letter) => {
        astr("alphabet.decode", letter);
        const i = indexes.get(letter);
        if (i === void 0)
          throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
        return i;
      });
    }
  };
}
// @__NO_SIDE_EFFECTS__
function join(separator = "") {
  astr("join", separator);
  return {
    encode: (from14) => {
      astrArr("join.decode", from14);
      return from14.join(separator);
    },
    decode: (to) => {
      astr("join.decode", to);
      return to.split(separator);
    }
  };
}
// @__NO_SIDE_EFFECTS__
function padding(bits, chr = "=") {
  anumber4(bits);
  astr("padding", chr);
  return {
    encode(data) {
      astrArr("padding.encode", data);
      while (data.length * bits % 8)
        data.push(chr);
      return data;
    },
    decode(input) {
      astrArr("padding.decode", input);
      let end = input.length;
      if (end * bits % 8)
        throw new Error("padding: invalid, string should have whole number of bytes");
      for (; end > 0 && input[end - 1] === chr; end--) {
        const last = end - 1;
        const byte = last * bits;
        if (byte % 8 === 0)
          throw new Error("padding: invalid, string has too much padding");
      }
      return input.slice(0, end);
    }
  };
}
function convertRadix(data, from14, to) {
  if (from14 < 2)
    throw new Error(`convertRadix: invalid from=${from14}, base cannot be less than 2`);
  if (to < 2)
    throw new Error(`convertRadix: invalid to=${to}, base cannot be less than 2`);
  aArr(data);
  if (!data.length)
    return [];
  let pos = 0;
  const res = [];
  const digits = Array.from(data, (d) => {
    anumber4(d);
    if (d < 0 || d >= from14)
      throw new Error(`invalid integer: ${d}`);
    return d;
  });
  const dlen = digits.length;
  while (true) {
    let carry = 0;
    let done = true;
    for (let i = pos; i < dlen; i++) {
      const digit = digits[i];
      const fromCarry = from14 * carry;
      const digitBase = fromCarry + digit;
      if (!Number.isSafeInteger(digitBase) || fromCarry / from14 !== carry || digitBase - digit !== fromCarry) {
        throw new Error("convertRadix: carry overflow");
      }
      const div = digitBase / to;
      carry = digitBase % to;
      const rounded = Math.floor(div);
      digits[i] = rounded;
      if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
        throw new Error("convertRadix: carry overflow");
      if (!done)
        continue;
      else if (!rounded)
        pos = i;
      else
        done = false;
    }
    res.push(carry);
    if (done)
      break;
  }
  for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
    res.push(0);
  return res.reverse();
}
function convertRadix2(data, from14, to, padding2) {
  aArr(data);
  if (from14 <= 0 || from14 > 32)
    throw new Error(`convertRadix2: wrong from=${from14}`);
  if (to <= 0 || to > 32)
    throw new Error(`convertRadix2: wrong to=${to}`);
  if (/* @__PURE__ */ radix2carry(from14, to) > 32) {
    throw new Error(`convertRadix2: carry overflow from=${from14} to=${to} carryBits=${/* @__PURE__ */ radix2carry(from14, to)}`);
  }
  let carry = 0;
  let pos = 0;
  const max = powers[from14];
  const mask = powers[to] - 1;
  const res = [];
  for (const n of data) {
    anumber4(n);
    if (n >= max)
      throw new Error(`convertRadix2: invalid data word=${n} from=${from14}`);
    carry = carry << from14 | n;
    if (pos + from14 > 32)
      throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from14}`);
    pos += from14;
    for (; pos >= to; pos -= to)
      res.push((carry >> pos - to & mask) >>> 0);
    const pow = powers[pos];
    if (pow === void 0)
      throw new Error("invalid carry");
    carry &= pow - 1;
  }
  carry = carry << to - pos & mask;
  if (!padding2 && pos >= from14)
    throw new Error("Excess padding");
  if (!padding2 && carry > 0)
    throw new Error(`Non-zero padding: ${carry}`);
  if (padding2 && pos > 0)
    res.push(carry >>> 0);
  return res;
}
// @__NO_SIDE_EFFECTS__
function radix(num2) {
  anumber4(num2);
  const _256 = 2 ** 8;
  return {
    encode: (bytes) => {
      if (!isBytes6(bytes))
        throw new Error("radix.encode input should be Uint8Array");
      return convertRadix(Array.from(bytes), _256, num2);
    },
    decode: (digits) => {
      anumArr("radix.decode", digits);
      return Uint8Array.from(convertRadix(digits, num2, _256));
    }
  };
}
// @__NO_SIDE_EFFECTS__
function radix2(bits, revPadding = false) {
  anumber4(bits);
  if (bits <= 0 || bits > 32)
    throw new Error("radix2: bits should be in (0..32]");
  if (/* @__PURE__ */ radix2carry(8, bits) > 32 || /* @__PURE__ */ radix2carry(bits, 8) > 32)
    throw new Error("radix2: carry overflow");
  return {
    encode: (bytes) => {
      if (!isBytes6(bytes))
        throw new Error("radix2.encode input should be Uint8Array");
      return convertRadix2(Array.from(bytes), 8, bits, !revPadding);
    },
    decode: (digits) => {
      anumArr("radix2.decode", digits);
      return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));
    }
  };
}
function checksum3(len, fn) {
  anumber4(len);
  afn(fn);
  return {
    encode(data) {
      if (!isBytes6(data))
        throw new Error("checksum.encode: input should be Uint8Array");
      const sum = fn(data).slice(0, len);
      const res = new Uint8Array(data.length + len);
      res.set(data);
      res.set(sum, data.length);
      return res;
    },
    decode(data) {
      if (!isBytes6(data))
        throw new Error("checksum.decode: input should be Uint8Array");
      const payload = data.slice(0, -len);
      const oldChecksum = data.slice(-len);
      const newChecksum = fn(payload).slice(0, len);
      for (let i = 0; i < len; i++)
        if (newChecksum[i] !== oldChecksum[i])
          throw new Error("Invalid checksum");
      return payload;
    }
  };
}
var gcd, radix2carry, powers, utils;
var init_esm2 = __esm({
  "node_modules/@scure/bip39/node_modules/@scure/base/lib/esm/index.js"() {
    "use strict";
    gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
    radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from14, to) => from14 + (to - gcd(from14, to));
    powers = /* @__PURE__ */ (() => {
      let res = [];
      for (let i = 0; i < 40; i++)
        res.push(2 ** i);
      return res;
    })();
    utils = {
      alphabet,
      chain,
      checksum: checksum3,
      convertRadix,
      convertRadix2,
      radix,
      radix2,
      join,
      padding
    };
  }
});

// node_modules/@scure/bip39/esm/index.js
function nfkd(str) {
  if (typeof str !== "string")
    throw new TypeError("invalid mnemonic type: " + typeof str);
  return str.normalize("NFKD");
}
function normalize(str) {
  const norm = nfkd(str);
  const words = norm.split(" ");
  if (![12, 15, 18, 21, 24].includes(words.length))
    throw new Error("Invalid mnemonic");
  return { nfkd: norm, words };
}
function aentropy(ent) {
  abytes5(ent, 16, 20, 24, 28, 32);
}
function generateMnemonic(wordlist2, strength = 128) {
  anumber3(strength);
  if (strength % 32 !== 0 || strength > 256)
    throw new TypeError("Invalid entropy");
  return entropyToMnemonic(randomBytes3(strength / 8), wordlist2);
}
function getCoder(wordlist2) {
  if (!Array.isArray(wordlist2) || wordlist2.length !== 2048 || typeof wordlist2[0] !== "string")
    throw new Error("Wordlist: expected array of 2048 strings");
  wordlist2.forEach((i) => {
    if (typeof i !== "string")
      throw new Error("wordlist: non-string element: " + i);
  });
  return utils.chain(utils.checksum(1, calcChecksum), utils.radix2(11, true), utils.alphabet(wordlist2));
}
function mnemonicToEntropy(mnemonic, wordlist2) {
  const { words } = normalize(mnemonic);
  const entropy = getCoder(wordlist2).decode(words);
  aentropy(entropy);
  return entropy;
}
function entropyToMnemonic(entropy, wordlist2) {
  aentropy(entropy);
  const words = getCoder(wordlist2).encode(entropy);
  return words.join(isJapanese(wordlist2) ? "\u3000" : " ");
}
function validateMnemonic(mnemonic, wordlist2) {
  try {
    mnemonicToEntropy(mnemonic, wordlist2);
  } catch (e7) {
    return false;
  }
  return true;
}
function mnemonicToSeedSync(mnemonic, passphrase = "") {
  return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { c: 2048, dkLen: 64 });
}
var isJapanese, calcChecksum, psalt;
var init_esm3 = __esm({
  "node_modules/@scure/bip39/esm/index.js"() {
    "use strict";
    init_pbkdf2();
    init_sha23();
    init_utils9();
    init_esm2();
    isJapanese = (wordlist2) => wordlist2[0] === "\u3042\u3044\u3053\u304F\u3057\u3093";
    calcChecksum = (entropy) => {
      const bitsLeft = 8 - entropy.length / 4;
      return new Uint8Array([sha2565(entropy)[0] >> bitsLeft << bitsLeft]);
    };
    psalt = (passphrase) => nfkd("mnemonic" + passphrase);
  }
});

// node_modules/viem/_esm/accounts/toAccount.js
function toAccount(source) {
  if (typeof source === "string") {
    if (!isAddress(source, { strict: false }))
      throw new InvalidAddressError({ address: source });
    return {
      address: source,
      type: "json-rpc"
    };
  }
  if (!isAddress(source.address, { strict: false }))
    throw new InvalidAddressError({ address: source.address });
  return {
    address: source.address,
    nonceManager: source.nonceManager,
    sign: source.sign,
    signAuthorization: source.signAuthorization,
    signMessage: source.signMessage,
    signTransaction: source.signTransaction,
    signTypedData: source.signTypedData,
    source: "custom",
    type: "local"
  };
}
var init_toAccount = __esm({
  "node_modules/viem/_esm/accounts/toAccount.js"() {
    "use strict";
    init_address();
    init_isAddress();
  }
});

// node_modules/viem/_esm/accounts/utils/sign.js
async function sign({ hash: hash3, privateKey, to = "object" }) {
  const { r, s: s3, recovery } = secp256k1.sign(hash3.slice(2), privateKey.slice(2), {
    lowS: true,
    extraEntropy: isHex(extraEntropy, { strict: false }) ? hexToBytes(extraEntropy) : extraEntropy
  });
  const signature2 = {
    r: numberToHex(r, { size: 32 }),
    s: numberToHex(s3, { size: 32 }),
    v: recovery ? 28n : 27n,
    yParity: recovery
  };
  return (() => {
    if (to === "bytes" || to === "hex")
      return serializeSignature({ ...signature2, to });
    return signature2;
  })();
}
var extraEntropy;
var init_sign = __esm({
  "node_modules/viem/_esm/accounts/utils/sign.js"() {
    "use strict";
    init_secp256k1();
    init_isHex();
    init_toBytes();
    init_toHex();
    init_serializeSignature();
    extraEntropy = false;
  }
});

// node_modules/viem/_esm/accounts/utils/signAuthorization.js
async function signAuthorization(parameters) {
  const { chainId, nonce, privateKey, to = "object" } = parameters;
  const address2 = parameters.contractAddress ?? parameters.address;
  const signature2 = await sign({
    hash: hashAuthorization({ address: address2, chainId, nonce }),
    privateKey,
    to
  });
  if (to === "object")
    return {
      address: address2,
      chainId,
      nonce,
      ...signature2
    };
  return signature2;
}
var init_signAuthorization = __esm({
  "node_modules/viem/_esm/accounts/utils/signAuthorization.js"() {
    "use strict";
    init_hashAuthorization();
    init_sign();
  }
});

// node_modules/viem/_esm/accounts/utils/signMessage.js
async function signMessage({ message, privateKey }) {
  return await sign({ hash: hashMessage(message), privateKey, to: "hex" });
}
var init_signMessage = __esm({
  "node_modules/viem/_esm/accounts/utils/signMessage.js"() {
    "use strict";
    init_hashMessage();
    init_sign();
  }
});

// node_modules/viem/_esm/accounts/utils/signTransaction.js
async function signTransaction(parameters) {
  const { privateKey, transaction, serializer = serializeTransaction } = parameters;
  const signableTransaction = (() => {
    if (transaction.type === "eip4844")
      return {
        ...transaction,
        sidecars: false
      };
    return transaction;
  })();
  const signature2 = await sign({
    hash: keccak256(await serializer(signableTransaction)),
    privateKey
  });
  return await serializer(transaction, signature2);
}
var init_signTransaction = __esm({
  "node_modules/viem/_esm/accounts/utils/signTransaction.js"() {
    "use strict";
    init_keccak256();
    init_serializeTransaction();
    init_sign();
  }
});

// node_modules/viem/_esm/accounts/utils/signTypedData.js
async function signTypedData(parameters) {
  const { privateKey, ...typedData } = parameters;
  return await sign({
    hash: hashTypedData(typedData),
    privateKey,
    to: "hex"
  });
}
var init_signTypedData = __esm({
  "node_modules/viem/_esm/accounts/utils/signTypedData.js"() {
    "use strict";
    init_hashTypedData();
    init_sign();
  }
});

// node_modules/viem/_esm/accounts/privateKeyToAccount.js
function privateKeyToAccount(privateKey, options = {}) {
  const { nonceManager } = options;
  const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false));
  const address2 = publicKeyToAddress(publicKey);
  const account = toAccount({
    address: address2,
    nonceManager,
    async sign({ hash: hash3 }) {
      return sign({ hash: hash3, privateKey, to: "hex" });
    },
    async signAuthorization(authorization) {
      return signAuthorization({ ...authorization, privateKey });
    },
    async signMessage({ message }) {
      return signMessage({ message, privateKey });
    },
    async signTransaction(transaction, { serializer } = {}) {
      return signTransaction({ privateKey, transaction, serializer });
    },
    async signTypedData(typedData) {
      return signTypedData({ ...typedData, privateKey });
    }
  });
  return {
    ...account,
    publicKey,
    source: "privateKey"
  };
}
var init_privateKeyToAccount = __esm({
  "node_modules/viem/_esm/accounts/privateKeyToAccount.js"() {
    "use strict";
    init_secp256k1();
    init_toHex();
    init_toAccount();
    init_publicKeyToAddress();
    init_sign();
    init_signAuthorization();
    init_signMessage();
    init_signTransaction();
    init_signTypedData();
  }
});

// node_modules/@scure/bip39/esm/wordlists/english.js
var wordlist;
var init_english = __esm({
  "node_modules/@scure/bip39/esm/wordlists/english.js"() {
    "use strict";
    wordlist = `abandon
ability
able
about
above
absent
absorb
abstract
absurd
abuse
access
accident
account
accuse
achieve
acid
acoustic
acquire
across
act
action
actor
actress
actual
adapt
add
addict
address
adjust
admit
adult
advance
advice
aerobic
affair
afford
afraid
again
age
agent
agree
ahead
aim
air
airport
aisle
alarm
album
alcohol
alert
alien
all
alley
allow
almost
alone
alpha
already
also
alter
always
amateur
amazing
among
amount
amused
analyst
anchor
ancient
anger
angle
angry
animal
ankle
announce
annual
another
answer
antenna
antique
anxiety
any
apart
apology
appear
apple
approve
april
arch
arctic
area
arena
argue
arm
armed
armor
army
around
arrange
arrest
arrive
arrow
art
artefact
artist
artwork
ask
aspect
assault
asset
assist
assume
asthma
athlete
atom
attack
attend
attitude
attract
auction
audit
august
aunt
author
auto
autumn
average
avocado
avoid
awake
aware
away
awesome
awful
awkward
axis
baby
bachelor
bacon
badge
bag
balance
balcony
ball
bamboo
banana
banner
bar
barely
bargain
barrel
base
basic
basket
battle
beach
bean
beauty
because
become
beef
before
begin
behave
behind
believe
below
belt
bench
benefit
best
betray
better
between
beyond
bicycle
bid
bike
bind
biology
bird
birth
bitter
black
blade
blame
blanket
blast
bleak
bless
blind
blood
blossom
blouse
blue
blur
blush
board
boat
body
boil
bomb
bone
bonus
book
boost
border
boring
borrow
boss
bottom
bounce
box
boy
bracket
brain
brand
brass
brave
bread
breeze
brick
bridge
brief
bright
bring
brisk
broccoli
broken
bronze
broom
brother
brown
brush
bubble
buddy
budget
buffalo
build
bulb
bulk
bullet
bundle
bunker
burden
burger
burst
bus
business
busy
butter
buyer
buzz
cabbage
cabin
cable
cactus
cage
cake
call
calm
camera
camp
can
canal
cancel
candy
cannon
canoe
canvas
canyon
capable
capital
captain
car
carbon
card
cargo
carpet
carry
cart
case
cash
casino
castle
casual
cat
catalog
catch
category
cattle
caught
cause
caution
cave
ceiling
celery
cement
census
century
cereal
certain
chair
chalk
champion
change
chaos
chapter
charge
chase
chat
cheap
check
cheese
chef
cherry
chest
chicken
chief
child
chimney
choice
choose
chronic
chuckle
chunk
churn
cigar
cinnamon
circle
citizen
city
civil
claim
clap
clarify
claw
clay
clean
clerk
clever
click
client
cliff
climb
clinic
clip
clock
clog
close
cloth
cloud
clown
club
clump
cluster
clutch
coach
coast
coconut
code
coffee
coil
coin
collect
color
column
combine
come
comfort
comic
common
company
concert
conduct
confirm
congress
connect
consider
control
convince
cook
cool
copper
copy
coral
core
corn
correct
cost
cotton
couch
country
couple
course
cousin
cover
coyote
crack
cradle
craft
cram
crane
crash
crater
crawl
crazy
cream
credit
creek
crew
cricket
crime
crisp
critic
crop
cross
crouch
crowd
crucial
cruel
cruise
crumble
crunch
crush
cry
crystal
cube
culture
cup
cupboard
curious
current
curtain
curve
cushion
custom
cute
cycle
dad
damage
damp
dance
danger
daring
dash
daughter
dawn
day
deal
debate
debris
decade
december
decide
decline
decorate
decrease
deer
defense
define
defy
degree
delay
deliver
demand
demise
denial
dentist
deny
depart
depend
deposit
depth
deputy
derive
describe
desert
design
desk
despair
destroy
detail
detect
develop
device
devote
diagram
dial
diamond
diary
dice
diesel
diet
differ
digital
dignity
dilemma
dinner
dinosaur
direct
dirt
disagree
discover
disease
dish
dismiss
disorder
display
distance
divert
divide
divorce
dizzy
doctor
document
dog
doll
dolphin
domain
donate
donkey
donor
door
dose
double
dove
draft
dragon
drama
drastic
draw
dream
dress
drift
drill
drink
drip
drive
drop
drum
dry
duck
dumb
dune
during
dust
dutch
duty
dwarf
dynamic
eager
eagle
early
earn
earth
easily
east
easy
echo
ecology
economy
edge
edit
educate
effort
egg
eight
either
elbow
elder
electric
elegant
element
elephant
elevator
elite
else
embark
embody
embrace
emerge
emotion
employ
empower
empty
enable
enact
end
endless
endorse
enemy
energy
enforce
engage
engine
enhance
enjoy
enlist
enough
enrich
enroll
ensure
enter
entire
entry
envelope
episode
equal
equip
era
erase
erode
erosion
error
erupt
escape
essay
essence
estate
eternal
ethics
evidence
evil
evoke
evolve
exact
example
excess
exchange
excite
exclude
excuse
execute
exercise
exhaust
exhibit
exile
exist
exit
exotic
expand
expect
expire
explain
expose
express
extend
extra
eye
eyebrow
fabric
face
faculty
fade
faint
faith
fall
false
fame
family
famous
fan
fancy
fantasy
farm
fashion
fat
fatal
father
fatigue
fault
favorite
feature
february
federal
fee
feed
feel
female
fence
festival
fetch
fever
few
fiber
fiction
field
figure
file
film
filter
final
find
fine
finger
finish
fire
firm
first
fiscal
fish
fit
fitness
fix
flag
flame
flash
flat
flavor
flee
flight
flip
float
flock
floor
flower
fluid
flush
fly
foam
focus
fog
foil
fold
follow
food
foot
force
forest
forget
fork
fortune
forum
forward
fossil
foster
found
fox
fragile
frame
frequent
fresh
friend
fringe
frog
front
frost
frown
frozen
fruit
fuel
fun
funny
furnace
fury
future
gadget
gain
galaxy
gallery
game
gap
garage
garbage
garden
garlic
garment
gas
gasp
gate
gather
gauge
gaze
general
genius
genre
gentle
genuine
gesture
ghost
giant
gift
giggle
ginger
giraffe
girl
give
glad
glance
glare
glass
glide
glimpse
globe
gloom
glory
glove
glow
glue
goat
goddess
gold
good
goose
gorilla
gospel
gossip
govern
gown
grab
grace
grain
grant
grape
grass
gravity
great
green
grid
grief
grit
grocery
group
grow
grunt
guard
guess
guide
guilt
guitar
gun
gym
habit
hair
half
hammer
hamster
hand
happy
harbor
hard
harsh
harvest
hat
have
hawk
hazard
head
health
heart
heavy
hedgehog
height
hello
helmet
help
hen
hero
hidden
high
hill
hint
hip
hire
history
hobby
hockey
hold
hole
holiday
hollow
home
honey
hood
hope
horn
horror
horse
hospital
host
hotel
hour
hover
hub
huge
human
humble
humor
hundred
hungry
hunt
hurdle
hurry
hurt
husband
hybrid
ice
icon
idea
identify
idle
ignore
ill
illegal
illness
image
imitate
immense
immune
impact
impose
improve
impulse
inch
include
income
increase
index
indicate
indoor
industry
infant
inflict
inform
inhale
inherit
initial
inject
injury
inmate
inner
innocent
input
inquiry
insane
insect
inside
inspire
install
intact
interest
into
invest
invite
involve
iron
island
isolate
issue
item
ivory
jacket
jaguar
jar
jazz
jealous
jeans
jelly
jewel
job
join
joke
journey
joy
judge
juice
jump
jungle
junior
junk
just
kangaroo
keen
keep
ketchup
key
kick
kid
kidney
kind
kingdom
kiss
kit
kitchen
kite
kitten
kiwi
knee
knife
knock
know
lab
label
labor
ladder
lady
lake
lamp
language
laptop
large
later
latin
laugh
laundry
lava
law
lawn
lawsuit
layer
lazy
leader
leaf
learn
leave
lecture
left
leg
legal
legend
leisure
lemon
lend
length
lens
leopard
lesson
letter
level
liar
liberty
library
license
life
lift
light
like
limb
limit
link
lion
liquid
list
little
live
lizard
load
loan
lobster
local
lock
logic
lonely
long
loop
lottery
loud
lounge
love
loyal
lucky
luggage
lumber
lunar
lunch
luxury
lyrics
machine
mad
magic
magnet
maid
mail
main
major
make
mammal
man
manage
mandate
mango
mansion
manual
maple
marble
march
margin
marine
market
marriage
mask
mass
master
match
material
math
matrix
matter
maximum
maze
meadow
mean
measure
meat
mechanic
medal
media
melody
melt
member
memory
mention
menu
mercy
merge
merit
merry
mesh
message
metal
method
middle
midnight
milk
million
mimic
mind
minimum
minor
minute
miracle
mirror
misery
miss
mistake
mix
mixed
mixture
mobile
model
modify
mom
moment
monitor
monkey
monster
month
moon
moral
more
morning
mosquito
mother
motion
motor
mountain
mouse
move
movie
much
muffin
mule
multiply
muscle
museum
mushroom
music
must
mutual
myself
mystery
myth
naive
name
napkin
narrow
nasty
nation
nature
near
neck
need
negative
neglect
neither
nephew
nerve
nest
net
network
neutral
never
news
next
nice
night
noble
noise
nominee
noodle
normal
north
nose
notable
note
nothing
notice
novel
now
nuclear
number
nurse
nut
oak
obey
object
oblige
obscure
observe
obtain
obvious
occur
ocean
october
odor
off
offer
office
often
oil
okay
old
olive
olympic
omit
once
one
onion
online
only
open
opera
opinion
oppose
option
orange
orbit
orchard
order
ordinary
organ
orient
original
orphan
ostrich
other
outdoor
outer
output
outside
oval
oven
over
own
owner
oxygen
oyster
ozone
pact
paddle
page
pair
palace
palm
panda
panel
panic
panther
paper
parade
parent
park
parrot
party
pass
patch
path
patient
patrol
pattern
pause
pave
payment
peace
peanut
pear
peasant
pelican
pen
penalty
pencil
people
pepper
perfect
permit
person
pet
phone
photo
phrase
physical
piano
picnic
picture
piece
pig
pigeon
pill
pilot
pink
pioneer
pipe
pistol
pitch
pizza
place
planet
plastic
plate
play
please
pledge
pluck
plug
plunge
poem
poet
point
polar
pole
police
pond
pony
pool
popular
portion
position
possible
post
potato
pottery
poverty
powder
power
practice
praise
predict
prefer
prepare
present
pretty
prevent
price
pride
primary
print
priority
prison
private
prize
problem
process
produce
profit
program
project
promote
proof
property
prosper
protect
proud
provide
public
pudding
pull
pulp
pulse
pumpkin
punch
pupil
puppy
purchase
purity
purpose
purse
push
put
puzzle
pyramid
quality
quantum
quarter
question
quick
quit
quiz
quote
rabbit
raccoon
race
rack
radar
radio
rail
rain
raise
rally
ramp
ranch
random
range
rapid
rare
rate
rather
raven
raw
razor
ready
real
reason
rebel
rebuild
recall
receive
recipe
record
recycle
reduce
reflect
reform
refuse
region
regret
regular
reject
relax
release
relief
rely
remain
remember
remind
remove
render
renew
rent
reopen
repair
repeat
replace
report
require
rescue
resemble
resist
resource
response
result
retire
retreat
return
reunion
reveal
review
reward
rhythm
rib
ribbon
rice
rich
ride
ridge
rifle
right
rigid
ring
riot
ripple
risk
ritual
rival
river
road
roast
robot
robust
rocket
romance
roof
rookie
room
rose
rotate
rough
round
route
royal
rubber
rude
rug
rule
run
runway
rural
sad
saddle
sadness
safe
sail
salad
salmon
salon
salt
salute
same
sample
sand
satisfy
satoshi
sauce
sausage
save
say
scale
scan
scare
scatter
scene
scheme
school
science
scissors
scorpion
scout
scrap
screen
script
scrub
sea
search
season
seat
second
secret
section
security
seed
seek
segment
select
sell
seminar
senior
sense
sentence
series
service
session
settle
setup
seven
shadow
shaft
shallow
share
shed
shell
sheriff
shield
shift
shine
ship
shiver
shock
shoe
shoot
shop
short
shoulder
shove
shrimp
shrug
shuffle
shy
sibling
sick
side
siege
sight
sign
silent
silk
silly
silver
similar
simple
since
sing
siren
sister
situate
six
size
skate
sketch
ski
skill
skin
skirt
skull
slab
slam
sleep
slender
slice
slide
slight
slim
slogan
slot
slow
slush
small
smart
smile
smoke
smooth
snack
snake
snap
sniff
snow
soap
soccer
social
sock
soda
soft
solar
soldier
solid
solution
solve
someone
song
soon
sorry
sort
soul
sound
soup
source
south
space
spare
spatial
spawn
speak
special
speed
spell
spend
sphere
spice
spider
spike
spin
spirit
split
spoil
sponsor
spoon
sport
spot
spray
spread
spring
spy
square
squeeze
squirrel
stable
stadium
staff
stage
stairs
stamp
stand
start
state
stay
steak
steel
stem
step
stereo
stick
still
sting
stock
stomach
stone
stool
story
stove
strategy
street
strike
strong
struggle
student
stuff
stumble
style
subject
submit
subway
success
such
sudden
suffer
sugar
suggest
suit
summer
sun
sunny
sunset
super
supply
supreme
sure
surface
surge
surprise
surround
survey
suspect
sustain
swallow
swamp
swap
swarm
swear
sweet
swift
swim
swing
switch
sword
symbol
symptom
syrup
system
table
tackle
tag
tail
talent
talk
tank
tape
target
task
taste
tattoo
taxi
teach
team
tell
ten
tenant
tennis
tent
term
test
text
thank
that
theme
then
theory
there
they
thing
this
thought
three
thrive
throw
thumb
thunder
ticket
tide
tiger
tilt
timber
time
tiny
tip
tired
tissue
title
toast
tobacco
today
toddler
toe
together
toilet
token
tomato
tomorrow
tone
tongue
tonight
tool
tooth
top
topic
topple
torch
tornado
tortoise
toss
total
tourist
toward
tower
town
toy
track
trade
traffic
tragic
train
transfer
trap
trash
travel
tray
treat
tree
trend
trial
tribe
trick
trigger
trim
trip
trophy
trouble
truck
true
truly
trumpet
trust
truth
try
tube
tuition
tumble
tuna
tunnel
turkey
turn
turtle
twelve
twenty
twice
twin
twist
two
type
typical
ugly
umbrella
unable
unaware
uncle
uncover
under
undo
unfair
unfold
unhappy
uniform
unique
unit
universe
unknown
unlock
until
unusual
unveil
update
upgrade
uphold
upon
upper
upset
urban
urge
usage
use
used
useful
useless
usual
utility
vacant
vacuum
vague
valid
valley
valve
van
vanish
vapor
various
vast
vault
vehicle
velvet
vendor
venture
venue
verb
verify
version
very
vessel
veteran
viable
vibrant
vicious
victory
video
view
village
vintage
violin
virtual
virus
visa
visit
visual
vital
vivid
vocal
voice
void
volcano
volume
vote
voyage
wage
wagon
wait
walk
wall
walnut
want
warfare
warm
warrior
wash
wasp
waste
water
wave
way
wealth
weapon
wear
weasel
weather
web
wedding
weekend
weird
welcome
west
wet
whale
what
wheat
wheel
when
where
whip
whisper
wide
width
wife
wild
will
win
window
wine
wing
wink
winner
winter
wire
wisdom
wise
wish
witness
wolf
woman
wonder
wood
wool
word
work
world
worry
worth
wrap
wreck
wrestle
wrist
write
wrong
yard
year
yellow
you
young
youth
zebra
zero
zone
zoo`.split("\n");
  }
});

// node_modules/viem/_esm/accounts/index.js
var init_accounts = __esm({
  "node_modules/viem/_esm/accounts/index.js"() {
    "use strict";
    init_privateKeyToAccount();
  }
});

// node_modules/zod/v3/helpers/util.js
var util, objectUtil, ZodParsedType, getParsedType;
var init_util = __esm({
  "node_modules/zod/v3/helpers/util.js"() {
    "use strict";
    (function(util2) {
      util2.assertEqual = (_) => {
      };
      function assertIs(_arg) {
      }
      util2.assertIs = assertIs;
      function assertNever(_x) {
        throw new Error();
      }
      util2.assertNever = assertNever;
      util2.arrayToEnum = (items) => {
        const obj = {};
        for (const item of items) {
          obj[item] = item;
        }
        return obj;
      };
      util2.getValidEnumValues = (obj) => {
        const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
        const filtered = {};
        for (const k of validKeys) {
          filtered[k] = obj[k];
        }
        return util2.objectValues(filtered);
      };
      util2.objectValues = (obj) => {
        return util2.objectKeys(obj).map(function(e7) {
          return obj[e7];
        });
      };
      util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
        const keys = [];
        for (const key in object) {
          if (Object.prototype.hasOwnProperty.call(object, key)) {
            keys.push(key);
          }
        }
        return keys;
      };
      util2.find = (arr, checker) => {
        for (const item of arr) {
          if (checker(item))
            return item;
        }
        return void 0;
      };
      util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
      function joinValues(array, separator = " | ") {
        return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
      }
      util2.joinValues = joinValues;
      util2.jsonStringifyReplacer = (_, value) => {
        if (typeof value === "bigint") {
          return value.toString();
        }
        return value;
      };
    })(util || (util = {}));
    (function(objectUtil2) {
      objectUtil2.mergeShapes = (first, second) => {
        return {
          ...first,
          ...second
          // second overwrites first
        };
      };
    })(objectUtil || (objectUtil = {}));
    ZodParsedType = util.arrayToEnum([
      "string",
      "nan",
      "number",
      "integer",
      "float",
      "boolean",
      "date",
      "bigint",
      "symbol",
      "function",
      "undefined",
      "null",
      "array",
      "object",
      "unknown",
      "promise",
      "void",
      "never",
      "map",
      "set"
    ]);
    getParsedType = (data) => {
      const t = typeof data;
      switch (t) {
        case "undefined":
          return ZodParsedType.undefined;
        case "string":
          return ZodParsedType.string;
        case "number":
          return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
        case "boolean":
          return ZodParsedType.boolean;
        case "function":
          return ZodParsedType.function;
        case "bigint":
          return ZodParsedType.bigint;
        case "symbol":
          return ZodParsedType.symbol;
        case "object":
          if (Array.isArray(data)) {
            return ZodParsedType.array;
          }
          if (data === null) {
            return ZodParsedType.null;
          }
          if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
            return ZodParsedType.promise;
          }
          if (typeof Map !== "undefined" && data instanceof Map) {
            return ZodParsedType.map;
          }
          if (typeof Set !== "undefined" && data instanceof Set) {
            return ZodParsedType.set;
          }
          if (typeof Date !== "undefined" && data instanceof Date) {
            return ZodParsedType.date;
          }
          return ZodParsedType.object;
        default:
          return ZodParsedType.unknown;
      }
    };
  }
});

// node_modules/zod/v3/ZodError.js
var ZodIssueCode, quotelessJson, ZodError;
var init_ZodError = __esm({
  "node_modules/zod/v3/ZodError.js"() {
    "use strict";
    init_util();
    ZodIssueCode = util.arrayToEnum([
      "invalid_type",
      "invalid_literal",
      "custom",
      "invalid_union",
      "invalid_union_discriminator",
      "invalid_enum_value",
      "unrecognized_keys",
      "invalid_arguments",
      "invalid_return_type",
      "invalid_date",
      "invalid_string",
      "too_small",
      "too_big",
      "invalid_intersection_types",
      "not_multiple_of",
      "not_finite"
    ]);
    quotelessJson = (obj) => {
      const json = JSON.stringify(obj, null, 2);
      return json.replace(/"([^"]+)":/g, "$1:");
    };
    ZodError = class _ZodError extends Error {
      get errors() {
        return this.issues;
      }
      constructor(issues) {
        super();
        this.issues = [];
        this.addIssue = (sub) => {
          this.issues = [...this.issues, sub];
        };
        this.addIssues = (subs = []) => {
          this.issues = [...this.issues, ...subs];
        };
        const actualProto = new.target.prototype;
        if (Object.setPrototypeOf) {
          Object.setPrototypeOf(this, actualProto);
        } else {
          this.__proto__ = actualProto;
        }
        this.name = "ZodError";
        this.issues = issues;
      }
      format(_mapper) {
        const mapper = _mapper || function(issue) {
          return issue.message;
        };
        const fieldErrors = { _errors: [] };
        const processError = (error) => {
          for (const issue of error.issues) {
            if (issue.code === "invalid_union") {
              issue.unionErrors.map(processError);
            } else if (issue.code === "invalid_return_type") {
              processError(issue.returnTypeError);
            } else if (issue.code === "invalid_arguments") {
              processError(issue.argumentsError);
            } else if (issue.path.length === 0) {
              fieldErrors._errors.push(mapper(issue));
            } else {
              let curr = fieldErrors;
              let i = 0;
              while (i < issue.path.length) {
                const el = issue.path[i];
                const terminal = i === issue.path.length - 1;
                if (!terminal) {
                  curr[el] = curr[el] || { _errors: [] };
                } else {
                  curr[el] = curr[el] || { _errors: [] };
                  curr[el]._errors.push(mapper(issue));
                }
                curr = curr[el];
                i++;
              }
            }
          }
        };
        processError(this);
        return fieldErrors;
      }
      static assert(value) {
        if (!(value instanceof _ZodError)) {
          throw new Error(`Not a ZodError: ${value}`);
        }
      }
      toString() {
        return this.message;
      }
      get message() {
        return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
      }
      get isEmpty() {
        return this.issues.length === 0;
      }
      flatten(mapper = (issue) => issue.message) {
        const fieldErrors = {};
        const formErrors = [];
        for (const sub of this.issues) {
          if (sub.path.length > 0) {
            const firstEl = sub.path[0];
            fieldErrors[firstEl] = fieldErrors[firstEl] || [];
            fieldErrors[firstEl].push(mapper(sub));
          } else {
            formErrors.push(mapper(sub));
          }
        }
        return { formErrors, fieldErrors };
      }
      get formErrors() {
        return this.flatten();
      }
    };
    ZodError.create = (issues) => {
      const error = new ZodError(issues);
      return error;
    };
  }
});

// node_modules/zod/v3/locales/en.js
var errorMap, en_default;
var init_en = __esm({
  "node_modules/zod/v3/locales/en.js"() {
    "use strict";
    init_ZodError();
    init_util();
    errorMap = (issue, _ctx) => {
      let message;
      switch (issue.code) {
        case ZodIssueCode.invalid_type:
          if (issue.received === ZodParsedType.undefined) {
            message = "Required";
          } else {
            message = `Expected ${issue.expected}, received ${issue.received}`;
          }
          break;
        case ZodIssueCode.invalid_literal:
          message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
          break;
        case ZodIssueCode.unrecognized_keys:
          message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
          break;
        case ZodIssueCode.invalid_union:
          message = `Invalid input`;
          break;
        case ZodIssueCode.invalid_union_discriminator:
          message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
          break;
        case ZodIssueCode.invalid_enum_value:
          message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
          break;
        case ZodIssueCode.invalid_arguments:
          message = `Invalid function arguments`;
          break;
        case ZodIssueCode.invalid_return_type:
          message = `Invalid function return type`;
          break;
        case ZodIssueCode.invalid_date:
          message = `Invalid date`;
          break;
        case ZodIssueCode.invalid_string:
          if (typeof issue.validation === "object") {
            if ("includes" in issue.validation) {
              message = `Invalid input: must include "${issue.validation.includes}"`;
              if (typeof issue.validation.position === "number") {
                message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
              }
            } else if ("startsWith" in issue.validation) {
              message = `Invalid input: must start with "${issue.validation.startsWith}"`;
            } else if ("endsWith" in issue.validation) {
              message = `Invalid input: must end with "${issue.validation.endsWith}"`;
            } else {
              util.assertNever(issue.validation);
            }
          } else if (issue.validation !== "regex") {
            message = `Invalid ${issue.validation}`;
          } else {
            message = "Invalid";
          }
          break;
        case ZodIssueCode.too_small:
          if (issue.type === "array")
            message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
          else if (issue.type === "string")
            message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
          else if (issue.type === "number")
            message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
          else if (issue.type === "bigint")
            message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
          else if (issue.type === "date")
            message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
          else
            message = "Invalid input";
          break;
        case ZodIssueCode.too_big:
          if (issue.type === "array")
            message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
          else if (issue.type === "string")
            message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
          else if (issue.type === "number")
            message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
          else if (issue.type === "bigint")
            message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
          else if (issue.type === "date")
            message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
          else
            message = "Invalid input";
          break;
        case ZodIssueCode.custom:
          message = `Invalid input`;
          break;
        case ZodIssueCode.invalid_intersection_types:
          message = `Intersection results could not be merged`;
          break;
        case ZodIssueCode.not_multiple_of:
          message = `Number must be a multiple of ${issue.multipleOf}`;
          break;
        case ZodIssueCode.not_finite:
          message = "Number must be finite";
          break;
        default:
          message = _ctx.defaultError;
          util.assertNever(issue);
      }
      return { message };
    };
    en_default = errorMap;
  }
});

// node_modules/zod/v3/errors.js
function setErrorMap(map) {
  overrideErrorMap = map;
}
function getErrorMap() {
  return overrideErrorMap;
}
var overrideErrorMap;
var init_errors4 = __esm({
  "node_modules/zod/v3/errors.js"() {
    "use strict";
    init_en();
    overrideErrorMap = en_default;
  }
});

// node_modules/zod/v3/helpers/parseUtil.js
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      // contextual error map is first priority
      ctx.schemaErrorMap,
      // then schema-bound map if available
      overrideMap,
      // then global override map
      overrideMap === en_default ? void 0 : en_default
      // then global default map
    ].filter((x) => !!x)
  });
  ctx.common.issues.push(issue);
}
var makeIssue, EMPTY_PATH, ParseStatus, INVALID, DIRTY, OK, isAborted, isDirty, isValid, isAsync;
var init_parseUtil = __esm({
  "node_modules/zod/v3/helpers/parseUtil.js"() {
    "use strict";
    init_errors4();
    init_en();
    makeIssue = (params) => {
      const { data, path: path2, errorMaps, issueData } = params;
      const fullPath = [...path2, ...issueData.path || []];
      const fullIssue = {
        ...issueData,
        path: fullPath
      };
      if (issueData.message !== void 0) {
        return {
          ...issueData,
          path: fullPath,
          message: issueData.message
        };
      }
      let errorMessage = "";
      const maps = errorMaps.filter((m) => !!m).slice().reverse();
      for (const map of maps) {
        errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
      }
      return {
        ...issueData,
        path: fullPath,
        message: errorMessage
      };
    };
    EMPTY_PATH = [];
    ParseStatus = class _ParseStatus {
      constructor() {
        this.value = "valid";
      }
      dirty() {
        if (this.value === "valid")
          this.value = "dirty";
      }
      abort() {
        if (this.value !== "aborted")
          this.value = "aborted";
      }
      static mergeArray(status, results) {
        const arrayValue = [];
        for (const s3 of results) {
          if (s3.status === "aborted")
            return INVALID;
          if (s3.status === "dirty")
            status.dirty();
          arrayValue.push(s3.value);
        }
        return { status: status.value, value: arrayValue };
      }
      static async mergeObjectAsync(status, pairs) {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value
          });
        }
        return _ParseStatus.mergeObjectSync(status, syncPairs);
      }
      static mergeObjectSync(status, pairs) {
        const finalObject = {};
        for (const pair of pairs) {
          const { key, value } = pair;
          if (key.status === "aborted")
            return INVALID;
          if (value.status === "aborted")
            return INVALID;
          if (key.status === "dirty")
            status.dirty();
          if (value.status === "dirty")
            status.dirty();
          if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
            finalObject[key.value] = value.value;
          }
        }
        return { status: status.value, value: finalObject };
      }
    };
    INVALID = Object.freeze({
      status: "aborted"
    });
    DIRTY = (value) => ({ status: "dirty", value });
    OK = (value) => ({ status: "valid", value });
    isAborted = (x) => x.status === "aborted";
    isDirty = (x) => x.status === "dirty";
    isValid = (x) => x.status === "valid";
    isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
  }
});

// node_modules/zod/v3/helpers/typeAliases.js
var init_typeAliases = __esm({
  "node_modules/zod/v3/helpers/typeAliases.js"() {
    "use strict";
  }
});

// node_modules/zod/v3/helpers/errorUtil.js
var errorUtil;
var init_errorUtil = __esm({
  "node_modules/zod/v3/helpers/errorUtil.js"() {
    "use strict";
    (function(errorUtil2) {
      errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
      errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
    })(errorUtil || (errorUtil = {}));
  }
});

// node_modules/zod/v3/types.js
function processCreateParams(params) {
  if (!params)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description };
  const customMap = (iss, ctx) => {
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message ?? ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: message ?? required_error ?? ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: message ?? invalid_type_error ?? ctx.defaultError };
  };
  return { errorMap: customMap, description };
}
function timeRegexSource(args) {
  let secondsRegexSource = `[0-5]\\d`;
  if (args.precision) {
    secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  }
  const secondsQuantifier = args.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
  let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex = `${regex}(${opts.join("|")})`;
  return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version4) {
  if ((version4 === "v4" || !version4) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version4 === "v6" || !version4) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    if (!header)
      return false;
    const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base64));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if ("typ" in decoded && decoded?.typ !== "JWT")
      return false;
    if (!decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch {
    return false;
  }
}
function isValidCidr(ip, version4) {
  if ((version4 === "v4" || !version4) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version4 === "v6" || !version4) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}
function floatSafeRemainder(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}
function deepPartialify(schema) {
  if (schema instanceof ZodObject) {
    const newShape = {};
    for (const key in schema.shape) {
      const fieldSchema = schema.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema._def,
      shape: () => newShape
    });
  } else if (schema instanceof ZodArray) {
    return new ZodArray({
      ...schema._def,
      type: deepPartialify(schema.element)
    });
  } else if (schema instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodTuple) {
    return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
  } else {
    return schema;
  }
}
function mergeValues(a, b) {
  const aType = getParsedType(a);
  const bType = getParsedType(b);
  if (a === b) {
    return { valid: true, data: a };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b);
    const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a, ...b };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a[key], b[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a.length !== b.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index2 = 0; index2 < a.length; index2++) {
      const itemA = a[index2];
      const itemB = b[index2];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
    return { valid: true, data: a };
  } else {
    return { valid: false };
  }
}
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
function cleanParams(params, data) {
  const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
  const p2 = typeof p === "string" ? { message: p } : p;
  return p2;
}
function custom(check, _params = {}, fatal) {
  if (check)
    return ZodAny.create().superRefine((data, ctx) => {
      const r = check(data);
      if (r instanceof Promise) {
        return r.then((r2) => {
          if (!r2) {
            const params = cleanParams(_params, data);
            const _fatal = params.fatal ?? fatal ?? true;
            ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
          }
        });
      }
      if (!r) {
        const params = cleanParams(_params, data);
        const _fatal = params.fatal ?? fatal ?? true;
        ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
      }
      return;
    });
  return ZodAny.create();
}
var ParseInputLazyPath, handleResult, ZodType, cuidRegex, cuid2Regex, ulidRegex, uuidRegex, nanoidRegex, jwtRegex, durationRegex, emailRegex, _emojiRegex, emojiRegex, ipv4Regex, ipv4CidrRegex, ipv6Regex, ipv6CidrRegex, base64Regex2, base64urlRegex, dateRegexSource, dateRegex, ZodString, ZodNumber, ZodBigInt, ZodBoolean, ZodDate, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodArray, ZodObject, ZodUnion, getDiscriminator, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodFunction, ZodLazy, ZodLiteral, ZodEnum, ZodNativeEnum, ZodPromise, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodCatch, ZodNaN, BRAND, ZodBranded, ZodPipeline, ZodReadonly, late, ZodFirstPartyTypeKind, instanceOfType, stringType, numberType, nanType, bigIntType, booleanType, dateType, symbolType, undefinedType, nullType, anyType, unknownType, neverType, voidType, arrayType, objectType, strictObjectType, unionType, discriminatedUnionType, intersectionType, tupleType, recordType, mapType, setType, functionType, lazyType, literalType, enumType, nativeEnumType, promiseType, effectsType, optionalType, nullableType, preprocessType, pipelineType, ostring, onumber, oboolean, coerce, NEVER;
var init_types = __esm({
  "node_modules/zod/v3/types.js"() {
    "use strict";
    init_ZodError();
    init_errors4();
    init_errorUtil();
    init_parseUtil();
    init_util();
    ParseInputLazyPath = class {
      constructor(parent, value, path2, key) {
        this._cachedPath = [];
        this.parent = parent;
        this.data = value;
        this._path = path2;
        this._key = key;
      }
      get path() {
        if (!this._cachedPath.length) {
          if (Array.isArray(this._key)) {
            this._cachedPath.push(...this._path, ...this._key);
          } else {
            this._cachedPath.push(...this._path, this._key);
          }
        }
        return this._cachedPath;
      }
    };
    handleResult = (ctx, result) => {
      if (isValid(result)) {
        return { success: true, data: result.value };
      } else {
        if (!ctx.common.issues.length) {
          throw new Error("Validation failed but no issues detected.");
        }
        return {
          success: false,
          get error() {
            if (this._error)
              return this._error;
            const error = new ZodError(ctx.common.issues);
            this._error = error;
            return this._error;
          }
        };
      }
    };
    ZodType = class {
      get description() {
        return this._def.description;
      }
      _getType(input) {
        return getParsedType(input.data);
      }
      _getOrReturnCtx(input, ctx) {
        return ctx || {
          common: input.parent.common,
          data: input.data,
          parsedType: getParsedType(input.data),
          schemaErrorMap: this._def.errorMap,
          path: input.path,
          parent: input.parent
        };
      }
      _processInputParams(input) {
        return {
          status: new ParseStatus(),
          ctx: {
            common: input.parent.common,
            data: input.data,
            parsedType: getParsedType(input.data),
            schemaErrorMap: this._def.errorMap,
            path: input.path,
            parent: input.parent
          }
        };
      }
      _parseSync(input) {
        const result = this._parse(input);
        if (isAsync(result)) {
          throw new Error("Synchronous parse encountered promise.");
        }
        return result;
      }
      _parseAsync(input) {
        const result = this._parse(input);
        return Promise.resolve(result);
      }
      parse(data, params) {
        const result = this.safeParse(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      safeParse(data, params) {
        const ctx = {
          common: {
            issues: [],
            async: params?.async ?? false,
            contextualErrorMap: params?.errorMap
          },
          path: params?.path || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        const result = this._parseSync({ data, path: ctx.path, parent: ctx });
        return handleResult(ctx, result);
      }
      "~validate"(data) {
        const ctx = {
          common: {
            issues: [],
            async: !!this["~standard"].async
          },
          path: [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        if (!this["~standard"].async) {
          try {
            const result = this._parseSync({ data, path: [], parent: ctx });
            return isValid(result) ? {
              value: result.value
            } : {
              issues: ctx.common.issues
            };
          } catch (err) {
            if (err?.message?.toLowerCase()?.includes("encountered")) {
              this["~standard"].async = true;
            }
            ctx.common = {
              issues: [],
              async: true
            };
          }
        }
        return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        });
      }
      async parseAsync(data, params) {
        const result = await this.safeParseAsync(data, params);
        if (result.success)
          return result.data;
        throw result.error;
      }
      async safeParseAsync(data, params) {
        const ctx = {
          common: {
            issues: [],
            contextualErrorMap: params?.errorMap,
            async: true
          },
          path: params?.path || [],
          schemaErrorMap: this._def.errorMap,
          parent: null,
          data,
          parsedType: getParsedType(data)
        };
        const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
        const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
        return handleResult(ctx, result);
      }
      refine(check, message) {
        const getIssueProperties = (val) => {
          if (typeof message === "string" || typeof message === "undefined") {
            return { message };
          } else if (typeof message === "function") {
            return message(val);
          } else {
            return message;
          }
        };
        return this._refinement((val, ctx) => {
          const result = check(val);
          const setError = () => ctx.addIssue({
            code: ZodIssueCode.custom,
            ...getIssueProperties(val)
          });
          if (typeof Promise !== "undefined" && result instanceof Promise) {
            return result.then((data) => {
              if (!data) {
                setError();
                return false;
              } else {
                return true;
              }
            });
          }
          if (!result) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      refinement(check, refinementData) {
        return this._refinement((val, ctx) => {
          if (!check(val)) {
            ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
            return false;
          } else {
            return true;
          }
        });
      }
      _refinement(refinement) {
        return new ZodEffects({
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "refinement", refinement }
        });
      }
      superRefine(refinement) {
        return this._refinement(refinement);
      }
      constructor(def) {
        this.spa = this.safeParseAsync;
        this._def = def;
        this.parse = this.parse.bind(this);
        this.safeParse = this.safeParse.bind(this);
        this.parseAsync = this.parseAsync.bind(this);
        this.safeParseAsync = this.safeParseAsync.bind(this);
        this.spa = this.spa.bind(this);
        this.refine = this.refine.bind(this);
        this.refinement = this.refinement.bind(this);
        this.superRefine = this.superRefine.bind(this);
        this.optional = this.optional.bind(this);
        this.nullable = this.nullable.bind(this);
        this.nullish = this.nullish.bind(this);
        this.array = this.array.bind(this);
        this.promise = this.promise.bind(this);
        this.or = this.or.bind(this);
        this.and = this.and.bind(this);
        this.transform = this.transform.bind(this);
        this.brand = this.brand.bind(this);
        this.default = this.default.bind(this);
        this.catch = this.catch.bind(this);
        this.describe = this.describe.bind(this);
        this.pipe = this.pipe.bind(this);
        this.readonly = this.readonly.bind(this);
        this.isNullable = this.isNullable.bind(this);
        this.isOptional = this.isOptional.bind(this);
        this["~standard"] = {
          version: 1,
          vendor: "zod",
          validate: (data) => this["~validate"](data)
        };
      }
      optional() {
        return ZodOptional.create(this, this._def);
      }
      nullable() {
        return ZodNullable.create(this, this._def);
      }
      nullish() {
        return this.nullable().optional();
      }
      array() {
        return ZodArray.create(this);
      }
      promise() {
        return ZodPromise.create(this, this._def);
      }
      or(option) {
        return ZodUnion.create([this, option], this._def);
      }
      and(incoming) {
        return ZodIntersection.create(this, incoming, this._def);
      }
      transform(transform2) {
        return new ZodEffects({
          ...processCreateParams(this._def),
          schema: this,
          typeName: ZodFirstPartyTypeKind.ZodEffects,
          effect: { type: "transform", transform: transform2 }
        });
      }
      default(def) {
        const defaultValueFunc = typeof def === "function" ? def : () => def;
        return new ZodDefault({
          ...processCreateParams(this._def),
          innerType: this,
          defaultValue: defaultValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodDefault
        });
      }
      brand() {
        return new ZodBranded({
          typeName: ZodFirstPartyTypeKind.ZodBranded,
          type: this,
          ...processCreateParams(this._def)
        });
      }
      catch(def) {
        const catchValueFunc = typeof def === "function" ? def : () => def;
        return new ZodCatch({
          ...processCreateParams(this._def),
          innerType: this,
          catchValue: catchValueFunc,
          typeName: ZodFirstPartyTypeKind.ZodCatch
        });
      }
      describe(description) {
        const This = this.constructor;
        return new This({
          ...this._def,
          description
        });
      }
      pipe(target) {
        return ZodPipeline.create(this, target);
      }
      readonly() {
        return ZodReadonly.create(this);
      }
      isOptional() {
        return this.safeParse(void 0).success;
      }
      isNullable() {
        return this.safeParse(null).success;
      }
    };
    cuidRegex = /^c[^\s-]{8,}$/i;
    cuid2Regex = /^[0-9a-z]+$/;
    ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
    uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
    nanoidRegex = /^[a-z0-9_-]{21}$/i;
    jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
    durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
    emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
    _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
    ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
    ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
    ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
    ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
    base64Regex2 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
    base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
    dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
    dateRegex = new RegExp(`^${dateRegexSource}$`);
    ZodString = class _ZodString extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = String(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.string) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.string,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            if (input.data.length < check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            if (input.data.length > check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check.value,
                type: "string",
                inclusive: true,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "length") {
            const tooBig = input.data.length > check.value;
            const tooSmall = input.data.length < check.value;
            if (tooBig || tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              if (tooBig) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_big,
                  maximum: check.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check.message
                });
              } else if (tooSmall) {
                addIssueToContext(ctx, {
                  code: ZodIssueCode.too_small,
                  minimum: check.value,
                  type: "string",
                  inclusive: true,
                  exact: true,
                  message: check.message
                });
              }
              status.dirty();
            }
          } else if (check.kind === "email") {
            if (!emailRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "email",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "emoji") {
            if (!emojiRegex) {
              emojiRegex = new RegExp(_emojiRegex, "u");
            }
            if (!emojiRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "emoji",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "uuid") {
            if (!uuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "uuid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "nanoid") {
            if (!nanoidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "nanoid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cuid") {
            if (!cuidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cuid2") {
            if (!cuid2Regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cuid2",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "ulid") {
            if (!ulidRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ulid",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "url") {
            try {
              new URL(input.data);
            } catch {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "url",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "regex") {
            check.regex.lastIndex = 0;
            const testResult = check.regex.test(input.data);
            if (!testResult) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "regex",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "trim") {
            input.data = input.data.trim();
          } else if (check.kind === "includes") {
            if (!input.data.includes(check.value, check.position)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { includes: check.value, position: check.position },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "toLowerCase") {
            input.data = input.data.toLowerCase();
          } else if (check.kind === "toUpperCase") {
            input.data = input.data.toUpperCase();
          } else if (check.kind === "startsWith") {
            if (!input.data.startsWith(check.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { startsWith: check.value },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "endsWith") {
            if (!input.data.endsWith(check.value)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: { endsWith: check.value },
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "datetime") {
            const regex = datetimeRegex(check);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "datetime",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "date") {
            const regex = dateRegex;
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "date",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "time") {
            const regex = timeRegex(check);
            if (!regex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_string,
                validation: "time",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "duration") {
            if (!durationRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "duration",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "ip") {
            if (!isValidIP(input.data, check.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "ip",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "jwt") {
            if (!isValidJWT(input.data, check.alg)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "jwt",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "cidr") {
            if (!isValidCidr(input.data, check.version)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "cidr",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "base64") {
            if (!base64Regex2.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "base64url") {
            if (!base64urlRegex.test(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                validation: "base64url",
                code: ZodIssueCode.invalid_string,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      _regex(regex, validation, message) {
        return this.refinement((data) => regex.test(data), {
          validation,
          code: ZodIssueCode.invalid_string,
          ...errorUtil.errToObj(message)
        });
      }
      _addCheck(check) {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      email(message) {
        return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
      }
      url(message) {
        return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
      }
      emoji(message) {
        return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
      }
      uuid(message) {
        return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
      }
      nanoid(message) {
        return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
      }
      cuid(message) {
        return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
      }
      cuid2(message) {
        return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
      }
      ulid(message) {
        return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
      }
      base64(message) {
        return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
      }
      base64url(message) {
        return this._addCheck({
          kind: "base64url",
          ...errorUtil.errToObj(message)
        });
      }
      jwt(options) {
        return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
      }
      ip(options) {
        return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
      }
      cidr(options) {
        return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
      }
      datetime(options) {
        if (typeof options === "string") {
          return this._addCheck({
            kind: "datetime",
            precision: null,
            offset: false,
            local: false,
            message: options
          });
        }
        return this._addCheck({
          kind: "datetime",
          precision: typeof options?.precision === "undefined" ? null : options?.precision,
          offset: options?.offset ?? false,
          local: options?.local ?? false,
          ...errorUtil.errToObj(options?.message)
        });
      }
      date(message) {
        return this._addCheck({ kind: "date", message });
      }
      time(options) {
        if (typeof options === "string") {
          return this._addCheck({
            kind: "time",
            precision: null,
            message: options
          });
        }
        return this._addCheck({
          kind: "time",
          precision: typeof options?.precision === "undefined" ? null : options?.precision,
          ...errorUtil.errToObj(options?.message)
        });
      }
      duration(message) {
        return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
      }
      regex(regex, message) {
        return this._addCheck({
          kind: "regex",
          regex,
          ...errorUtil.errToObj(message)
        });
      }
      includes(value, options) {
        return this._addCheck({
          kind: "includes",
          value,
          position: options?.position,
          ...errorUtil.errToObj(options?.message)
        });
      }
      startsWith(value, message) {
        return this._addCheck({
          kind: "startsWith",
          value,
          ...errorUtil.errToObj(message)
        });
      }
      endsWith(value, message) {
        return this._addCheck({
          kind: "endsWith",
          value,
          ...errorUtil.errToObj(message)
        });
      }
      min(minLength, message) {
        return this._addCheck({
          kind: "min",
          value: minLength,
          ...errorUtil.errToObj(message)
        });
      }
      max(maxLength, message) {
        return this._addCheck({
          kind: "max",
          value: maxLength,
          ...errorUtil.errToObj(message)
        });
      }
      length(len, message) {
        return this._addCheck({
          kind: "length",
          value: len,
          ...errorUtil.errToObj(message)
        });
      }
      /**
       * Equivalent to `.min(1)`
       */
      nonempty(message) {
        return this.min(1, errorUtil.errToObj(message));
      }
      trim() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "trim" }]
        });
      }
      toLowerCase() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "toLowerCase" }]
        });
      }
      toUpperCase() {
        return new _ZodString({
          ...this._def,
          checks: [...this._def.checks, { kind: "toUpperCase" }]
        });
      }
      get isDatetime() {
        return !!this._def.checks.find((ch) => ch.kind === "datetime");
      }
      get isDate() {
        return !!this._def.checks.find((ch) => ch.kind === "date");
      }
      get isTime() {
        return !!this._def.checks.find((ch) => ch.kind === "time");
      }
      get isDuration() {
        return !!this._def.checks.find((ch) => ch.kind === "duration");
      }
      get isEmail() {
        return !!this._def.checks.find((ch) => ch.kind === "email");
      }
      get isURL() {
        return !!this._def.checks.find((ch) => ch.kind === "url");
      }
      get isEmoji() {
        return !!this._def.checks.find((ch) => ch.kind === "emoji");
      }
      get isUUID() {
        return !!this._def.checks.find((ch) => ch.kind === "uuid");
      }
      get isNANOID() {
        return !!this._def.checks.find((ch) => ch.kind === "nanoid");
      }
      get isCUID() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid");
      }
      get isCUID2() {
        return !!this._def.checks.find((ch) => ch.kind === "cuid2");
      }
      get isULID() {
        return !!this._def.checks.find((ch) => ch.kind === "ulid");
      }
      get isIP() {
        return !!this._def.checks.find((ch) => ch.kind === "ip");
      }
      get isCIDR() {
        return !!this._def.checks.find((ch) => ch.kind === "cidr");
      }
      get isBase64() {
        return !!this._def.checks.find((ch) => ch.kind === "base64");
      }
      get isBase64url() {
        return !!this._def.checks.find((ch) => ch.kind === "base64url");
      }
      get minLength() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxLength() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
    };
    ZodString.create = (params) => {
      return new ZodString({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodString,
        coerce: params?.coerce ?? false,
        ...processCreateParams(params)
      });
    };
    ZodNumber = class _ZodNumber extends ZodType {
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
        this.step = this.multipleOf;
      }
      _parse(input) {
        if (this._def.coerce) {
          input.data = Number(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.number) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.number,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
          if (check.kind === "int") {
            if (!util.isInteger(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.invalid_type,
                expected: "integer",
                received: "float",
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "min") {
            const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                minimum: check.value,
                type: "number",
                inclusive: check.inclusive,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                maximum: check.value,
                type: "number",
                inclusive: check.inclusive,
                exact: false,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "multipleOf") {
            if (floatSafeRemainder(input.data, check.value) !== 0) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check.value,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "finite") {
            if (!Number.isFinite(input.data)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_finite,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodNumber({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check) {
        return new _ZodNumber({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      int(message) {
        return this._addCheck({
          kind: "int",
          message: errorUtil.toString(message)
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: 0,
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      finite(message) {
        return this._addCheck({
          kind: "finite",
          message: errorUtil.toString(message)
        });
      }
      safe(message) {
        return this._addCheck({
          kind: "min",
          inclusive: true,
          value: Number.MIN_SAFE_INTEGER,
          message: errorUtil.toString(message)
        })._addCheck({
          kind: "max",
          inclusive: true,
          value: Number.MAX_SAFE_INTEGER,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
      get isInt() {
        return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
      }
      get isFinite() {
        let max = null;
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
            return true;
          } else if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          } else if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return Number.isFinite(min) && Number.isFinite(max);
      }
    };
    ZodNumber.create = (params) => {
      return new ZodNumber({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodNumber,
        coerce: params?.coerce || false,
        ...processCreateParams(params)
      });
    };
    ZodBigInt = class _ZodBigInt extends ZodType {
      constructor() {
        super(...arguments);
        this.min = this.gte;
        this.max = this.lte;
      }
      _parse(input) {
        if (this._def.coerce) {
          try {
            input.data = BigInt(input.data);
          } catch {
            return this._getInvalidInput(input);
          }
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.bigint) {
          return this._getInvalidInput(input);
        }
        let ctx = void 0;
        const status = new ParseStatus();
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
            if (tooSmall) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                type: "bigint",
                minimum: check.value,
                inclusive: check.inclusive,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
            if (tooBig) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                type: "bigint",
                maximum: check.value,
                inclusive: check.inclusive,
                message: check.message
              });
              status.dirty();
            }
          } else if (check.kind === "multipleOf") {
            if (input.data % check.value !== BigInt(0)) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.not_multiple_of,
                multipleOf: check.value,
                message: check.message
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return { status: status.value, value: input.data };
      }
      _getInvalidInput(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.bigint,
          received: ctx.parsedType
        });
        return INVALID;
      }
      gte(value, message) {
        return this.setLimit("min", value, true, errorUtil.toString(message));
      }
      gt(value, message) {
        return this.setLimit("min", value, false, errorUtil.toString(message));
      }
      lte(value, message) {
        return this.setLimit("max", value, true, errorUtil.toString(message));
      }
      lt(value, message) {
        return this.setLimit("max", value, false, errorUtil.toString(message));
      }
      setLimit(kind, value, inclusive, message) {
        return new _ZodBigInt({
          ...this._def,
          checks: [
            ...this._def.checks,
            {
              kind,
              value,
              inclusive,
              message: errorUtil.toString(message)
            }
          ]
        });
      }
      _addCheck(check) {
        return new _ZodBigInt({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      positive(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      negative(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: false,
          message: errorUtil.toString(message)
        });
      }
      nonpositive(message) {
        return this._addCheck({
          kind: "max",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      nonnegative(message) {
        return this._addCheck({
          kind: "min",
          value: BigInt(0),
          inclusive: true,
          message: errorUtil.toString(message)
        });
      }
      multipleOf(value, message) {
        return this._addCheck({
          kind: "multipleOf",
          value,
          message: errorUtil.toString(message)
        });
      }
      get minValue() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min;
      }
      get maxValue() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max;
      }
    };
    ZodBigInt.create = (params) => {
      return new ZodBigInt({
        checks: [],
        typeName: ZodFirstPartyTypeKind.ZodBigInt,
        coerce: params?.coerce ?? false,
        ...processCreateParams(params)
      });
    };
    ZodBoolean = class extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = Boolean(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.boolean) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.boolean,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodBoolean.create = (params) => {
      return new ZodBoolean({
        typeName: ZodFirstPartyTypeKind.ZodBoolean,
        coerce: params?.coerce || false,
        ...processCreateParams(params)
      });
    };
    ZodDate = class _ZodDate extends ZodType {
      _parse(input) {
        if (this._def.coerce) {
          input.data = new Date(input.data);
        }
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.date) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.date,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        if (Number.isNaN(input.data.getTime())) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_date
          });
          return INVALID;
        }
        const status = new ParseStatus();
        let ctx = void 0;
        for (const check of this._def.checks) {
          if (check.kind === "min") {
            if (input.data.getTime() < check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_small,
                message: check.message,
                inclusive: true,
                exact: false,
                minimum: check.value,
                type: "date"
              });
              status.dirty();
            }
          } else if (check.kind === "max") {
            if (input.data.getTime() > check.value) {
              ctx = this._getOrReturnCtx(input, ctx);
              addIssueToContext(ctx, {
                code: ZodIssueCode.too_big,
                message: check.message,
                inclusive: true,
                exact: false,
                maximum: check.value,
                type: "date"
              });
              status.dirty();
            }
          } else {
            util.assertNever(check);
          }
        }
        return {
          status: status.value,
          value: new Date(input.data.getTime())
        };
      }
      _addCheck(check) {
        return new _ZodDate({
          ...this._def,
          checks: [...this._def.checks, check]
        });
      }
      min(minDate, message) {
        return this._addCheck({
          kind: "min",
          value: minDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      max(maxDate, message) {
        return this._addCheck({
          kind: "max",
          value: maxDate.getTime(),
          message: errorUtil.toString(message)
        });
      }
      get minDate() {
        let min = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "min") {
            if (min === null || ch.value > min)
              min = ch.value;
          }
        }
        return min != null ? new Date(min) : null;
      }
      get maxDate() {
        let max = null;
        for (const ch of this._def.checks) {
          if (ch.kind === "max") {
            if (max === null || ch.value < max)
              max = ch.value;
          }
        }
        return max != null ? new Date(max) : null;
      }
    };
    ZodDate.create = (params) => {
      return new ZodDate({
        checks: [],
        coerce: params?.coerce || false,
        typeName: ZodFirstPartyTypeKind.ZodDate,
        ...processCreateParams(params)
      });
    };
    ZodSymbol = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.symbol) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.symbol,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodSymbol.create = (params) => {
      return new ZodSymbol({
        typeName: ZodFirstPartyTypeKind.ZodSymbol,
        ...processCreateParams(params)
      });
    };
    ZodUndefined = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.undefined,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodUndefined.create = (params) => {
      return new ZodUndefined({
        typeName: ZodFirstPartyTypeKind.ZodUndefined,
        ...processCreateParams(params)
      });
    };
    ZodNull = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.null) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.null,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodNull.create = (params) => {
      return new ZodNull({
        typeName: ZodFirstPartyTypeKind.ZodNull,
        ...processCreateParams(params)
      });
    };
    ZodAny = class extends ZodType {
      constructor() {
        super(...arguments);
        this._any = true;
      }
      _parse(input) {
        return OK(input.data);
      }
    };
    ZodAny.create = (params) => {
      return new ZodAny({
        typeName: ZodFirstPartyTypeKind.ZodAny,
        ...processCreateParams(params)
      });
    };
    ZodUnknown = class extends ZodType {
      constructor() {
        super(...arguments);
        this._unknown = true;
      }
      _parse(input) {
        return OK(input.data);
      }
    };
    ZodUnknown.create = (params) => {
      return new ZodUnknown({
        typeName: ZodFirstPartyTypeKind.ZodUnknown,
        ...processCreateParams(params)
      });
    };
    ZodNever = class extends ZodType {
      _parse(input) {
        const ctx = this._getOrReturnCtx(input);
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_type,
          expected: ZodParsedType.never,
          received: ctx.parsedType
        });
        return INVALID;
      }
    };
    ZodNever.create = (params) => {
      return new ZodNever({
        typeName: ZodFirstPartyTypeKind.ZodNever,
        ...processCreateParams(params)
      });
    };
    ZodVoid = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.undefined) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.void,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return OK(input.data);
      }
    };
    ZodVoid.create = (params) => {
      return new ZodVoid({
        typeName: ZodFirstPartyTypeKind.ZodVoid,
        ...processCreateParams(params)
      });
    };
    ZodArray = class _ZodArray extends ZodType {
      _parse(input) {
        const { ctx, status } = this._processInputParams(input);
        const def = this._def;
        if (ctx.parsedType !== ZodParsedType.array) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.array,
            received: ctx.parsedType
          });
          return INVALID;
        }
        if (def.exactLength !== null) {
          const tooBig = ctx.data.length > def.exactLength.value;
          const tooSmall = ctx.data.length < def.exactLength.value;
          if (tooBig || tooSmall) {
            addIssueToContext(ctx, {
              code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
              minimum: tooSmall ? def.exactLength.value : void 0,
              maximum: tooBig ? def.exactLength.value : void 0,
              type: "array",
              inclusive: true,
              exact: true,
              message: def.exactLength.message
            });
            status.dirty();
          }
        }
        if (def.minLength !== null) {
          if (ctx.data.length < def.minLength.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: def.minLength.value,
              type: "array",
              inclusive: true,
              exact: false,
              message: def.minLength.message
            });
            status.dirty();
          }
        }
        if (def.maxLength !== null) {
          if (ctx.data.length > def.maxLength.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: def.maxLength.value,
              type: "array",
              inclusive: true,
              exact: false,
              message: def.maxLength.message
            });
            status.dirty();
          }
        }
        if (ctx.common.async) {
          return Promise.all([...ctx.data].map((item, i) => {
            return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
          })).then((result2) => {
            return ParseStatus.mergeArray(status, result2);
          });
        }
        const result = [...ctx.data].map((item, i) => {
          return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
        });
        return ParseStatus.mergeArray(status, result);
      }
      get element() {
        return this._def.type;
      }
      min(minLength, message) {
        return new _ZodArray({
          ...this._def,
          minLength: { value: minLength, message: errorUtil.toString(message) }
        });
      }
      max(maxLength, message) {
        return new _ZodArray({
          ...this._def,
          maxLength: { value: maxLength, message: errorUtil.toString(message) }
        });
      }
      length(len, message) {
        return new _ZodArray({
          ...this._def,
          exactLength: { value: len, message: errorUtil.toString(message) }
        });
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodArray.create = (schema, params) => {
      return new ZodArray({
        type: schema,
        minLength: null,
        maxLength: null,
        exactLength: null,
        typeName: ZodFirstPartyTypeKind.ZodArray,
        ...processCreateParams(params)
      });
    };
    ZodObject = class _ZodObject extends ZodType {
      constructor() {
        super(...arguments);
        this._cached = null;
        this.nonstrict = this.passthrough;
        this.augment = this.extend;
      }
      _getCached() {
        if (this._cached !== null)
          return this._cached;
        const shape = this._def.shape();
        const keys = util.objectKeys(shape);
        this._cached = { shape, keys };
        return this._cached;
      }
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.object) {
          const ctx2 = this._getOrReturnCtx(input);
          addIssueToContext(ctx2, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx2.parsedType
          });
          return INVALID;
        }
        const { status, ctx } = this._processInputParams(input);
        const { shape, keys: shapeKeys } = this._getCached();
        const extraKeys = [];
        if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
          for (const key in ctx.data) {
            if (!shapeKeys.includes(key)) {
              extraKeys.push(key);
            }
          }
        }
        const pairs = [];
        for (const key of shapeKeys) {
          const keyValidator = shape[key];
          const value = ctx.data[key];
          pairs.push({
            key: { status: "valid", value: key },
            value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (this._def.catchall instanceof ZodNever) {
          const unknownKeys = this._def.unknownKeys;
          if (unknownKeys === "passthrough") {
            for (const key of extraKeys) {
              pairs.push({
                key: { status: "valid", value: key },
                value: { status: "valid", value: ctx.data[key] }
              });
            }
          } else if (unknownKeys === "strict") {
            if (extraKeys.length > 0) {
              addIssueToContext(ctx, {
                code: ZodIssueCode.unrecognized_keys,
                keys: extraKeys
              });
              status.dirty();
            }
          } else if (unknownKeys === "strip") {
          } else {
            throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
          }
        } else {
          const catchall = this._def.catchall;
          for (const key of extraKeys) {
            const value = ctx.data[key];
            pairs.push({
              key: { status: "valid", value: key },
              value: catchall._parse(
                new ParseInputLazyPath(ctx, value, ctx.path, key)
                //, ctx.child(key), value, getParsedType(value)
              ),
              alwaysSet: key in ctx.data
            });
          }
        }
        if (ctx.common.async) {
          return Promise.resolve().then(async () => {
            const syncPairs = [];
            for (const pair of pairs) {
              const key = await pair.key;
              const value = await pair.value;
              syncPairs.push({
                key,
                value,
                alwaysSet: pair.alwaysSet
              });
            }
            return syncPairs;
          }).then((syncPairs) => {
            return ParseStatus.mergeObjectSync(status, syncPairs);
          });
        } else {
          return ParseStatus.mergeObjectSync(status, pairs);
        }
      }
      get shape() {
        return this._def.shape();
      }
      strict(message) {
        errorUtil.errToObj;
        return new _ZodObject({
          ...this._def,
          unknownKeys: "strict",
          ...message !== void 0 ? {
            errorMap: (issue, ctx) => {
              const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
              if (issue.code === "unrecognized_keys")
                return {
                  message: errorUtil.errToObj(message).message ?? defaultError
                };
              return {
                message: defaultError
              };
            }
          } : {}
        });
      }
      strip() {
        return new _ZodObject({
          ...this._def,
          unknownKeys: "strip"
        });
      }
      passthrough() {
        return new _ZodObject({
          ...this._def,
          unknownKeys: "passthrough"
        });
      }
      // const AugmentFactory =
      //   <Def extends ZodObjectDef>(def: Def) =>
      //   <Augmentation extends ZodRawShape>(
      //     augmentation: Augmentation
      //   ): ZodObject<
      //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
      //     Def["unknownKeys"],
      //     Def["catchall"]
      //   > => {
      //     return new ZodObject({
      //       ...def,
      //       shape: () => ({
      //         ...def.shape(),
      //         ...augmentation,
      //       }),
      //     }) as any;
      //   };
      extend(augmentation) {
        return new _ZodObject({
          ...this._def,
          shape: () => ({
            ...this._def.shape(),
            ...augmentation
          })
        });
      }
      /**
       * Prior to zod@1.0.12 there was a bug in the
       * inferred type of merged objects. Please
       * upgrade if you are experiencing issues.
       */
      merge(merging) {
        const merged = new _ZodObject({
          unknownKeys: merging._def.unknownKeys,
          catchall: merging._def.catchall,
          shape: () => ({
            ...this._def.shape(),
            ...merging._def.shape()
          }),
          typeName: ZodFirstPartyTypeKind.ZodObject
        });
        return merged;
      }
      // merge<
      //   Incoming extends AnyZodObject,
      //   Augmentation extends Incoming["shape"],
      //   NewOutput extends {
      //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
      //       ? Augmentation[k]["_output"]
      //       : k extends keyof Output
      //       ? Output[k]
      //       : never;
      //   },
      //   NewInput extends {
      //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
      //       ? Augmentation[k]["_input"]
      //       : k extends keyof Input
      //       ? Input[k]
      //       : never;
      //   }
      // >(
      //   merging: Incoming
      // ): ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"],
      //   NewOutput,
      //   NewInput
      // > {
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      setKey(key, schema) {
        return this.augment({ [key]: schema });
      }
      // merge<Incoming extends AnyZodObject>(
      //   merging: Incoming
      // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
      // ZodObject<
      //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
      //   Incoming["_def"]["unknownKeys"],
      //   Incoming["_def"]["catchall"]
      // > {
      //   // const mergedShape = objectUtil.mergeShapes(
      //   //   this._def.shape(),
      //   //   merging._def.shape()
      //   // );
      //   const merged: any = new ZodObject({
      //     unknownKeys: merging._def.unknownKeys,
      //     catchall: merging._def.catchall,
      //     shape: () =>
      //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
      //     typeName: ZodFirstPartyTypeKind.ZodObject,
      //   }) as any;
      //   return merged;
      // }
      catchall(index2) {
        return new _ZodObject({
          ...this._def,
          catchall: index2
        });
      }
      pick(mask) {
        const shape = {};
        for (const key of util.objectKeys(mask)) {
          if (mask[key] && this.shape[key]) {
            shape[key] = this.shape[key];
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      omit(mask) {
        const shape = {};
        for (const key of util.objectKeys(this.shape)) {
          if (!mask[key]) {
            shape[key] = this.shape[key];
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => shape
        });
      }
      /**
       * @deprecated
       */
      deepPartial() {
        return deepPartialify(this);
      }
      partial(mask) {
        const newShape = {};
        for (const key of util.objectKeys(this.shape)) {
          const fieldSchema = this.shape[key];
          if (mask && !mask[key]) {
            newShape[key] = fieldSchema;
          } else {
            newShape[key] = fieldSchema.optional();
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => newShape
        });
      }
      required(mask) {
        const newShape = {};
        for (const key of util.objectKeys(this.shape)) {
          if (mask && !mask[key]) {
            newShape[key] = this.shape[key];
          } else {
            const fieldSchema = this.shape[key];
            let newField = fieldSchema;
            while (newField instanceof ZodOptional) {
              newField = newField._def.innerType;
            }
            newShape[key] = newField;
          }
        }
        return new _ZodObject({
          ...this._def,
          shape: () => newShape
        });
      }
      keyof() {
        return createZodEnum(util.objectKeys(this.shape));
      }
    };
    ZodObject.create = (shape, params) => {
      return new ZodObject({
        shape: () => shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodObject.strictCreate = (shape, params) => {
      return new ZodObject({
        shape: () => shape,
        unknownKeys: "strict",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodObject.lazycreate = (shape, params) => {
      return new ZodObject({
        shape,
        unknownKeys: "strip",
        catchall: ZodNever.create(),
        typeName: ZodFirstPartyTypeKind.ZodObject,
        ...processCreateParams(params)
      });
    };
    ZodUnion = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const options = this._def.options;
        function handleResults(results) {
          for (const result of results) {
            if (result.result.status === "valid") {
              return result.result;
            }
          }
          for (const result of results) {
            if (result.result.status === "dirty") {
              ctx.common.issues.push(...result.ctx.common.issues);
              return result.result;
            }
          }
          const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union,
            unionErrors
          });
          return INVALID;
        }
        if (ctx.common.async) {
          return Promise.all(options.map(async (option) => {
            const childCtx = {
              ...ctx,
              common: {
                ...ctx.common,
                issues: []
              },
              parent: null
            };
            return {
              result: await option._parseAsync({
                data: ctx.data,
                path: ctx.path,
                parent: childCtx
              }),
              ctx: childCtx
            };
          })).then(handleResults);
        } else {
          let dirty = void 0;
          const issues = [];
          for (const option of options) {
            const childCtx = {
              ...ctx,
              common: {
                ...ctx.common,
                issues: []
              },
              parent: null
            };
            const result = option._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: childCtx
            });
            if (result.status === "valid") {
              return result;
            } else if (result.status === "dirty" && !dirty) {
              dirty = { result, ctx: childCtx };
            }
            if (childCtx.common.issues.length) {
              issues.push(childCtx.common.issues);
            }
          }
          if (dirty) {
            ctx.common.issues.push(...dirty.ctx.common.issues);
            return dirty.result;
          }
          const unionErrors = issues.map((issues2) => new ZodError(issues2));
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union,
            unionErrors
          });
          return INVALID;
        }
      }
      get options() {
        return this._def.options;
      }
    };
    ZodUnion.create = (types, params) => {
      return new ZodUnion({
        options: types,
        typeName: ZodFirstPartyTypeKind.ZodUnion,
        ...processCreateParams(params)
      });
    };
    getDiscriminator = (type) => {
      if (type instanceof ZodLazy) {
        return getDiscriminator(type.schema);
      } else if (type instanceof ZodEffects) {
        return getDiscriminator(type.innerType());
      } else if (type instanceof ZodLiteral) {
        return [type.value];
      } else if (type instanceof ZodEnum) {
        return type.options;
      } else if (type instanceof ZodNativeEnum) {
        return util.objectValues(type.enum);
      } else if (type instanceof ZodDefault) {
        return getDiscriminator(type._def.innerType);
      } else if (type instanceof ZodUndefined) {
        return [void 0];
      } else if (type instanceof ZodNull) {
        return [null];
      } else if (type instanceof ZodOptional) {
        return [void 0, ...getDiscriminator(type.unwrap())];
      } else if (type instanceof ZodNullable) {
        return [null, ...getDiscriminator(type.unwrap())];
      } else if (type instanceof ZodBranded) {
        return getDiscriminator(type.unwrap());
      } else if (type instanceof ZodReadonly) {
        return getDiscriminator(type.unwrap());
      } else if (type instanceof ZodCatch) {
        return getDiscriminator(type._def.innerType);
      } else {
        return [];
      }
    };
    ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const discriminator = this.discriminator;
        const discriminatorValue = ctx.data[discriminator];
        const option = this.optionsMap.get(discriminatorValue);
        if (!option) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_union_discriminator,
            options: Array.from(this.optionsMap.keys()),
            path: [discriminator]
          });
          return INVALID;
        }
        if (ctx.common.async) {
          return option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
        } else {
          return option._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
        }
      }
      get discriminator() {
        return this._def.discriminator;
      }
      get options() {
        return this._def.options;
      }
      get optionsMap() {
        return this._def.optionsMap;
      }
      /**
       * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
       * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
       * have a different value for each object in the union.
       * @param discriminator the name of the discriminator property
       * @param types an array of object schemas
       * @param params
       */
      static create(discriminator, options, params) {
        const optionsMap = /* @__PURE__ */ new Map();
        for (const type of options) {
          const discriminatorValues = getDiscriminator(type.shape[discriminator]);
          if (!discriminatorValues.length) {
            throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
          }
          for (const value of discriminatorValues) {
            if (optionsMap.has(value)) {
              throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
            }
            optionsMap.set(value, type);
          }
        }
        return new _ZodDiscriminatedUnion({
          typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
          discriminator,
          options,
          optionsMap,
          ...processCreateParams(params)
        });
      }
    };
    ZodIntersection = class extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const handleParsed = (parsedLeft, parsedRight) => {
          if (isAborted(parsedLeft) || isAborted(parsedRight)) {
            return INVALID;
          }
          const merged = mergeValues(parsedLeft.value, parsedRight.value);
          if (!merged.valid) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.invalid_intersection_types
            });
            return INVALID;
          }
          if (isDirty(parsedLeft) || isDirty(parsedRight)) {
            status.dirty();
          }
          return { status: status.value, value: merged.data };
        };
        if (ctx.common.async) {
          return Promise.all([
            this._def.left._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            }),
            this._def.right._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            })
          ]).then(([left, right]) => handleParsed(left, right));
        } else {
          return handleParsed(this._def.left._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          }), this._def.right._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          }));
        }
      }
    };
    ZodIntersection.create = (left, right, params) => {
      return new ZodIntersection({
        left,
        right,
        typeName: ZodFirstPartyTypeKind.ZodIntersection,
        ...processCreateParams(params)
      });
    };
    ZodTuple = class _ZodTuple extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.array) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.array,
            received: ctx.parsedType
          });
          return INVALID;
        }
        if (ctx.data.length < this._def.items.length) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          return INVALID;
        }
        const rest = this._def.rest;
        if (!rest && ctx.data.length > this._def.items.length) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: this._def.items.length,
            inclusive: true,
            exact: false,
            type: "array"
          });
          status.dirty();
        }
        const items = [...ctx.data].map((item, itemIndex) => {
          const schema = this._def.items[itemIndex] || this._def.rest;
          if (!schema)
            return null;
          return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
        }).filter((x) => !!x);
        if (ctx.common.async) {
          return Promise.all(items).then((results) => {
            return ParseStatus.mergeArray(status, results);
          });
        } else {
          return ParseStatus.mergeArray(status, items);
        }
      }
      get items() {
        return this._def.items;
      }
      rest(rest) {
        return new _ZodTuple({
          ...this._def,
          rest
        });
      }
    };
    ZodTuple.create = (schemas, params) => {
      if (!Array.isArray(schemas)) {
        throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
      }
      return new ZodTuple({
        items: schemas,
        typeName: ZodFirstPartyTypeKind.ZodTuple,
        rest: null,
        ...processCreateParams(params)
      });
    };
    ZodRecord = class _ZodRecord extends ZodType {
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.object) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.object,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const pairs = [];
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        for (const key in ctx.data) {
          pairs.push({
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
            value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
            alwaysSet: key in ctx.data
          });
        }
        if (ctx.common.async) {
          return ParseStatus.mergeObjectAsync(status, pairs);
        } else {
          return ParseStatus.mergeObjectSync(status, pairs);
        }
      }
      get element() {
        return this._def.valueType;
      }
      static create(first, second, third) {
        if (second instanceof ZodType) {
          return new _ZodRecord({
            keyType: first,
            valueType: second,
            typeName: ZodFirstPartyTypeKind.ZodRecord,
            ...processCreateParams(third)
          });
        }
        return new _ZodRecord({
          keyType: ZodString.create(),
          valueType: first,
          typeName: ZodFirstPartyTypeKind.ZodRecord,
          ...processCreateParams(second)
        });
      }
    };
    ZodMap = class extends ZodType {
      get keySchema() {
        return this._def.keyType;
      }
      get valueSchema() {
        return this._def.valueType;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.map) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.map,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const keyType = this._def.keyType;
        const valueType = this._def.valueType;
        const pairs = [...ctx.data.entries()].map(([key, value], index2) => {
          return {
            key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])),
            value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"]))
          };
        });
        if (ctx.common.async) {
          const finalMap = /* @__PURE__ */ new Map();
          return Promise.resolve().then(async () => {
            for (const pair of pairs) {
              const key = await pair.key;
              const value = await pair.value;
              if (key.status === "aborted" || value.status === "aborted") {
                return INVALID;
              }
              if (key.status === "dirty" || value.status === "dirty") {
                status.dirty();
              }
              finalMap.set(key.value, value.value);
            }
            return { status: status.value, value: finalMap };
          });
        } else {
          const finalMap = /* @__PURE__ */ new Map();
          for (const pair of pairs) {
            const key = pair.key;
            const value = pair.value;
            if (key.status === "aborted" || value.status === "aborted") {
              return INVALID;
            }
            if (key.status === "dirty" || value.status === "dirty") {
              status.dirty();
            }
            finalMap.set(key.value, value.value);
          }
          return { status: status.value, value: finalMap };
        }
      }
    };
    ZodMap.create = (keyType, valueType, params) => {
      return new ZodMap({
        valueType,
        keyType,
        typeName: ZodFirstPartyTypeKind.ZodMap,
        ...processCreateParams(params)
      });
    };
    ZodSet = class _ZodSet extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.set) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.set,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const def = this._def;
        if (def.minSize !== null) {
          if (ctx.data.size < def.minSize.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: def.minSize.value,
              type: "set",
              inclusive: true,
              exact: false,
              message: def.minSize.message
            });
            status.dirty();
          }
        }
        if (def.maxSize !== null) {
          if (ctx.data.size > def.maxSize.value) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: def.maxSize.value,
              type: "set",
              inclusive: true,
              exact: false,
              message: def.maxSize.message
            });
            status.dirty();
          }
        }
        const valueType = this._def.valueType;
        function finalizeSet(elements2) {
          const parsedSet = /* @__PURE__ */ new Set();
          for (const element of elements2) {
            if (element.status === "aborted")
              return INVALID;
            if (element.status === "dirty")
              status.dirty();
            parsedSet.add(element.value);
          }
          return { status: status.value, value: parsedSet };
        }
        const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
        if (ctx.common.async) {
          return Promise.all(elements).then((elements2) => finalizeSet(elements2));
        } else {
          return finalizeSet(elements);
        }
      }
      min(minSize, message) {
        return new _ZodSet({
          ...this._def,
          minSize: { value: minSize, message: errorUtil.toString(message) }
        });
      }
      max(maxSize, message) {
        return new _ZodSet({
          ...this._def,
          maxSize: { value: maxSize, message: errorUtil.toString(message) }
        });
      }
      size(size5, message) {
        return this.min(size5, message).max(size5, message);
      }
      nonempty(message) {
        return this.min(1, message);
      }
    };
    ZodSet.create = (valueType, params) => {
      return new ZodSet({
        valueType,
        minSize: null,
        maxSize: null,
        typeName: ZodFirstPartyTypeKind.ZodSet,
        ...processCreateParams(params)
      });
    };
    ZodFunction = class _ZodFunction extends ZodType {
      constructor() {
        super(...arguments);
        this.validate = this.implement;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.function) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.function,
            received: ctx.parsedType
          });
          return INVALID;
        }
        function makeArgsIssue(args, error) {
          return makeIssue({
            data: args,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
            issueData: {
              code: ZodIssueCode.invalid_arguments,
              argumentsError: error
            }
          });
        }
        function makeReturnsIssue(returns, error) {
          return makeIssue({
            data: returns,
            path: ctx.path,
            errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x),
            issueData: {
              code: ZodIssueCode.invalid_return_type,
              returnTypeError: error
            }
          });
        }
        const params = { errorMap: ctx.common.contextualErrorMap };
        const fn = ctx.data;
        if (this._def.returns instanceof ZodPromise) {
          const me = this;
          return OK(async function(...args) {
            const error = new ZodError([]);
            const parsedArgs = await me._def.args.parseAsync(args, params).catch((e7) => {
              error.addIssue(makeArgsIssue(args, e7));
              throw error;
            });
            const result = await Reflect.apply(fn, this, parsedArgs);
            const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e7) => {
              error.addIssue(makeReturnsIssue(result, e7));
              throw error;
            });
            return parsedReturns;
          });
        } else {
          const me = this;
          return OK(function(...args) {
            const parsedArgs = me._def.args.safeParse(args, params);
            if (!parsedArgs.success) {
              throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
            }
            const result = Reflect.apply(fn, this, parsedArgs.data);
            const parsedReturns = me._def.returns.safeParse(result, params);
            if (!parsedReturns.success) {
              throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
            }
            return parsedReturns.data;
          });
        }
      }
      parameters() {
        return this._def.args;
      }
      returnType() {
        return this._def.returns;
      }
      args(...items) {
        return new _ZodFunction({
          ...this._def,
          args: ZodTuple.create(items).rest(ZodUnknown.create())
        });
      }
      returns(returnType) {
        return new _ZodFunction({
          ...this._def,
          returns: returnType
        });
      }
      implement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
      }
      strictImplement(func) {
        const validatedFunc = this.parse(func);
        return validatedFunc;
      }
      static create(args, returns, params) {
        return new _ZodFunction({
          args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
          returns: returns || ZodUnknown.create(),
          typeName: ZodFirstPartyTypeKind.ZodFunction,
          ...processCreateParams(params)
        });
      }
    };
    ZodLazy = class extends ZodType {
      get schema() {
        return this._def.getter();
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const lazySchema = this._def.getter();
        return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
      }
    };
    ZodLazy.create = (getter, params) => {
      return new ZodLazy({
        getter,
        typeName: ZodFirstPartyTypeKind.ZodLazy,
        ...processCreateParams(params)
      });
    };
    ZodLiteral = class extends ZodType {
      _parse(input) {
        if (input.data !== this._def.value) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_literal,
            expected: this._def.value
          });
          return INVALID;
        }
        return { status: "valid", value: input.data };
      }
      get value() {
        return this._def.value;
      }
    };
    ZodLiteral.create = (value, params) => {
      return new ZodLiteral({
        value,
        typeName: ZodFirstPartyTypeKind.ZodLiteral,
        ...processCreateParams(params)
      });
    };
    ZodEnum = class _ZodEnum extends ZodType {
      _parse(input) {
        if (typeof input.data !== "string") {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          addIssueToContext(ctx, {
            expected: util.joinValues(expectedValues),
            received: ctx.parsedType,
            code: ZodIssueCode.invalid_type
          });
          return INVALID;
        }
        if (!this._cache) {
          this._cache = new Set(this._def.values);
        }
        if (!this._cache.has(input.data)) {
          const ctx = this._getOrReturnCtx(input);
          const expectedValues = this._def.values;
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return INVALID;
        }
        return OK(input.data);
      }
      get options() {
        return this._def.values;
      }
      get enum() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      get Values() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      get Enum() {
        const enumValues = {};
        for (const val of this._def.values) {
          enumValues[val] = val;
        }
        return enumValues;
      }
      extract(values, newDef = this._def) {
        return _ZodEnum.create(values, {
          ...this._def,
          ...newDef
        });
      }
      exclude(values, newDef = this._def) {
        return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
          ...this._def,
          ...newDef
        });
      }
    };
    ZodEnum.create = createZodEnum;
    ZodNativeEnum = class extends ZodType {
      _parse(input) {
        const nativeEnumValues = util.getValidEnumValues(this._def.values);
        const ctx = this._getOrReturnCtx(input);
        if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
          const expectedValues = util.objectValues(nativeEnumValues);
          addIssueToContext(ctx, {
            expected: util.joinValues(expectedValues),
            received: ctx.parsedType,
            code: ZodIssueCode.invalid_type
          });
          return INVALID;
        }
        if (!this._cache) {
          this._cache = new Set(util.getValidEnumValues(this._def.values));
        }
        if (!this._cache.has(input.data)) {
          const expectedValues = util.objectValues(nativeEnumValues);
          addIssueToContext(ctx, {
            received: ctx.data,
            code: ZodIssueCode.invalid_enum_value,
            options: expectedValues
          });
          return INVALID;
        }
        return OK(input.data);
      }
      get enum() {
        return this._def.values;
      }
    };
    ZodNativeEnum.create = (values, params) => {
      return new ZodNativeEnum({
        values,
        typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
        ...processCreateParams(params)
      });
    };
    ZodPromise = class extends ZodType {
      unwrap() {
        return this._def.type;
      }
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.promise,
            received: ctx.parsedType
          });
          return INVALID;
        }
        const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
        return OK(promisified.then((data) => {
          return this._def.type.parseAsync(data, {
            path: ctx.path,
            errorMap: ctx.common.contextualErrorMap
          });
        }));
      }
    };
    ZodPromise.create = (schema, params) => {
      return new ZodPromise({
        type: schema,
        typeName: ZodFirstPartyTypeKind.ZodPromise,
        ...processCreateParams(params)
      });
    };
    ZodEffects = class extends ZodType {
      innerType() {
        return this._def.schema;
      }
      sourceType() {
        return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
      }
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        const effect = this._def.effect || null;
        const checkCtx = {
          addIssue: (arg) => {
            addIssueToContext(ctx, arg);
            if (arg.fatal) {
              status.abort();
            } else {
              status.dirty();
            }
          },
          get path() {
            return ctx.path;
          }
        };
        checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
        if (effect.type === "preprocess") {
          const processed = effect.transform(ctx.data, checkCtx);
          if (ctx.common.async) {
            return Promise.resolve(processed).then(async (processed2) => {
              if (status.value === "aborted")
                return INVALID;
              const result = await this._def.schema._parseAsync({
                data: processed2,
                path: ctx.path,
                parent: ctx
              });
              if (result.status === "aborted")
                return INVALID;
              if (result.status === "dirty")
                return DIRTY(result.value);
              if (status.value === "dirty")
                return DIRTY(result.value);
              return result;
            });
          } else {
            if (status.value === "aborted")
              return INVALID;
            const result = this._def.schema._parseSync({
              data: processed,
              path: ctx.path,
              parent: ctx
            });
            if (result.status === "aborted")
              return INVALID;
            if (result.status === "dirty")
              return DIRTY(result.value);
            if (status.value === "dirty")
              return DIRTY(result.value);
            return result;
          }
        }
        if (effect.type === "refinement") {
          const executeRefinement = (acc) => {
            const result = effect.refinement(acc, checkCtx);
            if (ctx.common.async) {
              return Promise.resolve(result);
            }
            if (result instanceof Promise) {
              throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
            }
            return acc;
          };
          if (ctx.common.async === false) {
            const inner = this._def.schema._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (inner.status === "aborted")
              return INVALID;
            if (inner.status === "dirty")
              status.dirty();
            executeRefinement(inner.value);
            return { status: status.value, value: inner.value };
          } else {
            return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
              if (inner.status === "aborted")
                return INVALID;
              if (inner.status === "dirty")
                status.dirty();
              return executeRefinement(inner.value).then(() => {
                return { status: status.value, value: inner.value };
              });
            });
          }
        }
        if (effect.type === "transform") {
          if (ctx.common.async === false) {
            const base2 = this._def.schema._parseSync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (!isValid(base2))
              return INVALID;
            const result = effect.transform(base2.value, checkCtx);
            if (result instanceof Promise) {
              throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
            }
            return { status: status.value, value: result };
          } else {
            return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base2) => {
              if (!isValid(base2))
                return INVALID;
              return Promise.resolve(effect.transform(base2.value, checkCtx)).then((result) => ({
                status: status.value,
                value: result
              }));
            });
          }
        }
        util.assertNever(effect);
      }
    };
    ZodEffects.create = (schema, effect, params) => {
      return new ZodEffects({
        schema,
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        effect,
        ...processCreateParams(params)
      });
    };
    ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
      return new ZodEffects({
        schema,
        effect: { type: "preprocess", transform: preprocess },
        typeName: ZodFirstPartyTypeKind.ZodEffects,
        ...processCreateParams(params)
      });
    };
    ZodOptional = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.undefined) {
          return OK(void 0);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodOptional.create = (type, params) => {
      return new ZodOptional({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodOptional,
        ...processCreateParams(params)
      });
    };
    ZodNullable = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType === ZodParsedType.null) {
          return OK(null);
        }
        return this._def.innerType._parse(input);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodNullable.create = (type, params) => {
      return new ZodNullable({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodNullable,
        ...processCreateParams(params)
      });
    };
    ZodDefault = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        let data = ctx.data;
        if (ctx.parsedType === ZodParsedType.undefined) {
          data = this._def.defaultValue();
        }
        return this._def.innerType._parse({
          data,
          path: ctx.path,
          parent: ctx
        });
      }
      removeDefault() {
        return this._def.innerType;
      }
    };
    ZodDefault.create = (type, params) => {
      return new ZodDefault({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodDefault,
        defaultValue: typeof params.default === "function" ? params.default : () => params.default,
        ...processCreateParams(params)
      });
    };
    ZodCatch = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const newCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          }
        };
        const result = this._def.innerType._parse({
          data: newCtx.data,
          path: newCtx.path,
          parent: {
            ...newCtx
          }
        });
        if (isAsync(result)) {
          return result.then((result2) => {
            return {
              status: "valid",
              value: result2.status === "valid" ? result2.value : this._def.catchValue({
                get error() {
                  return new ZodError(newCtx.common.issues);
                },
                input: newCtx.data
              })
            };
          });
        } else {
          return {
            status: "valid",
            value: result.status === "valid" ? result.value : this._def.catchValue({
              get error() {
                return new ZodError(newCtx.common.issues);
              },
              input: newCtx.data
            })
          };
        }
      }
      removeCatch() {
        return this._def.innerType;
      }
    };
    ZodCatch.create = (type, params) => {
      return new ZodCatch({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodCatch,
        catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
        ...processCreateParams(params)
      });
    };
    ZodNaN = class extends ZodType {
      _parse(input) {
        const parsedType = this._getType(input);
        if (parsedType !== ZodParsedType.nan) {
          const ctx = this._getOrReturnCtx(input);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: ZodParsedType.nan,
            received: ctx.parsedType
          });
          return INVALID;
        }
        return { status: "valid", value: input.data };
      }
    };
    ZodNaN.create = (params) => {
      return new ZodNaN({
        typeName: ZodFirstPartyTypeKind.ZodNaN,
        ...processCreateParams(params)
      });
    };
    BRAND = /* @__PURE__ */ Symbol("zod_brand");
    ZodBranded = class extends ZodType {
      _parse(input) {
        const { ctx } = this._processInputParams(input);
        const data = ctx.data;
        return this._def.type._parse({
          data,
          path: ctx.path,
          parent: ctx
        });
      }
      unwrap() {
        return this._def.type;
      }
    };
    ZodPipeline = class _ZodPipeline extends ZodType {
      _parse(input) {
        const { status, ctx } = this._processInputParams(input);
        if (ctx.common.async) {
          const handleAsync = async () => {
            const inResult = await this._def.in._parseAsync({
              data: ctx.data,
              path: ctx.path,
              parent: ctx
            });
            if (inResult.status === "aborted")
              return INVALID;
            if (inResult.status === "dirty") {
              status.dirty();
              return DIRTY(inResult.value);
            } else {
              return this._def.out._parseAsync({
                data: inResult.value,
                path: ctx.path,
                parent: ctx
              });
            }
          };
          return handleAsync();
        } else {
          const inResult = this._def.in._parseSync({
            data: ctx.data,
            path: ctx.path,
            parent: ctx
          });
          if (inResult.status === "aborted")
            return INVALID;
          if (inResult.status === "dirty") {
            status.dirty();
            return {
              status: "dirty",
              value: inResult.value
            };
          } else {
            return this._def.out._parseSync({
              data: inResult.value,
              path: ctx.path,
              parent: ctx
            });
          }
        }
      }
      static create(a, b) {
        return new _ZodPipeline({
          in: a,
          out: b,
          typeName: ZodFirstPartyTypeKind.ZodPipeline
        });
      }
    };
    ZodReadonly = class extends ZodType {
      _parse(input) {
        const result = this._def.innerType._parse(input);
        const freeze = (data) => {
          if (isValid(data)) {
            data.value = Object.freeze(data.value);
          }
          return data;
        };
        return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
      }
      unwrap() {
        return this._def.innerType;
      }
    };
    ZodReadonly.create = (type, params) => {
      return new ZodReadonly({
        innerType: type,
        typeName: ZodFirstPartyTypeKind.ZodReadonly,
        ...processCreateParams(params)
      });
    };
    late = {
      object: ZodObject.lazycreate
    };
    (function(ZodFirstPartyTypeKind2) {
      ZodFirstPartyTypeKind2["ZodString"] = "ZodString";
      ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber";
      ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN";
      ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt";
      ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean";
      ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate";
      ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol";
      ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined";
      ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull";
      ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny";
      ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown";
      ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever";
      ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid";
      ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray";
      ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject";
      ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion";
      ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
      ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection";
      ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple";
      ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord";
      ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap";
      ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet";
      ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction";
      ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy";
      ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral";
      ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum";
      ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects";
      ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum";
      ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional";
      ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable";
      ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault";
      ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch";
      ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise";
      ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded";
      ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline";
      ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly";
    })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
    instanceOfType = (cls, params = {
      message: `Input not instance of ${cls.name}`
    }) => custom((data) => data instanceof cls, params);
    stringType = ZodString.create;
    numberType = ZodNumber.create;
    nanType = ZodNaN.create;
    bigIntType = ZodBigInt.create;
    booleanType = ZodBoolean.create;
    dateType = ZodDate.create;
    symbolType = ZodSymbol.create;
    undefinedType = ZodUndefined.create;
    nullType = ZodNull.create;
    anyType = ZodAny.create;
    unknownType = ZodUnknown.create;
    neverType = ZodNever.create;
    voidType = ZodVoid.create;
    arrayType = ZodArray.create;
    objectType = ZodObject.create;
    strictObjectType = ZodObject.strictCreate;
    unionType = ZodUnion.create;
    discriminatedUnionType = ZodDiscriminatedUnion.create;
    intersectionType = ZodIntersection.create;
    tupleType = ZodTuple.create;
    recordType = ZodRecord.create;
    mapType = ZodMap.create;
    setType = ZodSet.create;
    functionType = ZodFunction.create;
    lazyType = ZodLazy.create;
    literalType = ZodLiteral.create;
    enumType = ZodEnum.create;
    nativeEnumType = ZodNativeEnum.create;
    promiseType = ZodPromise.create;
    effectsType = ZodEffects.create;
    optionalType = ZodOptional.create;
    nullableType = ZodNullable.create;
    preprocessType = ZodEffects.createWithPreprocess;
    pipelineType = ZodPipeline.create;
    ostring = () => stringType().optional();
    onumber = () => numberType().optional();
    oboolean = () => booleanType().optional();
    coerce = {
      string: ((arg) => ZodString.create({ ...arg, coerce: true })),
      number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
      boolean: ((arg) => ZodBoolean.create({
        ...arg,
        coerce: true
      })),
      bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
      date: ((arg) => ZodDate.create({ ...arg, coerce: true }))
    };
    NEVER = INVALID;
  }
});

// node_modules/zod/v3/external.js
var external_exports = {};
__export(external_exports, {
  BRAND: () => BRAND,
  DIRTY: () => DIRTY,
  EMPTY_PATH: () => EMPTY_PATH,
  INVALID: () => INVALID,
  NEVER: () => NEVER,
  OK: () => OK,
  ParseStatus: () => ParseStatus,
  Schema: () => ZodType,
  ZodAny: () => ZodAny,
  ZodArray: () => ZodArray,
  ZodBigInt: () => ZodBigInt,
  ZodBoolean: () => ZodBoolean,
  ZodBranded: () => ZodBranded,
  ZodCatch: () => ZodCatch,
  ZodDate: () => ZodDate,
  ZodDefault: () => ZodDefault,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion,
  ZodEffects: () => ZodEffects,
  ZodEnum: () => ZodEnum,
  ZodError: () => ZodError,
  ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind,
  ZodFunction: () => ZodFunction,
  ZodIntersection: () => ZodIntersection,
  ZodIssueCode: () => ZodIssueCode,
  ZodLazy: () => ZodLazy,
  ZodLiteral: () => ZodLiteral,
  ZodMap: () => ZodMap,
  ZodNaN: () => ZodNaN,
  ZodNativeEnum: () => ZodNativeEnum,
  ZodNever: () => ZodNever,
  ZodNull: () => ZodNull,
  ZodNullable: () => ZodNullable,
  ZodNumber: () => ZodNumber,
  ZodObject: () => ZodObject,
  ZodOptional: () => ZodOptional,
  ZodParsedType: () => ZodParsedType,
  ZodPipeline: () => ZodPipeline,
  ZodPromise: () => ZodPromise,
  ZodReadonly: () => ZodReadonly,
  ZodRecord: () => ZodRecord,
  ZodSchema: () => ZodType,
  ZodSet: () => ZodSet,
  ZodString: () => ZodString,
  ZodSymbol: () => ZodSymbol,
  ZodTransformer: () => ZodEffects,
  ZodTuple: () => ZodTuple,
  ZodType: () => ZodType,
  ZodUndefined: () => ZodUndefined,
  ZodUnion: () => ZodUnion,
  ZodUnknown: () => ZodUnknown,
  ZodVoid: () => ZodVoid,
  addIssueToContext: () => addIssueToContext,
  any: () => anyType,
  array: () => arrayType,
  bigint: () => bigIntType,
  boolean: () => booleanType,
  coerce: () => coerce,
  custom: () => custom,
  date: () => dateType,
  datetimeRegex: () => datetimeRegex,
  defaultErrorMap: () => en_default,
  discriminatedUnion: () => discriminatedUnionType,
  effect: () => effectsType,
  enum: () => enumType,
  function: () => functionType,
  getErrorMap: () => getErrorMap,
  getParsedType: () => getParsedType,
  instanceof: () => instanceOfType,
  intersection: () => intersectionType,
  isAborted: () => isAborted,
  isAsync: () => isAsync,
  isDirty: () => isDirty,
  isValid: () => isValid,
  late: () => late,
  lazy: () => lazyType,
  literal: () => literalType,
  makeIssue: () => makeIssue,
  map: () => mapType,
  nan: () => nanType,
  nativeEnum: () => nativeEnumType,
  never: () => neverType,
  null: () => nullType,
  nullable: () => nullableType,
  number: () => numberType,
  object: () => objectType,
  objectUtil: () => objectUtil,
  oboolean: () => oboolean,
  onumber: () => onumber,
  optional: () => optionalType,
  ostring: () => ostring,
  pipeline: () => pipelineType,
  preprocess: () => preprocessType,
  promise: () => promiseType,
  quotelessJson: () => quotelessJson,
  record: () => recordType,
  set: () => setType,
  setErrorMap: () => setErrorMap,
  strictObject: () => strictObjectType,
  string: () => stringType,
  symbol: () => symbolType,
  transformer: () => effectsType,
  tuple: () => tupleType,
  undefined: () => undefinedType,
  union: () => unionType,
  unknown: () => unknownType,
  util: () => util,
  void: () => voidType
});
var init_external = __esm({
  "node_modules/zod/v3/external.js"() {
    "use strict";
    init_errors4();
    init_parseUtil();
    init_typeAliases();
    init_util();
    init_types();
    init_ZodError();
  }
});

// node_modules/zod/index.js
var init_zod = __esm({
  "node_modules/zod/index.js"() {
    "use strict";
    init_external();
    init_external();
  }
});

// node_modules/@x402/core/dist/esm/chunk-KMQH4MQI.mjs
var NonEmptyString, Any, OptionalAny, NetworkSchemaV1, NetworkSchemaV2, NetworkSchema, ResourceInfoSchema, PaymentRequirementsV1Schema, PaymentRequiredV1Schema, PaymentPayloadV1Schema, PaymentRequirementsV2Schema, PaymentRequiredV2Schema, PaymentPayloadV2Schema, PaymentRequirementsSchema, PaymentRequiredSchema, PaymentPayloadSchema;
var init_chunk_KMQH4MQI = __esm({
  "node_modules/@x402/core/dist/esm/chunk-KMQH4MQI.mjs"() {
    "use strict";
    init_zod();
    init_zod();
    NonEmptyString = external_exports.string().min(1);
    Any = external_exports.record(external_exports.unknown());
    OptionalAny = external_exports.record(external_exports.unknown()).optional().nullable();
    NetworkSchemaV1 = NonEmptyString;
    NetworkSchemaV2 = external_exports.string().min(3).refine((val) => val.includes(":"), {
      message: "Network must be in CAIP-2 format (e.g., 'eip155:84532')"
    });
    NetworkSchema = external_exports.union([NetworkSchemaV1, NetworkSchemaV2]);
    ResourceInfoSchema = external_exports.object({
      url: NonEmptyString,
      description: external_exports.string().optional(),
      mimeType: external_exports.string().optional()
    });
    PaymentRequirementsV1Schema = external_exports.object({
      scheme: NonEmptyString,
      network: NetworkSchemaV1,
      maxAmountRequired: NonEmptyString,
      resource: NonEmptyString,
      // URL string in V1
      description: external_exports.string(),
      mimeType: external_exports.string().optional(),
      outputSchema: Any.optional().nullable(),
      payTo: NonEmptyString,
      maxTimeoutSeconds: external_exports.number().positive(),
      asset: NonEmptyString,
      extra: OptionalAny
    });
    PaymentRequiredV1Schema = external_exports.object({
      x402Version: external_exports.literal(1),
      error: external_exports.string().optional(),
      accepts: external_exports.array(PaymentRequirementsV1Schema).min(1)
    });
    PaymentPayloadV1Schema = external_exports.object({
      x402Version: external_exports.literal(1),
      scheme: NonEmptyString,
      network: NetworkSchemaV1,
      payload: Any
    });
    PaymentRequirementsV2Schema = external_exports.object({
      scheme: NonEmptyString,
      network: NetworkSchemaV2,
      amount: NonEmptyString,
      asset: NonEmptyString,
      payTo: NonEmptyString,
      maxTimeoutSeconds: external_exports.number().positive(),
      extra: OptionalAny
    });
    PaymentRequiredV2Schema = external_exports.object({
      x402Version: external_exports.literal(2),
      error: external_exports.string().optional(),
      resource: ResourceInfoSchema,
      accepts: external_exports.array(PaymentRequirementsV2Schema).min(1),
      extensions: OptionalAny
    });
    PaymentPayloadV2Schema = external_exports.object({
      x402Version: external_exports.literal(2),
      resource: ResourceInfoSchema.optional(),
      accepted: PaymentRequirementsV2Schema,
      payload: Any,
      extensions: OptionalAny
    });
    PaymentRequirementsSchema = external_exports.union([
      PaymentRequirementsV1Schema,
      PaymentRequirementsV2Schema
    ]);
    PaymentRequiredSchema = external_exports.discriminatedUnion("x402Version", [
      PaymentRequiredV1Schema,
      PaymentRequiredV2Schema
    ]);
    PaymentPayloadSchema = external_exports.discriminatedUnion("x402Version", [
      PaymentPayloadV1Schema,
      PaymentPayloadV2Schema
    ]);
  }
});

// node_modules/@x402/core/dist/esm/chunk-VE37GDG2.mjs
var x402Version;
var init_chunk_VE37GDG2 = __esm({
  "node_modules/@x402/core/dist/esm/chunk-VE37GDG2.mjs"() {
    "use strict";
    x402Version = 2;
  }
});

// node_modules/@x402/core/dist/esm/chunk-JUGE6MAI.mjs
var init_chunk_JUGE6MAI = __esm({
  "node_modules/@x402/core/dist/esm/chunk-JUGE6MAI.mjs"() {
    "use strict";
  }
});

// node_modules/@x402/core/dist/esm/chunk-4BKQ2IT7.mjs
function safeBase64Encode(data) {
  if (typeof globalThis !== "undefined" && typeof globalThis.btoa === "function") {
    const bytes = new TextEncoder().encode(data);
    const binaryString = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
    return globalThis.btoa(binaryString);
  }
  return Buffer.from(data, "utf8").toString("base64");
}
function safeBase64Decode(data) {
  if (typeof globalThis !== "undefined" && typeof globalThis.atob === "function") {
    const binaryString = globalThis.atob(data);
    const bytes = new Uint8Array(binaryString.length);
    for (let i = 0; i < binaryString.length; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }
    const decoder2 = new TextDecoder("utf-8");
    return decoder2.decode(bytes);
  }
  return Buffer.from(data, "base64").toString("utf-8");
}
var findSchemesByNetwork, findByNetworkAndScheme, Base64EncodedRegex;
var init_chunk_4BKQ2IT7 = __esm({
  "node_modules/@x402/core/dist/esm/chunk-4BKQ2IT7.mjs"() {
    "use strict";
    findSchemesByNetwork = (map, network) => {
      let implementationsByScheme = map.get(network);
      if (!implementationsByScheme) {
        for (const [registeredNetworkPattern, implementations] of map.entries()) {
          const pattern = registeredNetworkPattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*");
          const regex = new RegExp(`^${pattern}$`);
          if (regex.test(network)) {
            implementationsByScheme = implementations;
            break;
          }
        }
      }
      return implementationsByScheme;
    };
    findByNetworkAndScheme = (map, scheme, network) => {
      return findSchemesByNetwork(map, network)?.get(scheme);
    };
    Base64EncodedRegex = /^[A-Za-z0-9+/]*={0,2}$/;
  }
});

// node_modules/@x402/core/dist/esm/chunk-BJTO5JO5.mjs
var init_chunk_BJTO5JO5 = __esm({
  "node_modules/@x402/core/dist/esm/chunk-BJTO5JO5.mjs"() {
    "use strict";
  }
});

// node_modules/@x402/core/dist/esm/chunk-G3XJUKWR.mjs
function encodePaymentSignatureHeader(paymentPayload) {
  return safeBase64Encode(JSON.stringify(paymentPayload));
}
function decodePaymentRequiredHeader(paymentRequiredHeader) {
  if (!Base64EncodedRegex.test(paymentRequiredHeader)) {
    throw new Error("Invalid payment required header");
  }
  return JSON.parse(safeBase64Decode(paymentRequiredHeader));
}
function decodePaymentResponseHeader(paymentResponseHeader) {
  if (!Base64EncodedRegex.test(paymentResponseHeader)) {
    throw new Error("Invalid payment response header");
  }
  return JSON.parse(safeBase64Decode(paymentResponseHeader));
}
var verifyResponseSchema, settleResponseSchema, supportedKindSchema, supportedResponseSchema, x402HTTPClient;
var init_chunk_G3XJUKWR = __esm({
  "node_modules/@x402/core/dist/esm/chunk-G3XJUKWR.mjs"() {
    "use strict";
    init_chunk_KMQH4MQI();
    init_chunk_VE37GDG2();
    init_chunk_JUGE6MAI();
    init_chunk_4BKQ2IT7();
    init_chunk_BJTO5JO5();
    verifyResponseSchema = external_exports.object({
      isValid: external_exports.boolean(),
      invalidReason: external_exports.string().nullish().transform((v) => v ?? void 0),
      invalidMessage: external_exports.string().nullish().transform((v) => v ?? void 0),
      payer: external_exports.string().nullish().transform((v) => v ?? void 0),
      extensions: external_exports.record(external_exports.string(), external_exports.unknown()).nullish().transform((v) => v ?? void 0)
    });
    settleResponseSchema = external_exports.object({
      success: external_exports.boolean(),
      errorReason: external_exports.string().nullish().transform((v) => v ?? void 0),
      errorMessage: external_exports.string().nullish().transform((v) => v ?? void 0),
      payer: external_exports.string().nullish().transform((v) => v ?? void 0),
      transaction: external_exports.string(),
      network: external_exports.custom((value) => typeof value === "string"),
      extensions: external_exports.record(external_exports.string(), external_exports.unknown()).nullish().transform((v) => v ?? void 0)
    });
    supportedKindSchema = external_exports.object({
      x402Version: external_exports.number(),
      scheme: external_exports.string(),
      network: external_exports.custom(
        (value) => typeof value === "string"
      ),
      extra: external_exports.record(external_exports.string(), external_exports.unknown()).nullish().transform((v) => v ?? void 0)
    });
    supportedResponseSchema = external_exports.object({
      kinds: external_exports.array(supportedKindSchema),
      extensions: external_exports.array(external_exports.string()).default([]),
      signers: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())).default({})
    });
    x402HTTPClient = class {
      /**
       * Creates a new x402HTTPClient instance.
       *
       * @param client - The underlying x402Client for payment logic
       */
      constructor(client) {
        this.client = client;
        this.paymentRequiredHooks = [];
      }
      /**
       * Register a hook to handle 402 responses before payment.
       * Hooks run in order; first to return headers wins.
       *
       * @param hook - The hook function to register
       * @returns This instance for chaining
       */
      onPaymentRequired(hook) {
        this.paymentRequiredHooks.push(hook);
        return this;
      }
      /**
       * Run hooks and return headers if any hook provides them.
       *
       * @param paymentRequired - The payment required response from the server
       * @returns Headers to use for retry, or null to proceed to payment
       */
      async handlePaymentRequired(paymentRequired) {
        for (const hook of this.paymentRequiredHooks) {
          const result = await hook({ paymentRequired });
          if (result?.headers) {
            return result.headers;
          }
        }
        return null;
      }
      /**
       * Encodes a payment payload into appropriate HTTP headers based on version.
       *
       * @param paymentPayload - The payment payload to encode
       * @returns HTTP headers containing the encoded payment signature
       */
      encodePaymentSignatureHeader(paymentPayload) {
        switch (paymentPayload.x402Version) {
          case 2:
            return {
              "PAYMENT-SIGNATURE": encodePaymentSignatureHeader(paymentPayload)
            };
          case 1:
            return {
              "X-PAYMENT": encodePaymentSignatureHeader(paymentPayload)
            };
          default:
            throw new Error(
              `Unsupported x402 version: ${paymentPayload.x402Version}`
            );
        }
      }
      /**
       * Extracts payment required information from HTTP response.
       *
       * @param getHeader - Function to retrieve header value by name (case-insensitive)
       * @param body - Optional response body for v1 compatibility
       * @returns The payment required object
       */
      getPaymentRequiredResponse(getHeader, body) {
        const paymentRequired = getHeader("PAYMENT-REQUIRED");
        if (paymentRequired) {
          return decodePaymentRequiredHeader(paymentRequired);
        }
        if (body && body instanceof Object && "x402Version" in body && body.x402Version === 1) {
          return body;
        }
        throw new Error("Invalid payment required response");
      }
      /**
       * Extracts payment settlement response from HTTP headers.
       *
       * @param getHeader - Function to retrieve header value by name (case-insensitive)
       * @returns The settlement response object
       */
      getPaymentSettleResponse(getHeader) {
        const paymentResponse = getHeader("PAYMENT-RESPONSE");
        if (paymentResponse) {
          return decodePaymentResponseHeader(paymentResponse);
        }
        const xPaymentResponse = getHeader("X-PAYMENT-RESPONSE");
        if (xPaymentResponse) {
          return decodePaymentResponseHeader(xPaymentResponse);
        }
        throw new Error("Payment response header not found");
      }
      /**
       * Creates a payment payload for the given payment requirements.
       * Delegates to the underlying x402Client.
       *
       * @param paymentRequired - The payment required response from the server
       * @returns Promise resolving to the payment payload
       */
      async createPaymentPayload(paymentRequired) {
        return this.client.createPaymentPayload(paymentRequired);
      }
    };
  }
});

// node_modules/@x402/core/dist/esm/client/index.mjs
var x402Client;
var init_client = __esm({
  "node_modules/@x402/core/dist/esm/client/index.mjs"() {
    "use strict";
    init_chunk_G3XJUKWR();
    init_chunk_KMQH4MQI();
    init_chunk_VE37GDG2();
    init_chunk_JUGE6MAI();
    init_chunk_4BKQ2IT7();
    init_chunk_BJTO5JO5();
    x402Client = class _x402Client {
      /**
       * Creates a new x402Client instance.
       *
       * @param paymentRequirementsSelector - Function to select payment requirements from available options
       */
      constructor(paymentRequirementsSelector) {
        this.registeredClientSchemes = /* @__PURE__ */ new Map();
        this.policies = [];
        this.registeredExtensions = /* @__PURE__ */ new Map();
        this.beforePaymentCreationHooks = [];
        this.afterPaymentCreationHooks = [];
        this.onPaymentCreationFailureHooks = [];
        this.paymentRequirementsSelector = paymentRequirementsSelector || ((x402Version2, accepts) => accepts[0]);
      }
      /**
       * Creates a new x402Client instance from a configuration object.
       *
       * @param config - The client configuration including schemes, policies, and payment requirements selector
       * @returns A configured x402Client instance
       */
      static fromConfig(config) {
        const client = new _x402Client(config.paymentRequirementsSelector);
        config.schemes.forEach((scheme) => {
          if (scheme.x402Version === 1) {
            client.registerV1(scheme.network, scheme.client);
          } else {
            client.register(scheme.network, scheme.client);
          }
        });
        config.policies?.forEach((policy) => {
          client.registerPolicy(policy);
        });
        return client;
      }
      /**
       * Registers a scheme client for the current x402 version.
       *
       * @param network - The network to register the client for
       * @param client - The scheme network client to register
       * @returns The x402Client instance for chaining
       */
      register(network, client) {
        return this._registerScheme(x402Version, network, client);
      }
      /**
       * Registers a scheme client for x402 version 1.
       *
       * @param network - The v1 network identifier (e.g., 'base-sepolia', 'solana-devnet')
       * @param client - The scheme network client to register
       * @returns The x402Client instance for chaining
       */
      registerV1(network, client) {
        return this._registerScheme(1, network, client);
      }
      /**
       * Registers a policy to filter or transform payment requirements.
       *
       * Policies are applied in order after filtering by registered schemes
       * and before the selector chooses the final payment requirement.
       *
       * @param policy - Function to filter/transform payment requirements
       * @returns The x402Client instance for chaining
       *
       * @example
       * ```typescript
       * // Prefer cheaper options
       * client.registerPolicy((version, reqs) =>
       *   reqs.filter(r => BigInt(r.value) < BigInt('1000000'))
       * );
       *
       * // Prefer specific networks
       * client.registerPolicy((version, reqs) =>
       *   reqs.filter(r => r.network.startsWith('eip155:'))
       * );
       * ```
       */
      registerPolicy(policy) {
        this.policies.push(policy);
        return this;
      }
      /**
       * Registers a client extension that can enrich payment payloads.
       *
       * Extensions are invoked after the scheme creates the base payload and the
       * payload is wrapped with extensions/resource/accepted data. If the extension's
       * key is present in `paymentRequired.extensions`, the extension's
       * `enrichPaymentPayload` hook is called to modify the payload.
       *
       * @param extension - The client extension to register
       * @returns The x402Client instance for chaining
       */
      registerExtension(extension2) {
        this.registeredExtensions.set(extension2.key, extension2);
        return this;
      }
      /**
       * Register a hook to execute before payment payload creation.
       * Can abort creation by returning { abort: true, reason: string }
       *
       * @param hook - The hook function to register
       * @returns The x402Client instance for chaining
       */
      onBeforePaymentCreation(hook) {
        this.beforePaymentCreationHooks.push(hook);
        return this;
      }
      /**
       * Register a hook to execute after successful payment payload creation.
       *
       * @param hook - The hook function to register
       * @returns The x402Client instance for chaining
       */
      onAfterPaymentCreation(hook) {
        this.afterPaymentCreationHooks.push(hook);
        return this;
      }
      /**
       * Register a hook to execute when payment payload creation fails.
       * Can recover from failure by returning { recovered: true, payload: PaymentPayload }
       *
       * @param hook - The hook function to register
       * @returns The x402Client instance for chaining
       */
      onPaymentCreationFailure(hook) {
        this.onPaymentCreationFailureHooks.push(hook);
        return this;
      }
      /**
       * Creates a payment payload based on a PaymentRequired response.
       *
       * Automatically extracts x402Version, resource, and extensions from the PaymentRequired
       * response and constructs a complete PaymentPayload with the accepted requirements.
       *
       * @param paymentRequired - The PaymentRequired response from the server
       * @returns Promise resolving to the complete payment payload
       */
      async createPaymentPayload(paymentRequired) {
        const clientSchemesByNetwork = this.registeredClientSchemes.get(paymentRequired.x402Version);
        if (!clientSchemesByNetwork) {
          throw new Error(`No client registered for x402 version: ${paymentRequired.x402Version}`);
        }
        const requirements = this.selectPaymentRequirements(paymentRequired.x402Version, paymentRequired.accepts);
        const context = {
          paymentRequired,
          selectedRequirements: requirements
        };
        for (const hook of this.beforePaymentCreationHooks) {
          const result = await hook(context);
          if (result && "abort" in result && result.abort) {
            throw new Error(`Payment creation aborted: ${result.reason}`);
          }
        }
        try {
          const schemeNetworkClient = findByNetworkAndScheme(clientSchemesByNetwork, requirements.scheme, requirements.network);
          if (!schemeNetworkClient) {
            throw new Error(`No client registered for scheme: ${requirements.scheme} and network: ${requirements.network}`);
          }
          const partialPayload = await schemeNetworkClient.createPaymentPayload(
            paymentRequired.x402Version,
            requirements,
            { extensions: paymentRequired.extensions }
          );
          let paymentPayload;
          if (partialPayload.x402Version == 1) {
            paymentPayload = partialPayload;
          } else {
            const mergedExtensions = this.mergeExtensions(
              paymentRequired.extensions,
              partialPayload.extensions
            );
            paymentPayload = {
              x402Version: partialPayload.x402Version,
              payload: partialPayload.payload,
              extensions: mergedExtensions,
              resource: paymentRequired.resource,
              accepted: requirements
            };
          }
          paymentPayload = await this.enrichPaymentPayloadWithExtensions(paymentPayload, paymentRequired);
          const createdContext = {
            ...context,
            paymentPayload
          };
          for (const hook of this.afterPaymentCreationHooks) {
            await hook(createdContext);
          }
          return paymentPayload;
        } catch (error) {
          const failureContext = {
            ...context,
            error
          };
          for (const hook of this.onPaymentCreationFailureHooks) {
            const result = await hook(failureContext);
            if (result && "recovered" in result && result.recovered) {
              return result.payload;
            }
          }
          throw error;
        }
      }
      /**
       * Merges server-declared extensions with scheme-provided extensions.
       * Scheme extensions overlay on top of server extensions at each key,
       * preserving server-provided schema while overlaying scheme-provided info.
       *
       * @param serverExtensions - Extensions declared by the server in the 402 response
       * @param schemeExtensions - Extensions provided by the scheme client (e.g. EIP-2612)
       * @returns The merged extensions object, or undefined if both inputs are undefined
       */
      mergeExtensions(serverExtensions, schemeExtensions) {
        if (!schemeExtensions) return serverExtensions;
        if (!serverExtensions) return schemeExtensions;
        const merged = { ...serverExtensions };
        for (const [key, schemeValue] of Object.entries(schemeExtensions)) {
          const serverValue = merged[key];
          if (serverValue && typeof serverValue === "object" && schemeValue && typeof schemeValue === "object") {
            merged[key] = { ...serverValue, ...schemeValue };
          } else {
            merged[key] = schemeValue;
          }
        }
        return merged;
      }
      /**
       * Enriches a payment payload by calling registered extension hooks.
       * For each extension key present in the PaymentRequired response,
       * invokes the corresponding extension's enrichPaymentPayload callback.
       *
       * @param paymentPayload - The payment payload to enrich with extension data
       * @param paymentRequired - The PaymentRequired response containing extension declarations
       * @returns The enriched payment payload with extension data applied
       */
      async enrichPaymentPayloadWithExtensions(paymentPayload, paymentRequired) {
        if (!paymentRequired.extensions || this.registeredExtensions.size === 0) {
          return paymentPayload;
        }
        let enriched = paymentPayload;
        for (const [key, extension2] of this.registeredExtensions) {
          if (key in paymentRequired.extensions && extension2.enrichPaymentPayload) {
            enriched = await extension2.enrichPaymentPayload(enriched, paymentRequired);
          }
        }
        return enriched;
      }
      /**
       * Selects appropriate payment requirements based on registered clients and policies.
       *
       * Selection process:
       * 1. Filter by registered schemes (network + scheme support)
       * 2. Apply all registered policies in order
       * 3. Use selector to choose final requirement
       *
       * @param x402Version - The x402 protocol version
       * @param paymentRequirements - Array of available payment requirements
       * @returns The selected payment requirements
       */
      selectPaymentRequirements(x402Version2, paymentRequirements) {
        const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version2);
        if (!clientSchemesByNetwork) {
          throw new Error(`No client registered for x402 version: ${x402Version2}`);
        }
        const supportedPaymentRequirements = paymentRequirements.filter((requirement) => {
          let clientSchemes = findSchemesByNetwork(clientSchemesByNetwork, requirement.network);
          if (!clientSchemes) {
            return false;
          }
          return clientSchemes.has(requirement.scheme);
        });
        if (supportedPaymentRequirements.length === 0) {
          throw new Error(`No network/scheme registered for x402 version: ${x402Version2} which comply with the payment requirements. ${JSON.stringify({
            x402Version: x402Version2,
            paymentRequirements,
            x402Versions: Array.from(this.registeredClientSchemes.keys()),
            networks: Array.from(clientSchemesByNetwork.keys()),
            schemes: Array.from(clientSchemesByNetwork.values()).map((schemes) => Array.from(schemes.keys())).flat()
          })}`);
        }
        let filteredRequirements = supportedPaymentRequirements;
        for (const policy of this.policies) {
          filteredRequirements = policy(x402Version2, filteredRequirements);
          if (filteredRequirements.length === 0) {
            throw new Error(`All payment requirements were filtered out by policies for x402 version: ${x402Version2}`);
          }
        }
        return this.paymentRequirementsSelector(x402Version2, filteredRequirements);
      }
      /**
       * Internal method to register a scheme client.
       *
       * @param x402Version - The x402 protocol version
       * @param network - The network to register the client for
       * @param client - The scheme network client to register
       * @returns The x402Client instance for chaining
       */
      _registerScheme(x402Version2, network, client) {
        if (!this.registeredClientSchemes.has(x402Version2)) {
          this.registeredClientSchemes.set(x402Version2, /* @__PURE__ */ new Map());
        }
        const clientSchemesByNetwork = this.registeredClientSchemes.get(x402Version2);
        if (!clientSchemesByNetwork.has(network)) {
          clientSchemesByNetwork.set(network, /* @__PURE__ */ new Map());
        }
        const clientByScheme = clientSchemesByNetwork.get(network);
        if (!clientByScheme.has(client.scheme)) {
          clientByScheme.set(client.scheme, client);
        }
        return this;
      }
    };
  }
});

// node_modules/@x402/core/dist/esm/http/index.mjs
var init_http3 = __esm({
  "node_modules/@x402/core/dist/esm/http/index.mjs"() {
    "use strict";
    init_chunk_G3XJUKWR();
    init_chunk_KMQH4MQI();
    init_chunk_VE37GDG2();
    init_chunk_JUGE6MAI();
    init_chunk_4BKQ2IT7();
    init_chunk_BJTO5JO5();
  }
});

// node_modules/@x402/fetch/dist/esm/index.mjs
function wrapFetchWithPayment(fetch2, client) {
  const httpClient = client instanceof x402HTTPClient ? client : new x402HTTPClient(client);
  return async (input, init) => {
    const request = new Request(input, init);
    const clonedRequest = request.clone();
    const response = await fetch2(request);
    if (response.status !== 402) {
      return response;
    }
    let paymentRequired;
    try {
      const getHeader = (name) => response.headers.get(name);
      let body;
      try {
        const responseText = await response.text();
        if (responseText) {
          body = JSON.parse(responseText);
        }
      } catch {
      }
      paymentRequired = httpClient.getPaymentRequiredResponse(getHeader, body);
    } catch (error) {
      throw new Error(
        `Failed to parse payment requirements: ${error instanceof Error ? error.message : "Unknown error"}`
      );
    }
    const hookHeaders = await httpClient.handlePaymentRequired(paymentRequired);
    if (hookHeaders) {
      const hookRequest = clonedRequest.clone();
      for (const [key, value] of Object.entries(hookHeaders)) {
        hookRequest.headers.set(key, value);
      }
      const hookResponse = await fetch2(hookRequest);
      if (hookResponse.status !== 402) {
        return hookResponse;
      }
    }
    let paymentPayload;
    try {
      paymentPayload = await client.createPaymentPayload(paymentRequired);
    } catch (error) {
      throw new Error(
        `Failed to create payment payload: ${error instanceof Error ? error.message : "Unknown error"}`
      );
    }
    const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);
    if (clonedRequest.headers.has("PAYMENT-SIGNATURE") || clonedRequest.headers.has("X-PAYMENT")) {
      throw new Error("Payment already attempted");
    }
    for (const [key, value] of Object.entries(paymentHeaders)) {
      clonedRequest.headers.set(key, value);
    }
    clonedRequest.headers.set(
      "Access-Control-Expose-Headers",
      "PAYMENT-RESPONSE,X-PAYMENT-RESPONSE"
    );
    const secondResponse = await fetch2(clonedRequest);
    return secondResponse;
  };
}
var init_esm4 = __esm({
  "node_modules/@x402/fetch/dist/esm/index.mjs"() {
    "use strict";
    init_client();
    init_client();
    init_http3();
  }
});

// src/payment-preauth.ts
function createPayFetchWithPreAuth(baseFetch, client, ttlMs = DEFAULT_TTL_MS, options) {
  const httpClient = new x402HTTPClient(client);
  const cache2 = /* @__PURE__ */ new Map();
  return async (input, init) => {
    const request = new Request(input, init);
    const urlPath = new URL(request.url).pathname;
    let requestModel = "";
    if (init?.body) {
      try {
        const bodyStr = init.body instanceof Uint8Array ? new TextDecoder().decode(init.body) : typeof init.body === "string" ? init.body : "";
        if (bodyStr) {
          const parsed = JSON.parse(bodyStr);
          requestModel = parsed.model ?? "";
        }
      } catch {
      }
    }
    const cacheKey2 = `${urlPath}:${requestModel}`;
    const cached = !options?.skipPreAuth ? cache2.get(cacheKey2) : void 0;
    if (cached && Date.now() - cached.cachedAt < ttlMs) {
      try {
        const payload2 = await client.createPaymentPayload(cached.paymentRequired);
        const headers = httpClient.encodePaymentSignatureHeader(payload2);
        const preAuthRequest = request.clone();
        for (const [key, value] of Object.entries(headers)) {
          preAuthRequest.headers.set(key, value);
        }
        const response2 = await baseFetch(preAuthRequest);
        if (response2.status !== 402) {
          return response2;
        }
        cache2.delete(cacheKey2);
      } catch {
        cache2.delete(cacheKey2);
      }
    }
    const clonedRequest = request.clone();
    const response = await baseFetch(request);
    if (response.status !== 402) {
      return response;
    }
    let paymentRequired;
    try {
      const getHeader = (name) => response.headers.get(name);
      let body;
      try {
        const responseText = await Promise.race([
          response.text(),
          new Promise(
            (_, reject) => setTimeout(() => reject(new Error("Body read timeout")), 3e4)
          )
        ]);
        if (responseText) body = JSON.parse(responseText);
      } catch {
      }
      paymentRequired = httpClient.getPaymentRequiredResponse(getHeader, body);
      cache2.set(cacheKey2, { paymentRequired, cachedAt: Date.now() });
    } catch (error) {
      throw new Error(
        `Failed to parse payment requirements: ${error instanceof Error ? error.message : "Unknown error"}`,
        { cause: error }
      );
    }
    const payload = await client.createPaymentPayload(paymentRequired);
    const paymentHeaders = httpClient.encodePaymentSignatureHeader(payload);
    for (const [key, value] of Object.entries(paymentHeaders)) {
      clonedRequest.headers.set(key, value);
    }
    return baseFetch(clonedRequest);
  };
}
var DEFAULT_TTL_MS;
var init_payment_preauth = __esm({
  "src/payment-preauth.ts"() {
    "use strict";
    init_esm4();
    DEFAULT_TTL_MS = 36e5;
  }
});

// node_modules/@x402/evm/dist/esm/chunk-C4ZQMS77.mjs
function getEvmChainId(network) {
  if (network.startsWith("eip155:")) {
    const idStr = network.split(":")[1];
    const chainId = parseInt(idStr, 10);
    if (isNaN(chainId)) {
      throw new Error(`Invalid CAIP-2 chain ID: ${network}`);
    }
    return chainId;
  }
  throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);
}
function getCrypto() {
  const cryptoObj = globalThis.crypto;
  if (!cryptoObj) {
    throw new Error("Crypto API not available");
  }
  return cryptoObj;
}
function createNonce() {
  return toHex(getCrypto().getRandomValues(new Uint8Array(32)));
}
function createPermit2Nonce() {
  const randomBytes8 = getCrypto().getRandomValues(new Uint8Array(32));
  return BigInt(toHex(randomBytes8)).toString();
}
var authorizationTypes, permit2WitnessTypes, eip2612PermitTypes, eip2612NoncesAbi, erc20ApproveAbi, erc20AllowanceAbi, ERC20_APPROVE_GAS_LIMIT, DEFAULT_MAX_FEE_PER_GAS, DEFAULT_MAX_PRIORITY_FEE_PER_GAS, PERMIT2_ADDRESS, x402ExactPermit2ProxyAddress;
var init_chunk_C4ZQMS77 = __esm({
  "node_modules/@x402/evm/dist/esm/chunk-C4ZQMS77.mjs"() {
    "use strict";
    init_esm();
    authorizationTypes = {
      TransferWithAuthorization: [
        { name: "from", type: "address" },
        { name: "to", type: "address" },
        { name: "value", type: "uint256" },
        { name: "validAfter", type: "uint256" },
        { name: "validBefore", type: "uint256" },
        { name: "nonce", type: "bytes32" }
      ]
    };
    permit2WitnessTypes = {
      PermitWitnessTransferFrom: [
        { name: "permitted", type: "TokenPermissions" },
        { name: "spender", type: "address" },
        { name: "nonce", type: "uint256" },
        { name: "deadline", type: "uint256" },
        { name: "witness", type: "Witness" }
      ],
      TokenPermissions: [
        { name: "token", type: "address" },
        { name: "amount", type: "uint256" }
      ],
      Witness: [
        { name: "to", type: "address" },
        { name: "validAfter", type: "uint256" }
      ]
    };
    eip2612PermitTypes = {
      Permit: [
        { name: "owner", type: "address" },
        { name: "spender", type: "address" },
        { name: "value", type: "uint256" },
        { name: "nonce", type: "uint256" },
        { name: "deadline", type: "uint256" }
      ]
    };
    eip2612NoncesAbi = [
      {
        type: "function",
        name: "nonces",
        inputs: [{ name: "owner", type: "address" }],
        outputs: [{ type: "uint256" }],
        stateMutability: "view"
      }
    ];
    erc20ApproveAbi = [
      {
        type: "function",
        name: "approve",
        inputs: [
          { name: "spender", type: "address" },
          { name: "amount", type: "uint256" }
        ],
        outputs: [{ type: "bool" }],
        stateMutability: "nonpayable"
      }
    ];
    erc20AllowanceAbi = [
      {
        type: "function",
        name: "allowance",
        inputs: [
          { name: "owner", type: "address" },
          { name: "spender", type: "address" }
        ],
        outputs: [{ type: "uint256" }],
        stateMutability: "view"
      }
    ];
    ERC20_APPROVE_GAS_LIMIT = 70000n;
    DEFAULT_MAX_FEE_PER_GAS = 1000000000n;
    DEFAULT_MAX_PRIORITY_FEE_PER_GAS = 100000000n;
    PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
    x402ExactPermit2ProxyAddress = "0x402085c248EeA27D92E8b30b2C58ed07f9E20001";
  }
});

// node_modules/@x402/evm/dist/esm/chunk-EVC7K4OP.mjs
function getEvmChainIdV1(network) {
  const chainId = EVM_NETWORK_CHAIN_ID_MAP[network];
  if (!chainId) {
    throw new Error(`Unsupported v1 network: ${network}`);
  }
  return chainId;
}
var ExactEvmSchemeV1, EVM_NETWORK_CHAIN_ID_MAP, NETWORKS;
var init_chunk_EVC7K4OP = __esm({
  "node_modules/@x402/evm/dist/esm/chunk-EVC7K4OP.mjs"() {
    "use strict";
    init_chunk_C4ZQMS77();
    init_esm();
    ExactEvmSchemeV1 = class {
      /**
       * Creates a new ExactEvmClientV1 instance.
       *
       * @param signer - The EVM signer for client operations
       */
      constructor(signer) {
        this.signer = signer;
        this.scheme = "exact";
      }
      /**
       * Creates a payment payload for the Exact scheme (V1).
       *
       * @param x402Version - The x402 protocol version
       * @param paymentRequirements - The payment requirements
       * @returns Promise resolving to a payment payload
       */
      async createPaymentPayload(x402Version2, paymentRequirements) {
        const selectedV1 = paymentRequirements;
        const nonce = createNonce();
        const now = Math.floor(Date.now() / 1e3);
        const authorization = {
          from: this.signer.address,
          to: getAddress(selectedV1.payTo),
          value: selectedV1.maxAmountRequired,
          validAfter: (now - 600).toString(),
          // 10 minutes before
          validBefore: (now + selectedV1.maxTimeoutSeconds).toString(),
          nonce
        };
        const signature2 = await this.signAuthorization(authorization, selectedV1);
        const payload = {
          authorization,
          signature: signature2
        };
        return {
          x402Version: x402Version2,
          scheme: selectedV1.scheme,
          network: selectedV1.network,
          payload
        };
      }
      /**
       * Sign the EIP-3009 authorization using EIP-712
       *
       * @param authorization - The authorization to sign
       * @param requirements - The payment requirements
       * @returns Promise resolving to the signature
       */
      async signAuthorization(authorization, requirements) {
        const chainId = getEvmChainIdV1(requirements.network);
        if (!requirements.extra?.name || !requirements.extra?.version) {
          throw new Error(
            `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`
          );
        }
        const { name, version: version4 } = requirements.extra;
        const domain = {
          name,
          version: version4,
          chainId,
          verifyingContract: getAddress(requirements.asset)
        };
        const message = {
          from: getAddress(authorization.from),
          to: getAddress(authorization.to),
          value: BigInt(authorization.value),
          validAfter: BigInt(authorization.validAfter),
          validBefore: BigInt(authorization.validBefore),
          nonce: authorization.nonce
        };
        return await this.signer.signTypedData({
          domain,
          types: authorizationTypes,
          primaryType: "TransferWithAuthorization",
          message
        });
      }
    };
    EVM_NETWORK_CHAIN_ID_MAP = {
      ethereum: 1,
      sepolia: 11155111,
      abstract: 2741,
      "abstract-testnet": 11124,
      "base-sepolia": 84532,
      base: 8453,
      "avalanche-fuji": 43113,
      avalanche: 43114,
      iotex: 4689,
      sei: 1329,
      "sei-testnet": 1328,
      polygon: 137,
      "polygon-amoy": 80002,
      peaq: 3338,
      story: 1514,
      educhain: 41923,
      "skale-base-sepolia": 324705682,
      megaeth: 4326,
      monad: 143,
      stable: 988,
      "stable-testnet": 2201
    };
    NETWORKS = Object.keys(EVM_NETWORK_CHAIN_ID_MAP);
  }
});

// node_modules/@x402/evm/dist/esm/chunk-CRT6YNY5.mjs
async function createPermit2PayloadForProxy(proxyAddress, signer, x402Version2, paymentRequirements) {
  const now = Math.floor(Date.now() / 1e3);
  const nonce = createPermit2Nonce();
  const validAfter = (now - 600).toString();
  const deadline = (now + paymentRequirements.maxTimeoutSeconds).toString();
  const permit2Authorization = {
    from: signer.address,
    permitted: {
      token: getAddress(paymentRequirements.asset),
      amount: paymentRequirements.amount
    },
    spender: proxyAddress,
    nonce,
    deadline,
    witness: {
      to: getAddress(paymentRequirements.payTo),
      validAfter
    }
  };
  const signature2 = await signPermit2Authorization(
    signer,
    permit2Authorization,
    paymentRequirements
  );
  return {
    x402Version: x402Version2,
    payload: { signature: signature2, permit2Authorization }
  };
}
async function signPermit2Authorization(signer, permit2Authorization, requirements) {
  const chainId = getEvmChainId(requirements.network);
  return await signer.signTypedData({
    domain: { name: "Permit2", chainId, verifyingContract: PERMIT2_ADDRESS },
    types: permit2WitnessTypes,
    primaryType: "PermitWitnessTransferFrom",
    message: {
      permitted: {
        token: getAddress(permit2Authorization.permitted.token),
        amount: BigInt(permit2Authorization.permitted.amount)
      },
      spender: getAddress(permit2Authorization.spender),
      nonce: BigInt(permit2Authorization.nonce),
      deadline: BigInt(permit2Authorization.deadline),
      witness: {
        to: getAddress(permit2Authorization.witness.to),
        validAfter: BigInt(permit2Authorization.witness.validAfter)
      }
    }
  });
}
var EIP2612_GAS_SPONSORING_KEY, ERC20_APPROVAL_GAS_SPONSORING_KEY, ERC20_APPROVAL_GAS_SPONSORING_VERSION;
var init_chunk_CRT6YNY5 = __esm({
  "node_modules/@x402/evm/dist/esm/chunk-CRT6YNY5.mjs"() {
    "use strict";
    init_chunk_C4ZQMS77();
    init_esm();
    EIP2612_GAS_SPONSORING_KEY = "eip2612GasSponsoring";
    ERC20_APPROVAL_GAS_SPONSORING_KEY = "erc20ApprovalGasSponsoring";
    ERC20_APPROVAL_GAS_SPONSORING_VERSION = "1";
  }
});

// node_modules/@x402/evm/dist/esm/chunk-WKBC5YMI.mjs
async function createPermit2Payload(signer, x402Version2, paymentRequirements) {
  return createPermit2PayloadForProxy(
    x402ExactPermit2ProxyAddress,
    signer,
    x402Version2,
    paymentRequirements
  );
}
async function signEip2612Permit(signer, tokenAddress, tokenName, tokenVersion, chainId, deadline, permittedAmount) {
  const owner = signer.address;
  const spender = getAddress(PERMIT2_ADDRESS);
  const nonce = await signer.readContract({
    address: tokenAddress,
    abi: eip2612NoncesAbi,
    functionName: "nonces",
    args: [owner]
  });
  const domain = {
    name: tokenName,
    version: tokenVersion,
    chainId,
    verifyingContract: tokenAddress
  };
  const approvalAmount = BigInt(permittedAmount);
  const message = {
    owner,
    spender,
    value: approvalAmount,
    nonce,
    deadline: BigInt(deadline)
  };
  const signature2 = await signer.signTypedData({
    domain,
    types: eip2612PermitTypes,
    primaryType: "Permit",
    message
  });
  return {
    from: owner,
    asset: tokenAddress,
    spender,
    amount: approvalAmount.toString(),
    nonce: nonce.toString(),
    deadline,
    signature: signature2,
    version: "1"
  };
}
async function signErc20ApprovalTransaction(signer, tokenAddress, chainId) {
  const from14 = signer.address;
  const spender = getAddress(PERMIT2_ADDRESS);
  const data = encodeFunctionData({
    abi: erc20ApproveAbi,
    functionName: "approve",
    args: [spender, maxUint256]
  });
  const nonce = await signer.getTransactionCount({ address: from14 });
  let maxFeePerGas;
  let maxPriorityFeePerGas;
  try {
    const fees = await signer.estimateFeesPerGas?.();
    if (!fees) {
      throw new Error("no fee estimates available");
    }
    maxFeePerGas = fees.maxFeePerGas;
    maxPriorityFeePerGas = fees.maxPriorityFeePerGas;
  } catch {
    maxFeePerGas = DEFAULT_MAX_FEE_PER_GAS;
    maxPriorityFeePerGas = DEFAULT_MAX_PRIORITY_FEE_PER_GAS;
  }
  const signedTransaction = await signer.signTransaction({
    to: tokenAddress,
    data,
    nonce,
    gas: ERC20_APPROVE_GAS_LIMIT,
    maxFeePerGas,
    maxPriorityFeePerGas,
    chainId
  });
  return {
    from: from14,
    asset: tokenAddress,
    spender,
    amount: maxUint256.toString(),
    signedTransaction,
    version: ERC20_APPROVAL_GAS_SPONSORING_VERSION
  };
}
function isConfigByChainId(options) {
  const keys = Object.keys(options);
  return keys.length > 0 && keys.every((key) => /^\d+$/.test(key));
}
function getRpcClient(rpcUrl) {
  const existing = rpcClientCache.get(rpcUrl);
  if (existing) {
    return existing;
  }
  const client = createPublicClient({
    transport: http(rpcUrl)
  });
  rpcClientCache.set(rpcUrl, client);
  return client;
}
function resolveRpcUrl(network, options) {
  if (!options) {
    return void 0;
  }
  if (isConfigByChainId(options)) {
    const chainId = getEvmChainId(network);
    const optionsByChainId = options;
    return optionsByChainId[chainId]?.rpcUrl;
  }
  return options.rpcUrl;
}
function resolveExtensionRpcCapabilities(network, signer, options) {
  const capabilities = {
    signTransaction: signer.signTransaction,
    readContract: signer.readContract,
    getTransactionCount: signer.getTransactionCount,
    estimateFeesPerGas: signer.estimateFeesPerGas
  };
  const needsRpcBackfill = !capabilities.readContract || !capabilities.getTransactionCount || !capabilities.estimateFeesPerGas;
  if (!needsRpcBackfill) {
    return capabilities;
  }
  const rpcUrl = resolveRpcUrl(network, options);
  if (!rpcUrl) {
    return capabilities;
  }
  const rpcClient = getRpcClient(rpcUrl);
  if (!capabilities.readContract) {
    capabilities.readContract = (args) => rpcClient.readContract(args);
  }
  if (!capabilities.getTransactionCount) {
    capabilities.getTransactionCount = async (args) => rpcClient.getTransactionCount({ address: args.address });
  }
  if (!capabilities.estimateFeesPerGas) {
    capabilities.estimateFeesPerGas = async () => rpcClient.estimateFeesPerGas();
  }
  return capabilities;
}
async function trySignEip2612PermitExtension(signer, options, requirements, result, context) {
  const capabilities = resolveExtensionRpcCapabilities(requirements.network, signer, options);
  if (!capabilities.readContract) {
    return void 0;
  }
  if (!context?.extensions?.[EIP2612_GAS_SPONSORING_KEY]) {
    return void 0;
  }
  const tokenName = requirements.extra?.name;
  const tokenVersion = requirements.extra?.version;
  if (!tokenName || !tokenVersion) {
    return void 0;
  }
  const chainId = getEvmChainId(requirements.network);
  const tokenAddress = getAddress(requirements.asset);
  try {
    const allowance = await capabilities.readContract({
      address: tokenAddress,
      abi: erc20AllowanceAbi,
      functionName: "allowance",
      args: [signer.address, PERMIT2_ADDRESS]
    });
    if (allowance >= BigInt(requirements.amount)) {
      return void 0;
    }
  } catch {
  }
  const permit2Auth = result.payload?.permit2Authorization;
  const deadline = permit2Auth?.deadline ?? Math.floor(Date.now() / 1e3 + requirements.maxTimeoutSeconds).toString();
  const info = await signEip2612Permit(
    {
      address: signer.address,
      signTypedData: (msg) => signer.signTypedData(msg),
      readContract: capabilities.readContract
    },
    tokenAddress,
    tokenName,
    tokenVersion,
    chainId,
    deadline,
    requirements.amount
  );
  return {
    [EIP2612_GAS_SPONSORING_KEY]: { info }
  };
}
async function trySignErc20ApprovalExtension(signer, options, requirements, context) {
  const capabilities = resolveExtensionRpcCapabilities(requirements.network, signer, options);
  if (!capabilities.readContract) {
    return void 0;
  }
  if (!context?.extensions?.[ERC20_APPROVAL_GAS_SPONSORING_KEY]) {
    return void 0;
  }
  if (!capabilities.signTransaction || !capabilities.getTransactionCount) {
    return void 0;
  }
  const chainId = getEvmChainId(requirements.network);
  const tokenAddress = getAddress(requirements.asset);
  try {
    const allowance = await capabilities.readContract({
      address: tokenAddress,
      abi: erc20AllowanceAbi,
      functionName: "allowance",
      args: [signer.address, PERMIT2_ADDRESS]
    });
    if (allowance >= BigInt(requirements.amount)) {
      return void 0;
    }
  } catch {
  }
  const info = await signErc20ApprovalTransaction(
    {
      address: signer.address,
      signTransaction: capabilities.signTransaction,
      getTransactionCount: capabilities.getTransactionCount,
      estimateFeesPerGas: capabilities.estimateFeesPerGas
    },
    tokenAddress,
    chainId
  );
  return {
    [ERC20_APPROVAL_GAS_SPONSORING_KEY]: { info }
  };
}
var MAX_UINT256, rpcClientCache;
var init_chunk_WKBC5YMI = __esm({
  "node_modules/@x402/evm/dist/esm/chunk-WKBC5YMI.mjs"() {
    "use strict";
    init_chunk_CRT6YNY5();
    init_chunk_C4ZQMS77();
    init_esm();
    init_esm();
    init_esm();
    init_esm();
    MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
    rpcClientCache = /* @__PURE__ */ new Map();
  }
});

// node_modules/@x402/evm/dist/esm/chunk-664BKEHK.mjs
async function createEIP3009Payload(signer, x402Version2, paymentRequirements) {
  const nonce = createNonce();
  const now = Math.floor(Date.now() / 1e3);
  const authorization = {
    from: signer.address,
    to: getAddress(paymentRequirements.payTo),
    value: paymentRequirements.amount,
    validAfter: (now - 600).toString(),
    validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),
    nonce
  };
  const signature2 = await signEIP3009Authorization(signer, authorization, paymentRequirements);
  const payload = {
    authorization,
    signature: signature2
  };
  return {
    x402Version: x402Version2,
    payload
  };
}
async function signEIP3009Authorization(signer, authorization, requirements) {
  const chainId = getEvmChainId(requirements.network);
  if (!requirements.extra?.name || !requirements.extra?.version) {
    throw new Error(
      `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${requirements.asset}`
    );
  }
  const { name, version: version4 } = requirements.extra;
  const domain = {
    name,
    version: version4,
    chainId,
    verifyingContract: getAddress(requirements.asset)
  };
  const message = {
    from: getAddress(authorization.from),
    to: getAddress(authorization.to),
    value: BigInt(authorization.value),
    validAfter: BigInt(authorization.validAfter),
    validBefore: BigInt(authorization.validBefore),
    nonce: authorization.nonce
  };
  return await signer.signTypedData({
    domain,
    types: authorizationTypes,
    primaryType: "TransferWithAuthorization",
    message
  });
}
function registerExactEvmScheme(client, config) {
  const evmScheme = new ExactEvmScheme(config.signer, config.schemeOptions);
  if (config.networks && config.networks.length > 0) {
    config.networks.forEach((network) => {
      client.register(network, evmScheme);
    });
  } else {
    client.register("eip155:*", evmScheme);
  }
  NETWORKS.forEach((network) => {
    client.registerV1(network, new ExactEvmSchemeV1(config.signer));
  });
  if (config.policies) {
    config.policies.forEach((policy) => {
      client.registerPolicy(policy);
    });
  }
  return client;
}
var ExactEvmScheme;
var init_chunk_664BKEHK = __esm({
  "node_modules/@x402/evm/dist/esm/chunk-664BKEHK.mjs"() {
    "use strict";
    init_chunk_EVC7K4OP();
    init_chunk_WKBC5YMI();
    init_chunk_C4ZQMS77();
    init_esm();
    ExactEvmScheme = class {
      /**
       * Creates a new ExactEvmClient instance.
       *
       * @param signer - The EVM signer for client operations.
       *   Base flow only requires `address` + `signTypedData`.
       *   Extension enrichment (EIP-2612 / ERC-20 approval sponsoring) additionally
       *   requires optional capabilities like `readContract` and tx signing helpers.
       * @param options - Optional RPC configuration used to backfill extension capabilities.
       */
      constructor(signer, options) {
        this.signer = signer;
        this.options = options;
        this.scheme = "exact";
      }
      /**
       * Creates a payment payload for the Exact scheme.
       * Routes to EIP-3009 or Permit2 based on requirements.extra.assetTransferMethod.
       *
       * For Permit2 flows, if the server advertises `eip2612GasSponsoring` and the
       * signer supports `readContract`, automatically signs an EIP-2612 permit
       * when Permit2 allowance is insufficient.
       *
       * @param x402Version - The x402 protocol version
       * @param paymentRequirements - The payment requirements
       * @param context - Optional context with server-declared extensions
       * @returns Promise resolving to a payment payload result (with optional extensions)
       */
      async createPaymentPayload(x402Version2, paymentRequirements, context) {
        const assetTransferMethod = paymentRequirements.extra?.assetTransferMethod ?? "eip3009";
        if (assetTransferMethod === "permit2") {
          const result = await createPermit2Payload(this.signer, x402Version2, paymentRequirements);
          const eip2612Extensions = await trySignEip2612PermitExtension(
            this.signer,
            this.options,
            paymentRequirements,
            result,
            context
          );
          if (eip2612Extensions) {
            return {
              ...result,
              extensions: eip2612Extensions
            };
          }
          const erc20Extensions = await trySignErc20ApprovalExtension(
            this.signer,
            this.options,
            paymentRequirements,
            context
          );
          if (erc20Extensions) {
            return {
              ...result,
              extensions: erc20Extensions
            };
          }
          return result;
        }
        return createEIP3009Payload(this.signer, x402Version2, paymentRequirements);
      }
    };
  }
});

// node_modules/@x402/evm/dist/esm/exact/client/index.mjs
var init_client2 = __esm({
  "node_modules/@x402/evm/dist/esm/exact/client/index.mjs"() {
    "use strict";
    init_chunk_664BKEHK();
    init_chunk_EVC7K4OP();
    init_chunk_WKBC5YMI();
    init_chunk_CRT6YNY5();
    init_chunk_C4ZQMS77();
  }
});

// node_modules/@x402/evm/dist/esm/chunk-VZDOZ2BW.mjs
var init_chunk_VZDOZ2BW = __esm({
  "node_modules/@x402/evm/dist/esm/chunk-VZDOZ2BW.mjs"() {
    "use strict";
  }
});

// node_modules/@x402/evm/dist/esm/chunk-JII456TS.mjs
var init_chunk_JII456TS = __esm({
  "node_modules/@x402/evm/dist/esm/chunk-JII456TS.mjs"() {
    "use strict";
  }
});

// node_modules/@x402/evm/dist/esm/chunk-GJ57SZGI.mjs
var init_chunk_GJ57SZGI = __esm({
  "node_modules/@x402/evm/dist/esm/chunk-GJ57SZGI.mjs"() {
    "use strict";
    init_chunk_WKBC5YMI();
    init_chunk_C4ZQMS77();
  }
});

// node_modules/@x402/evm/dist/esm/index.mjs
function toClientEvmSigner(signer, publicClient) {
  const readContract2 = signer.readContract ?? publicClient?.readContract.bind(publicClient);
  const result = {
    address: signer.address,
    signTypedData: (msg) => signer.signTypedData(msg)
  };
  if (readContract2) {
    result.readContract = readContract2;
  }
  const signTransaction3 = signer.signTransaction;
  if (signTransaction3) {
    result.signTransaction = (args) => signTransaction3(args);
  }
  const getTransactionCount2 = signer.getTransactionCount ?? publicClient?.getTransactionCount?.bind(publicClient);
  if (getTransactionCount2) {
    result.getTransactionCount = (args) => getTransactionCount2(args);
  }
  const estimateFeesPerGas2 = signer.estimateFeesPerGas ?? publicClient?.estimateFeesPerGas?.bind(publicClient);
  if (estimateFeesPerGas2) {
    result.estimateFeesPerGas = () => estimateFeesPerGas2();
  }
  return result;
}
var init_esm5 = __esm({
  "node_modules/@x402/evm/dist/esm/index.mjs"() {
    "use strict";
    init_chunk_664BKEHK();
    init_chunk_VZDOZ2BW();
    init_chunk_JII456TS();
    init_chunk_EVC7K4OP();
    init_chunk_GJ57SZGI();
    init_chunk_WKBC5YMI();
    init_chunk_CRT6YNY5();
    init_chunk_C4ZQMS77();
  }
});

// src/router/rules.ts
function scoreTokenCount(estimatedTokens, thresholds) {
  if (estimatedTokens < thresholds.simple) {
    return { name: "tokenCount", score: -1, signal: `short (${estimatedTokens} tokens)` };
  }
  if (estimatedTokens > thresholds.complex) {
    return { name: "tokenCount", score: 1, signal: `long (${estimatedTokens} tokens)` };
  }
  return { name: "tokenCount", score: 0, signal: null };
}
function scoreKeywordMatch(text, keywords, name, signalLabel, thresholds, scores) {
  const matches = keywords.filter((kw) => text.includes(kw.toLowerCase()));
  if (matches.length >= thresholds.high) {
    return {
      name,
      score: scores.high,
      signal: `${signalLabel} (${matches.slice(0, 3).join(", ")})`
    };
  }
  if (matches.length >= thresholds.low) {
    return {
      name,
      score: scores.low,
      signal: `${signalLabel} (${matches.slice(0, 3).join(", ")})`
    };
  }
  return { name, score: scores.none, signal: null };
}
function scoreMultiStep(text) {
  const patterns = [/first.*then/i, /step \d/i, /\d\.\s/];
  const hits = patterns.filter((p) => p.test(text));
  if (hits.length > 0) {
    return { name: "multiStepPatterns", score: 0.5, signal: "multi-step" };
  }
  return { name: "multiStepPatterns", score: 0, signal: null };
}
function scoreQuestionComplexity(prompt) {
  const count = (prompt.match(/\?/g) || []).length;
  if (count > 3) {
    return { name: "questionComplexity", score: 0.5, signal: `${count} questions` };
  }
  return { name: "questionComplexity", score: 0, signal: null };
}
function scoreAgenticTask(text, keywords) {
  let matchCount = 0;
  const signals = [];
  for (const keyword of keywords) {
    if (text.includes(keyword.toLowerCase())) {
      matchCount++;
      if (signals.length < 3) {
        signals.push(keyword);
      }
    }
  }
  if (matchCount >= 4) {
    return {
      dimensionScore: {
        name: "agenticTask",
        score: 1,
        signal: `agentic (${signals.join(", ")})`
      },
      agenticScore: 1
    };
  } else if (matchCount >= 3) {
    return {
      dimensionScore: {
        name: "agenticTask",
        score: 0.6,
        signal: `agentic (${signals.join(", ")})`
      },
      agenticScore: 0.6
    };
  } else if (matchCount >= 1) {
    return {
      dimensionScore: {
        name: "agenticTask",
        score: 0.2,
        signal: `agentic-light (${signals.join(", ")})`
      },
      agenticScore: 0.2
    };
  }
  return {
    dimensionScore: { name: "agenticTask", score: 0, signal: null },
    agenticScore: 0
  };
}
function classifyByRules(prompt, systemPrompt, estimatedTokens, config) {
  const userText = prompt.toLowerCase();
  const dimensions = [
    // Token count uses total estimated tokens (system + user) — context size matters for model selection
    scoreTokenCount(estimatedTokens, config.tokenCountThresholds),
    scoreKeywordMatch(
      userText,
      config.codeKeywords,
      "codePresence",
      "code",
      { low: 1, high: 2 },
      { none: 0, low: 0.5, high: 1 }
    ),
    scoreKeywordMatch(
      userText,
      config.reasoningKeywords,
      "reasoningMarkers",
      "reasoning",
      { low: 1, high: 2 },
      { none: 0, low: 0.7, high: 1 }
    ),
    scoreKeywordMatch(
      userText,
      config.technicalKeywords,
      "technicalTerms",
      "technical",
      { low: 2, high: 4 },
      { none: 0, low: 0.5, high: 1 }
    ),
    scoreKeywordMatch(
      userText,
      config.creativeKeywords,
      "creativeMarkers",
      "creative",
      { low: 1, high: 2 },
      { none: 0, low: 0.5, high: 0.7 }
    ),
    scoreKeywordMatch(
      userText,
      config.simpleKeywords,
      "simpleIndicators",
      "simple",
      { low: 1, high: 2 },
      { none: 0, low: -1, high: -1 }
    ),
    scoreMultiStep(userText),
    scoreQuestionComplexity(prompt),
    // 6 new dimensions
    scoreKeywordMatch(
      userText,
      config.imperativeVerbs,
      "imperativeVerbs",
      "imperative",
      { low: 1, high: 2 },
      { none: 0, low: 0.3, high: 0.5 }
    ),
    scoreKeywordMatch(
      userText,
      config.constraintIndicators,
      "constraintCount",
      "constraints",
      { low: 1, high: 3 },
      { none: 0, low: 0.3, high: 0.7 }
    ),
    scoreKeywordMatch(
      userText,
      config.outputFormatKeywords,
      "outputFormat",
      "format",
      { low: 1, high: 2 },
      { none: 0, low: 0.4, high: 0.7 }
    ),
    scoreKeywordMatch(
      userText,
      config.referenceKeywords,
      "referenceComplexity",
      "references",
      { low: 1, high: 2 },
      { none: 0, low: 0.3, high: 0.5 }
    ),
    scoreKeywordMatch(
      userText,
      config.negationKeywords,
      "negationComplexity",
      "negation",
      { low: 2, high: 3 },
      { none: 0, low: 0.3, high: 0.5 }
    ),
    scoreKeywordMatch(
      userText,
      config.domainSpecificKeywords,
      "domainSpecificity",
      "domain-specific",
      { low: 1, high: 2 },
      { none: 0, low: 0.5, high: 0.8 }
    )
  ];
  const agenticResult = scoreAgenticTask(userText, config.agenticTaskKeywords);
  dimensions.push(agenticResult.dimensionScore);
  const agenticScore = agenticResult.agenticScore;
  const signals = dimensions.filter((d) => d.signal !== null).map((d) => d.signal);
  const weights = config.dimensionWeights;
  let weightedScore = 0;
  for (const d of dimensions) {
    const w = weights[d.name] ?? 0;
    weightedScore += d.score * w;
  }
  const reasoningMatches = config.reasoningKeywords.filter(
    (kw) => userText.includes(kw.toLowerCase())
  );
  if (reasoningMatches.length >= 2) {
    const confidence2 = calibrateConfidence(
      Math.max(weightedScore, 0.3),
      // ensure positive for confidence calc
      config.confidenceSteepness
    );
    return {
      score: weightedScore,
      tier: "REASONING",
      confidence: Math.max(confidence2, 0.85),
      signals,
      agenticScore,
      dimensions
    };
  }
  const { simpleMedium, mediumComplex, complexReasoning } = config.tierBoundaries;
  let tier;
  let distanceFromBoundary;
  if (weightedScore < simpleMedium) {
    tier = "SIMPLE";
    distanceFromBoundary = simpleMedium - weightedScore;
  } else if (weightedScore < mediumComplex) {
    tier = "MEDIUM";
    distanceFromBoundary = Math.min(weightedScore - simpleMedium, mediumComplex - weightedScore);
  } else if (weightedScore < complexReasoning) {
    tier = "COMPLEX";
    distanceFromBoundary = Math.min(
      weightedScore - mediumComplex,
      complexReasoning - weightedScore
    );
  } else {
    tier = "REASONING";
    distanceFromBoundary = weightedScore - complexReasoning;
  }
  const confidence = calibrateConfidence(distanceFromBoundary, config.confidenceSteepness);
  if (confidence < config.confidenceThreshold) {
    return { score: weightedScore, tier: null, confidence, signals, agenticScore, dimensions };
  }
  return { score: weightedScore, tier, confidence, signals, agenticScore, dimensions };
}
function calibrateConfidence(distance, steepness) {
  return 1 / (1 + Math.exp(-steepness * distance));
}
var init_rules = __esm({
  "src/router/rules.ts"() {
    "use strict";
  }
});

// src/router/selector.ts
function selectModel(tier, confidence, method, reasoning, tierConfigs, modelPricing, estimatedInputTokens, maxOutputTokens, routingProfile, agenticScore) {
  const tierConfig = tierConfigs[tier];
  const model = tierConfig.primary;
  const pricing = modelPricing.get(model);
  let costEstimate;
  if (pricing?.flatPrice !== void 0) {
    costEstimate = pricing.flatPrice;
  } else {
    const inputPrice = pricing?.inputPrice ?? 0;
    const outputPrice = pricing?.outputPrice ?? 0;
    costEstimate = estimatedInputTokens / 1e6 * inputPrice + maxOutputTokens / 1e6 * outputPrice;
  }
  const opusPricing = modelPricing.get(BASELINE_MODEL_ID);
  const opusInputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE;
  const opusOutputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE;
  const baselineInput = estimatedInputTokens / 1e6 * opusInputPrice;
  const baselineOutput = maxOutputTokens / 1e6 * opusOutputPrice;
  const baselineCost = baselineInput + baselineOutput;
  const savings = routingProfile === "premium" ? 0 : baselineCost > 0 ? Math.max(0, (baselineCost - costEstimate) / baselineCost) : 0;
  return {
    model,
    tier,
    confidence,
    method,
    reasoning,
    costEstimate,
    baselineCost,
    savings,
    ...agenticScore !== void 0 && { agenticScore }
  };
}
function getFallbackChain(tier, tierConfigs) {
  const config = tierConfigs[tier];
  return [config.primary, ...config.fallback];
}
function calculateModelCost(model, modelPricing, estimatedInputTokens, maxOutputTokens, routingProfile) {
  const pricing = modelPricing.get(model);
  let costEstimate;
  if (pricing?.flatPrice !== void 0) {
    costEstimate = Math.max(pricing.flatPrice * (1 + SERVER_MARGIN_PERCENT / 100), MIN_PAYMENT_USD);
  } else {
    const inputPrice = pricing?.inputPrice ?? 0;
    const outputPrice = pricing?.outputPrice ?? 0;
    const inputCost = estimatedInputTokens / 1e6 * inputPrice;
    const outputCost = maxOutputTokens / 1e6 * outputPrice;
    costEstimate = Math.max(
      (inputCost + outputCost) * (1 + SERVER_MARGIN_PERCENT / 100),
      MIN_PAYMENT_USD
    );
  }
  const opusPricing = modelPricing.get(BASELINE_MODEL_ID);
  const opusInputPrice = opusPricing?.inputPrice ?? BASELINE_INPUT_PRICE;
  const opusOutputPrice = opusPricing?.outputPrice ?? BASELINE_OUTPUT_PRICE;
  const baselineInput = estimatedInputTokens / 1e6 * opusInputPrice;
  const baselineOutput = maxOutputTokens / 1e6 * opusOutputPrice;
  const baselineCost = baselineInput + baselineOutput;
  const savings = routingProfile === "premium" ? 0 : baselineCost > 0 ? Math.max(0, (baselineCost - costEstimate) / baselineCost) : 0;
  return { costEstimate, baselineCost, savings };
}
function filterByToolCalling(models, hasTools, supportsToolCalling2) {
  if (!hasTools) return models;
  const filtered = models.filter(supportsToolCalling2);
  return filtered.length > 0 ? filtered : models;
}
function filterByVision(models, hasVision, supportsVision2) {
  if (!hasVision) return models;
  const filtered = models.filter(supportsVision2);
  return filtered.length > 0 ? filtered : models;
}
function filterByExcludeList(models, excludeList) {
  if (excludeList.size === 0) return models;
  const filtered = models.filter((m) => !excludeList.has(m));
  return filtered.length > 0 ? filtered : models;
}
function getFallbackChainFiltered(tier, tierConfigs, estimatedTotalTokens, getContextWindow) {
  const fullChain = getFallbackChain(tier, tierConfigs);
  const filtered = fullChain.filter((modelId) => {
    const contextWindow = getContextWindow(modelId);
    if (contextWindow === void 0) {
      return true;
    }
    return contextWindow >= estimatedTotalTokens * 1.1;
  });
  if (filtered.length === 0) {
    return fullChain;
  }
  return filtered;
}
var BASELINE_MODEL_ID, BASELINE_INPUT_PRICE, BASELINE_OUTPUT_PRICE, SERVER_MARGIN_PERCENT, MIN_PAYMENT_USD;
var init_selector = __esm({
  "src/router/selector.ts"() {
    "use strict";
    BASELINE_MODEL_ID = "anthropic/claude-opus-4.7";
    BASELINE_INPUT_PRICE = 5;
    BASELINE_OUTPUT_PRICE = 25;
    SERVER_MARGIN_PERCENT = 5;
    MIN_PAYMENT_USD = 1e-3;
  }
});

// src/router/strategy.ts
function applyPromotions(tierConfigs, promotions, profile, now = /* @__PURE__ */ new Date()) {
  if (!promotions || promotions.length === 0) return tierConfigs;
  let result = tierConfigs;
  for (const promo of promotions) {
    const start = new Date(promo.startDate);
    const end = new Date(promo.endDate);
    if (now < start || now >= end) continue;
    if (promo.profiles && !promo.profiles.includes(profile)) continue;
    if (result === tierConfigs) {
      result = { ...tierConfigs };
      for (const t of Object.keys(result)) {
        result[t] = { ...result[t] };
      }
    }
    for (const [tier, override] of Object.entries(promo.tierOverrides)) {
      if (!result[tier]) continue;
      if (override.primary) result[tier].primary = override.primary;
      if (override.fallback) result[tier].fallback = override.fallback;
    }
  }
  return result;
}
function getStrategy(name) {
  const strategy = registry.get(name);
  if (!strategy) {
    throw new Error(`Unknown routing strategy: ${name}`);
  }
  return strategy;
}
var RulesStrategy, registry;
var init_strategy = __esm({
  "src/router/strategy.ts"() {
    "use strict";
    init_rules();
    init_selector();
    RulesStrategy = class {
      name = "rules";
      route(prompt, systemPrompt, maxOutputTokens, options) {
        const { config, modelPricing } = options;
        const fullText = `${systemPrompt ?? ""} ${prompt}`;
        const estimatedTokens = Math.ceil(fullText.length / 4);
        const ruleResult = classifyByRules(prompt, systemPrompt, estimatedTokens, config.scoring);
        const { routingProfile } = options;
        let tierConfigs;
        let profileSuffix;
        let profile;
        if (routingProfile === "eco") {
          tierConfigs = config.ecoTiers ?? config.tiers;
          profileSuffix = config.ecoTiers ? " | eco" : " | eco (default tiers)";
          profile = "eco";
        } else if (routingProfile === "premium") {
          tierConfigs = config.premiumTiers ?? config.tiers;
          profileSuffix = config.premiumTiers ? " | premium" : " | premium (default tiers)";
          profile = "premium";
        } else {
          const agenticScore = ruleResult.agenticScore ?? 0;
          const isAutoAgentic = agenticScore >= 0.5;
          const agenticModeSetting = config.overrides.agenticMode;
          const hasToolsInRequest = options.hasTools ?? false;
          let useAgenticTiers;
          if (agenticModeSetting === false) {
            useAgenticTiers = false;
          } else if (agenticModeSetting === true) {
            useAgenticTiers = config.agenticTiers != null;
          } else {
            useAgenticTiers = (hasToolsInRequest || isAutoAgentic) && config.agenticTiers != null;
          }
          tierConfigs = useAgenticTiers ? config.agenticTiers : config.tiers;
          profileSuffix = useAgenticTiers ? ` | agentic${hasToolsInRequest ? " (tools)" : ""}` : "";
          profile = useAgenticTiers ? "agentic" : "auto";
        }
        tierConfigs = applyPromotions(tierConfigs, config.promotions, profile, options.now);
        const agenticScoreValue = ruleResult.agenticScore;
        if (estimatedTokens > config.overrides.maxTokensForceComplex) {
          const decision2 = selectModel(
            "COMPLEX",
            0.95,
            "rules",
            `Input exceeds ${config.overrides.maxTokensForceComplex} tokens${profileSuffix}`,
            tierConfigs,
            modelPricing,
            estimatedTokens,
            maxOutputTokens,
            routingProfile,
            agenticScoreValue
          );
          return { ...decision2, tierConfigs, profile };
        }
        const hasStructuredOutput = systemPrompt ? /json|structured|schema/i.test(systemPrompt) : false;
        let tier;
        let confidence;
        const method = "rules";
        let reasoning = `score=${ruleResult.score.toFixed(2)} | ${ruleResult.signals.join(", ")}`;
        if (ruleResult.tier !== null) {
          tier = ruleResult.tier;
          confidence = ruleResult.confidence;
        } else {
          tier = config.overrides.ambiguousDefaultTier;
          confidence = 0.5;
          reasoning += ` | ambiguous -> default: ${tier}`;
        }
        if (hasStructuredOutput) {
          const tierRank = { SIMPLE: 0, MEDIUM: 1, COMPLEX: 2, REASONING: 3 };
          const minTier = config.overrides.structuredOutputMinTier;
          if (tierRank[tier] < tierRank[minTier]) {
            reasoning += ` | upgraded to ${minTier} (structured output)`;
            tier = minTier;
          }
        }
        reasoning += profileSuffix;
        const decision = selectModel(
          tier,
          confidence,
          method,
          reasoning,
          tierConfigs,
          modelPricing,
          estimatedTokens,
          maxOutputTokens,
          routingProfile,
          agenticScoreValue
        );
        return { ...decision, tierConfigs, profile };
      }
    };
    registry = /* @__PURE__ */ new Map();
    registry.set("rules", new RulesStrategy());
  }
});

// src/router/config.ts
var DEFAULT_ROUTING_CONFIG;
var init_config = __esm({
  "src/router/config.ts"() {
    "use strict";
    DEFAULT_ROUTING_CONFIG = {
      version: "2.0",
      classifier: {
        llmModel: "google/gemini-2.5-flash",
        llmMaxTokens: 10,
        llmTemperature: 0,
        promptTruncationChars: 500,
        cacheTtlMs: 36e5
        // 1 hour
      },
      scoring: {
        tokenCountThresholds: { simple: 50, complex: 500 },
        // Multilingual keywords: EN + ZH + JA + RU + DE + ES + PT + KO + AR
        codeKeywords: [
          // English
          "function",
          "class",
          "import",
          "def",
          "SELECT",
          "async",
          "await",
          "const",
          "let",
          "var",
          "return",
          "```",
          // Chinese
          "\u51FD\u6570",
          "\u7C7B",
          "\u5BFC\u5165",
          "\u5B9A\u4E49",
          "\u67E5\u8BE2",
          "\u5F02\u6B65",
          "\u7B49\u5F85",
          "\u5E38\u91CF",
          "\u53D8\u91CF",
          "\u8FD4\u56DE",
          // Japanese
          "\u95A2\u6570",
          "\u30AF\u30E9\u30B9",
          "\u30A4\u30F3\u30DD\u30FC\u30C8",
          "\u975E\u540C\u671F",
          "\u5B9A\u6570",
          "\u5909\u6570",
          // Russian
          "\u0444\u0443\u043D\u043A\u0446\u0438\u044F",
          "\u043A\u043B\u0430\u0441\u0441",
          "\u0438\u043C\u043F\u043E\u0440\u0442",
          "\u043E\u043F\u0440\u0435\u0434\u0435\u043B",
          "\u0437\u0430\u043F\u0440\u043E\u0441",
          "\u0430\u0441\u0438\u043D\u0445\u0440\u043E\u043D\u043D\u044B\u0439",
          "\u043E\u0436\u0438\u0434\u0430\u0442\u044C",
          "\u043A\u043E\u043D\u0441\u0442\u0430\u043D\u0442\u0430",
          "\u043F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u0430\u044F",
          "\u0432\u0435\u0440\u043D\u0443\u0442\u044C",
          // German
          "funktion",
          "klasse",
          "importieren",
          "definieren",
          "abfrage",
          "asynchron",
          "erwarten",
          "konstante",
          "variable",
          "zur\xFCckgeben",
          // Spanish
          "funci\xF3n",
          "clase",
          "importar",
          "definir",
          "consulta",
          "as\xEDncrono",
          "esperar",
          "constante",
          "variable",
          "retornar",
          // Portuguese
          "fun\xE7\xE3o",
          "classe",
          "importar",
          "definir",
          "consulta",
          "ass\xEDncrono",
          "aguardar",
          "constante",
          "vari\xE1vel",
          "retornar",
          // Korean
          "\uD568\uC218",
          "\uD074\uB798\uC2A4",
          "\uAC00\uC838\uC624\uAE30",
          "\uC815\uC758",
          "\uCFFC\uB9AC",
          "\uBE44\uB3D9\uAE30",
          "\uB300\uAE30",
          "\uC0C1\uC218",
          "\uBCC0\uC218",
          "\uBC18\uD658",
          // Arabic
          "\u062F\u0627\u0644\u0629",
          "\u0641\u0626\u0629",
          "\u0627\u0633\u062A\u064A\u0631\u0627\u062F",
          "\u062A\u0639\u0631\u064A\u0641",
          "\u0627\u0633\u062A\u0639\u0644\u0627\u0645",
          "\u063A\u064A\u0631 \u0645\u062A\u0632\u0627\u0645\u0646",
          "\u0627\u0646\u062A\u0638\u0627\u0631",
          "\u062B\u0627\u0628\u062A",
          "\u0645\u062A\u063A\u064A\u0631",
          "\u0625\u0631\u062C\u0627\u0639"
        ],
        reasoningKeywords: [
          // English
          "prove",
          "theorem",
          "derive",
          "step by step",
          "chain of thought",
          "formally",
          "mathematical",
          "proof",
          "logically",
          // Chinese
          "\u8BC1\u660E",
          "\u5B9A\u7406",
          "\u63A8\u5BFC",
          "\u9010\u6B65",
          "\u601D\u7EF4\u94FE",
          "\u5F62\u5F0F\u5316",
          "\u6570\u5B66",
          "\u903B\u8F91",
          // Japanese
          "\u8A3C\u660E",
          "\u5B9A\u7406",
          "\u5C0E\u51FA",
          "\u30B9\u30C6\u30C3\u30D7\u30D0\u30A4\u30B9\u30C6\u30C3\u30D7",
          "\u8AD6\u7406\u7684",
          // Russian
          "\u0434\u043E\u043A\u0430\u0437\u0430\u0442\u044C",
          "\u0434\u043E\u043A\u0430\u0436\u0438",
          "\u0434\u043E\u043A\u0430\u0437\u0430\u0442\u0435\u043B\u044C\u0441\u0442\u0432",
          "\u0442\u0435\u043E\u0440\u0435\u043C\u0430",
          "\u0432\u044B\u0432\u0435\u0441\u0442\u0438",
          "\u0448\u0430\u0433 \u0437\u0430 \u0448\u0430\u0433\u043E\u043C",
          "\u043F\u043E\u0448\u0430\u0433\u043E\u0432\u043E",
          "\u043F\u043E\u044D\u0442\u0430\u043F\u043D\u043E",
          "\u0446\u0435\u043F\u043E\u0447\u043A\u0430 \u0440\u0430\u0441\u0441\u0443\u0436\u0434\u0435\u043D\u0438\u0439",
          "\u0440\u0430\u0441\u0441\u0443\u0436\u0434\u0435\u043D\u0438",
          "\u0444\u043E\u0440\u043C\u0430\u043B\u044C\u043D\u043E",
          "\u043C\u0430\u0442\u0435\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438",
          "\u043B\u043E\u0433\u0438\u0447\u0435\u0441\u043A\u0438",
          // German
          "beweisen",
          "beweis",
          "theorem",
          "ableiten",
          "schritt f\xFCr schritt",
          "gedankenkette",
          "formal",
          "mathematisch",
          "logisch",
          // Spanish
          "demostrar",
          "teorema",
          "derivar",
          "paso a paso",
          "cadena de pensamiento",
          "formalmente",
          "matem\xE1tico",
          "prueba",
          "l\xF3gicamente",
          // Portuguese
          "provar",
          "teorema",
          "derivar",
          "passo a passo",
          "cadeia de pensamento",
          "formalmente",
          "matem\xE1tico",
          "prova",
          "logicamente",
          // Korean
          "\uC99D\uBA85",
          "\uC815\uB9AC",
          "\uB3C4\uCD9C",
          "\uB2E8\uACC4\uBCC4",
          "\uC0AC\uACE0\uC758 \uC5F0\uC1C4",
          "\uD615\uC2DD\uC801",
          "\uC218\uD559\uC801",
          "\uB17C\uB9AC\uC801",
          // Arabic
          "\u0625\u062B\u0628\u0627\u062A",
          "\u0646\u0638\u0631\u064A\u0629",
          "\u0627\u0634\u062A\u0642\u0627\u0642",
          "\u062E\u0637\u0648\u0629 \u0628\u062E\u0637\u0648\u0629",
          "\u0633\u0644\u0633\u0644\u0629 \u0627\u0644\u062A\u0641\u0643\u064A\u0631",
          "\u0631\u0633\u0645\u064A\u0627\u064B",
          "\u0631\u064A\u0627\u0636\u064A",
          "\u0628\u0631\u0647\u0627\u0646",
          "\u0645\u0646\u0637\u0642\u064A\u0627\u064B"
        ],
        simpleKeywords: [
          // English
          "what is",
          "define",
          "translate",
          "hello",
          "yes or no",
          "capital of",
          "how old",
          "who is",
          "when was",
          // Chinese
          "\u4EC0\u4E48\u662F",
          "\u5B9A\u4E49",
          "\u7FFB\u8BD1",
          "\u4F60\u597D",
          "\u662F\u5426",
          "\u9996\u90FD",
          "\u591A\u5927",
          "\u8C01\u662F",
          "\u4F55\u65F6",
          // Japanese
          "\u3068\u306F",
          "\u5B9A\u7FA9",
          "\u7FFB\u8A33",
          "\u3053\u3093\u306B\u3061\u306F",
          "\u306F\u3044\u304B\u3044\u3044\u3048",
          "\u9996\u90FD",
          "\u8AB0",
          // Russian
          "\u0447\u0442\u043E \u0442\u0430\u043A\u043E\u0435",
          "\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435",
          "\u043F\u0435\u0440\u0435\u0432\u0435\u0441\u0442\u0438",
          "\u043F\u0435\u0440\u0435\u0432\u0435\u0434\u0438",
          "\u043F\u0440\u0438\u0432\u0435\u0442",
          "\u0434\u0430 \u0438\u043B\u0438 \u043D\u0435\u0442",
          "\u0441\u0442\u043E\u043B\u0438\u0446\u0430",
          "\u0441\u043A\u043E\u043B\u044C\u043A\u043E \u043B\u0435\u0442",
          "\u043A\u0442\u043E \u0442\u0430\u043A\u043E\u0439",
          "\u043A\u043E\u0433\u0434\u0430",
          "\u043E\u0431\u044A\u044F\u0441\u043D\u0438",
          // German
          "was ist",
          "definiere",
          "\xFCbersetze",
          "hallo",
          "ja oder nein",
          "hauptstadt",
          "wie alt",
          "wer ist",
          "wann",
          "erkl\xE4re",
          // Spanish
          "qu\xE9 es",
          "definir",
          "traducir",
          "hola",
          "s\xED o no",
          "capital de",
          "cu\xE1ntos a\xF1os",
          "qui\xE9n es",
          "cu\xE1ndo",
          // Portuguese
          "o que \xE9",
          "definir",
          "traduzir",
          "ol\xE1",
          "sim ou n\xE3o",
          "capital de",
          "quantos anos",
          "quem \xE9",
          "quando",
          // Korean
          "\uBB34\uC5C7",
          "\uC815\uC758",
          "\uBC88\uC5ED",
          "\uC548\uB155\uD558\uC138\uC694",
          "\uC608 \uB610\uB294 \uC544\uB2C8\uC624",
          "\uC218\uB3C4",
          "\uB204\uAD6C",
          "\uC5B8\uC81C",
          // Arabic
          "\u0645\u0627 \u0647\u0648",
          "\u062A\u0639\u0631\u064A\u0641",
          "\u062A\u0631\u062C\u0645",
          "\u0645\u0631\u062D\u0628\u0627",
          "\u0646\u0639\u0645 \u0623\u0648 \u0644\u0627",
          "\u0639\u0627\u0635\u0645\u0629",
          "\u0645\u0646 \u0647\u0648",
          "\u0645\u062A\u0649"
        ],
        technicalKeywords: [
          // English
          "algorithm",
          "optimize",
          "architecture",
          "distributed",
          "kubernetes",
          "microservice",
          "database",
          "infrastructure",
          // Chinese
          "\u7B97\u6CD5",
          "\u4F18\u5316",
          "\u67B6\u6784",
          "\u5206\u5E03\u5F0F",
          "\u5FAE\u670D\u52A1",
          "\u6570\u636E\u5E93",
          "\u57FA\u7840\u8BBE\u65BD",
          // Japanese
          "\u30A2\u30EB\u30B4\u30EA\u30BA\u30E0",
          "\u6700\u9069\u5316",
          "\u30A2\u30FC\u30AD\u30C6\u30AF\u30C1\u30E3",
          "\u5206\u6563",
          "\u30DE\u30A4\u30AF\u30ED\u30B5\u30FC\u30D3\u30B9",
          "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9",
          // Russian
          "\u0430\u043B\u0433\u043E\u0440\u0438\u0442\u043C",
          "\u043E\u043F\u0442\u0438\u043C\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u0442\u044C",
          "\u043E\u043F\u0442\u0438\u043C\u0438\u0437\u0430\u0446\u0438",
          "\u043E\u043F\u0442\u0438\u043C\u0438\u0437\u0438\u0440\u0443\u0439",
          "\u0430\u0440\u0445\u0438\u0442\u0435\u043A\u0442\u0443\u0440\u0430",
          "\u0440\u0430\u0441\u043F\u0440\u0435\u0434\u0435\u043B\u0451\u043D\u043D\u044B\u0439",
          "\u043C\u0438\u043A\u0440\u043E\u0441\u0435\u0440\u0432\u0438\u0441",
          "\u0431\u0430\u0437\u0430 \u0434\u0430\u043D\u043D\u044B\u0445",
          "\u0438\u043D\u0444\u0440\u0430\u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u0430",
          // German
          "algorithmus",
          "optimieren",
          "architektur",
          "verteilt",
          "kubernetes",
          "mikroservice",
          "datenbank",
          "infrastruktur",
          // Spanish
          "algoritmo",
          "optimizar",
          "arquitectura",
          "distribuido",
          "microservicio",
          "base de datos",
          "infraestructura",
          // Portuguese
          "algoritmo",
          "otimizar",
          "arquitetura",
          "distribu\xEDdo",
          "microsservi\xE7o",
          "banco de dados",
          "infraestrutura",
          // Korean
          "\uC54C\uACE0\uB9AC\uC998",
          "\uCD5C\uC801\uD654",
          "\uC544\uD0A4\uD14D\uCC98",
          "\uBD84\uC0B0",
          "\uB9C8\uC774\uD06C\uB85C\uC11C\uBE44\uC2A4",
          "\uB370\uC774\uD130\uBCA0\uC774\uC2A4",
          "\uC778\uD504\uB77C",
          // Arabic
          "\u062E\u0648\u0627\u0631\u0632\u0645\u064A\u0629",
          "\u062A\u062D\u0633\u064A\u0646",
          "\u0628\u0646\u064A\u0629",
          "\u0645\u0648\u0632\u0639",
          "\u062E\u062F\u0645\u0629 \u0645\u0635\u063A\u0631\u0629",
          "\u0642\u0627\u0639\u062F\u0629 \u0628\u064A\u0627\u0646\u0627\u062A",
          "\u0628\u0646\u064A\u0629 \u062A\u062D\u062A\u064A\u0629"
        ],
        creativeKeywords: [
          // English
          "story",
          "poem",
          "compose",
          "brainstorm",
          "creative",
          "imagine",
          "write a",
          // Chinese
          "\u6545\u4E8B",
          "\u8BD7",
          "\u521B\u4F5C",
          "\u5934\u8111\u98CE\u66B4",
          "\u521B\u610F",
          "\u60F3\u8C61",
          "\u5199\u4E00\u4E2A",
          // Japanese
          "\u7269\u8A9E",
          "\u8A69",
          "\u4F5C\u66F2",
          "\u30D6\u30EC\u30A4\u30F3\u30B9\u30C8\u30FC\u30E0",
          "\u5275\u9020\u7684",
          "\u60F3\u50CF",
          // Russian
          "\u0438\u0441\u0442\u043E\u0440\u0438\u044F",
          "\u0440\u0430\u0441\u0441\u043A\u0430\u0437",
          "\u0441\u0442\u0438\u0445\u043E\u0442\u0432\u043E\u0440\u0435\u043D\u0438\u0435",
          "\u0441\u043E\u0447\u0438\u043D\u0438\u0442\u044C",
          "\u0441\u043E\u0447\u0438\u043D\u0438",
          "\u043C\u043E\u0437\u0433\u043E\u0432\u043E\u0439 \u0448\u0442\u0443\u0440\u043C",
          "\u0442\u0432\u043E\u0440\u0447\u0435\u0441\u043A\u0438\u0439",
          "\u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u0438\u0442\u044C",
          "\u043F\u0440\u0438\u0434\u0443\u043C\u0430\u0439",
          "\u043D\u0430\u043F\u0438\u0448\u0438",
          // German
          "geschichte",
          "gedicht",
          "komponieren",
          "brainstorming",
          "kreativ",
          "vorstellen",
          "schreibe",
          "erz\xE4hlung",
          // Spanish
          "historia",
          "poema",
          "componer",
          "lluvia de ideas",
          "creativo",
          "imaginar",
          "escribe",
          // Portuguese
          "hist\xF3ria",
          "poema",
          "compor",
          "criativo",
          "imaginar",
          "escreva",
          // Korean
          "\uC774\uC57C\uAE30",
          "\uC2DC",
          "\uC791\uACE1",
          "\uBE0C\uB808\uC778\uC2A4\uD1A0\uBC0D",
          "\uCC3D\uC758\uC801",
          "\uC0C1\uC0C1",
          "\uC791\uC131",
          // Arabic
          "\u0642\u0635\u0629",
          "\u0642\u0635\u064A\u062F\u0629",
          "\u062A\u0623\u0644\u064A\u0641",
          "\u0639\u0635\u0641 \u0630\u0647\u0646\u064A",
          "\u0625\u0628\u062F\u0627\u0639\u064A",
          "\u062A\u062E\u064A\u0644",
          "\u0627\u0643\u062A\u0628"
        ],
        // New dimension keyword lists (multilingual)
        imperativeVerbs: [
          // English
          "build",
          "create",
          "implement",
          "design",
          "develop",
          "construct",
          "generate",
          "deploy",
          "configure",
          "set up",
          // Chinese
          "\u6784\u5EFA",
          "\u521B\u5EFA",
          "\u5B9E\u73B0",
          "\u8BBE\u8BA1",
          "\u5F00\u53D1",
          "\u751F\u6210",
          "\u90E8\u7F72",
          "\u914D\u7F6E",
          "\u8BBE\u7F6E",
          // Japanese
          "\u69CB\u7BC9",
          "\u4F5C\u6210",
          "\u5B9F\u88C5",
          "\u8A2D\u8A08",
          "\u958B\u767A",
          "\u751F\u6210",
          "\u30C7\u30D7\u30ED\u30A4",
          "\u8A2D\u5B9A",
          // Russian
          "\u043F\u043E\u0441\u0442\u0440\u043E\u0438\u0442\u044C",
          "\u043F\u043E\u0441\u0442\u0440\u043E\u0439",
          "\u0441\u043E\u0437\u0434\u0430\u0442\u044C",
          "\u0441\u043E\u0437\u0434\u0430\u0439",
          "\u0440\u0435\u0430\u043B\u0438\u0437\u043E\u0432\u0430\u0442\u044C",
          "\u0440\u0435\u0430\u043B\u0438\u0437\u0443\u0439",
          "\u0441\u043F\u0440\u043E\u0435\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C",
          "\u0440\u0430\u0437\u0440\u0430\u0431\u043E\u0442\u0430\u0442\u044C",
          "\u0440\u0430\u0437\u0440\u0430\u0431\u043E\u0442\u0430\u0439",
          "\u0441\u043A\u043E\u043D\u0441\u0442\u0440\u0443\u0438\u0440\u043E\u0432\u0430\u0442\u044C",
          "\u0441\u0433\u0435\u043D\u0435\u0440\u0438\u0440\u043E\u0432\u0430\u0442\u044C",
          "\u0441\u0433\u0435\u043D\u0435\u0440\u0438\u0440\u0443\u0439",
          "\u0440\u0430\u0437\u0432\u0435\u0440\u043D\u0443\u0442\u044C",
          "\u0440\u0430\u0437\u0432\u0435\u0440\u043D\u0438",
          "\u043D\u0430\u0441\u0442\u0440\u043E\u0438\u0442\u044C",
          "\u043D\u0430\u0441\u0442\u0440\u043E\u0439",
          // German
          "erstellen",
          "bauen",
          "implementieren",
          "entwerfen",
          "entwickeln",
          "konstruieren",
          "generieren",
          "bereitstellen",
          "konfigurieren",
          "einrichten",
          // Spanish
          "construir",
          "crear",
          "implementar",
          "dise\xF1ar",
          "desarrollar",
          "generar",
          "desplegar",
          "configurar",
          // Portuguese
          "construir",
          "criar",
          "implementar",
          "projetar",
          "desenvolver",
          "gerar",
          "implantar",
          "configurar",
          // Korean
          "\uAD6C\uCD95",
          "\uC0DD\uC131",
          "\uAD6C\uD604",
          "\uC124\uACC4",
          "\uAC1C\uBC1C",
          "\uBC30\uD3EC",
          "\uC124\uC815",
          // Arabic
          "\u0628\u0646\u0627\u0621",
          "\u0625\u0646\u0634\u0627\u0621",
          "\u062A\u0646\u0641\u064A\u0630",
          "\u062A\u0635\u0645\u064A\u0645",
          "\u062A\u0637\u0648\u064A\u0631",
          "\u062A\u0648\u0644\u064A\u062F",
          "\u0646\u0634\u0631",
          "\u0625\u0639\u062F\u0627\u062F"
        ],
        constraintIndicators: [
          // English
          "under",
          "at most",
          "at least",
          "within",
          "no more than",
          "o(",
          "maximum",
          "minimum",
          "limit",
          "budget",
          // Chinese
          "\u4E0D\u8D85\u8FC7",
          "\u81F3\u5C11",
          "\u6700\u591A",
          "\u5728\u5185",
          "\u6700\u5927",
          "\u6700\u5C0F",
          "\u9650\u5236",
          "\u9884\u7B97",
          // Japanese
          "\u4EE5\u4E0B",
          "\u6700\u5927",
          "\u6700\u5C0F",
          "\u5236\u9650",
          "\u4E88\u7B97",
          // Russian
          "\u043D\u0435 \u0431\u043E\u043B\u0435\u0435",
          "\u043D\u0435 \u043C\u0435\u043D\u0435\u0435",
          "\u043A\u0430\u043A \u043C\u0438\u043D\u0438\u043C\u0443\u043C",
          "\u0432 \u043F\u0440\u0435\u0434\u0435\u043B\u0430\u0445",
          "\u043C\u0430\u043A\u0441\u0438\u043C\u0443\u043C",
          "\u043C\u0438\u043D\u0438\u043C\u0443\u043C",
          "\u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0435\u043D\u0438\u0435",
          "\u0431\u044E\u0434\u0436\u0435\u0442",
          // German
          "h\xF6chstens",
          "mindestens",
          "innerhalb",
          "nicht mehr als",
          "maximal",
          "minimal",
          "grenze",
          "budget",
          // Spanish
          "como m\xE1ximo",
          "al menos",
          "dentro de",
          "no m\xE1s de",
          "m\xE1ximo",
          "m\xEDnimo",
          "l\xEDmite",
          "presupuesto",
          // Portuguese
          "no m\xE1ximo",
          "pelo menos",
          "dentro de",
          "n\xE3o mais que",
          "m\xE1ximo",
          "m\xEDnimo",
          "limite",
          "or\xE7amento",
          // Korean
          "\uC774\uD558",
          "\uC774\uC0C1",
          "\uCD5C\uB300",
          "\uCD5C\uC18C",
          "\uC81C\uD55C",
          "\uC608\uC0B0",
          // Arabic
          "\u0639\u0644\u0649 \u0627\u0644\u0623\u0643\u062B\u0631",
          "\u0639\u0644\u0649 \u0627\u0644\u0623\u0642\u0644",
          "\u0636\u0645\u0646",
          "\u0644\u0627 \u064A\u0632\u064A\u062F \u0639\u0646",
          "\u0623\u0642\u0635\u0649",
          "\u0623\u062F\u0646\u0649",
          "\u062D\u062F",
          "\u0645\u064A\u0632\u0627\u0646\u064A\u0629"
        ],
        outputFormatKeywords: [
          // English
          "json",
          "yaml",
          "xml",
          "table",
          "csv",
          "markdown",
          "schema",
          "format as",
          "structured",
          // Chinese
          "\u8868\u683C",
          "\u683C\u5F0F\u5316\u4E3A",
          "\u7ED3\u6784\u5316",
          // Japanese
          "\u30C6\u30FC\u30D6\u30EB",
          "\u30D5\u30A9\u30FC\u30DE\u30C3\u30C8",
          "\u69CB\u9020\u5316",
          // Russian
          "\u0442\u0430\u0431\u043B\u0438\u0446\u0430",
          "\u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u043A\u0430\u043A",
          "\u0441\u0442\u0440\u0443\u043A\u0442\u0443\u0440\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439",
          // German
          "tabelle",
          "formatieren als",
          "strukturiert",
          // Spanish
          "tabla",
          "formatear como",
          "estructurado",
          // Portuguese
          "tabela",
          "formatar como",
          "estruturado",
          // Korean
          "\uD14C\uC774\uBE14",
          "\uD615\uC2DD",
          "\uAD6C\uC870\uD654",
          // Arabic
          "\u062C\u062F\u0648\u0644",
          "\u062A\u0646\u0633\u064A\u0642",
          "\u0645\u0646\u0638\u0645"
        ],
        referenceKeywords: [
          // English
          "above",
          "below",
          "previous",
          "following",
          "the docs",
          "the api",
          "the code",
          "earlier",
          "attached",
          // Chinese
          "\u4E0A\u9762",
          "\u4E0B\u9762",
          "\u4E4B\u524D",
          "\u63A5\u4E0B\u6765",
          "\u6587\u6863",
          "\u4EE3\u7801",
          "\u9644\u4EF6",
          // Japanese
          "\u4E0A\u8A18",
          "\u4E0B\u8A18",
          "\u524D\u306E",
          "\u6B21\u306E",
          "\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8",
          "\u30B3\u30FC\u30C9",
          // Russian
          "\u0432\u044B\u0448\u0435",
          "\u043D\u0438\u0436\u0435",
          "\u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0438\u0439",
          "\u0441\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0439",
          "\u0434\u043E\u043A\u0443\u043C\u0435\u043D\u0442\u0430\u0446\u0438\u044F",
          "\u043A\u043E\u0434",
          "\u0440\u0430\u043D\u0435\u0435",
          "\u0432\u043B\u043E\u0436\u0435\u043D\u0438\u0435",
          // German
          "oben",
          "unten",
          "vorherige",
          "folgende",
          "dokumentation",
          "der code",
          "fr\xFCher",
          "anhang",
          // Spanish
          "arriba",
          "abajo",
          "anterior",
          "siguiente",
          "documentaci\xF3n",
          "el c\xF3digo",
          "adjunto",
          // Portuguese
          "acima",
          "abaixo",
          "anterior",
          "seguinte",
          "documenta\xE7\xE3o",
          "o c\xF3digo",
          "anexo",
          // Korean
          "\uC704",
          "\uC544\uB798",
          "\uC774\uC804",
          "\uB2E4\uC74C",
          "\uBB38\uC11C",
          "\uCF54\uB4DC",
          "\uCCA8\uBD80",
          // Arabic
          "\u0623\u0639\u0644\u0627\u0647",
          "\u0623\u062F\u0646\u0627\u0647",
          "\u0627\u0644\u0633\u0627\u0628\u0642",
          "\u0627\u0644\u062A\u0627\u0644\u064A",
          "\u0627\u0644\u0648\u062B\u0627\u0626\u0642",
          "\u0627\u0644\u0643\u0648\u062F",
          "\u0645\u0631\u0641\u0642"
        ],
        negationKeywords: [
          // English
          "don't",
          "do not",
          "avoid",
          "never",
          "without",
          "except",
          "exclude",
          "no longer",
          // Chinese
          "\u4E0D\u8981",
          "\u907F\u514D",
          "\u4ECE\u4E0D",
          "\u6CA1\u6709",
          "\u9664\u4E86",
          "\u6392\u9664",
          // Japanese
          "\u3057\u306A\u3044\u3067",
          "\u907F\u3051\u308B",
          "\u6C7A\u3057\u3066",
          "\u306A\u3057\u3067",
          "\u9664\u304F",
          // Russian
          "\u043D\u0435 \u0434\u0435\u043B\u0430\u0439",
          "\u043D\u0435 \u043D\u0430\u0434\u043E",
          "\u043D\u0435\u043B\u044C\u0437\u044F",
          "\u0438\u0437\u0431\u0435\u0433\u0430\u0442\u044C",
          "\u043D\u0438\u043A\u043E\u0433\u0434\u0430",
          "\u0431\u0435\u0437",
          "\u043A\u0440\u043E\u043C\u0435",
          "\u0438\u0441\u043A\u043B\u044E\u0447\u0438\u0442\u044C",
          "\u0431\u043E\u043B\u044C\u0448\u0435 \u043D\u0435",
          // German
          "nicht",
          "vermeide",
          "niemals",
          "ohne",
          "au\xDFer",
          "ausschlie\xDFen",
          "nicht mehr",
          // Spanish
          "no hagas",
          "evitar",
          "nunca",
          "sin",
          "excepto",
          "excluir",
          // Portuguese
          "n\xE3o fa\xE7a",
          "evitar",
          "nunca",
          "sem",
          "exceto",
          "excluir",
          // Korean
          "\uD558\uC9C0 \uB9C8",
          "\uD53C\uD558\uB2E4",
          "\uC808\uB300",
          "\uC5C6\uC774",
          "\uC81C\uC678",
          // Arabic
          "\u0644\u0627 \u062A\u0641\u0639\u0644",
          "\u062A\u062C\u0646\u0628",
          "\u0623\u0628\u062F\u0627\u064B",
          "\u0628\u062F\u0648\u0646",
          "\u0628\u0627\u0633\u062A\u062B\u0646\u0627\u0621",
          "\u0627\u0633\u062A\u0628\u0639\u0627\u062F"
        ],
        domainSpecificKeywords: [
          // English
          "quantum",
          "fpga",
          "vlsi",
          "risc-v",
          "asic",
          "photonics",
          "genomics",
          "proteomics",
          "topological",
          "homomorphic",
          "zero-knowledge",
          "lattice-based",
          // Chinese
          "\u91CF\u5B50",
          "\u5149\u5B50\u5B66",
          "\u57FA\u56E0\u7EC4\u5B66",
          "\u86CB\u767D\u8D28\u7EC4\u5B66",
          "\u62D3\u6251",
          "\u540C\u6001",
          "\u96F6\u77E5\u8BC6",
          "\u683C\u5BC6\u7801",
          // Japanese
          "\u91CF\u5B50",
          "\u30D5\u30A9\u30C8\u30CB\u30AF\u30B9",
          "\u30B2\u30CE\u30DF\u30AF\u30B9",
          "\u30C8\u30DD\u30ED\u30B8\u30AB\u30EB",
          // Russian
          "\u043A\u0432\u0430\u043D\u0442\u043E\u0432\u044B\u0439",
          "\u0444\u043E\u0442\u043E\u043D\u0438\u043A\u0430",
          "\u0433\u0435\u043D\u043E\u043C\u0438\u043A\u0430",
          "\u043F\u0440\u043E\u0442\u0435\u043E\u043C\u0438\u043A\u0430",
          "\u0442\u043E\u043F\u043E\u043B\u043E\u0433\u0438\u0447\u0435\u0441\u043A\u0438\u0439",
          "\u0433\u043E\u043C\u043E\u043C\u043E\u0440\u0444\u043D\u044B\u0439",
          "\u0441 \u043D\u0443\u043B\u0435\u0432\u044B\u043C \u0440\u0430\u0437\u0433\u043B\u0430\u0448\u0435\u043D\u0438\u0435\u043C",
          "\u043D\u0430 \u043E\u0441\u043D\u043E\u0432\u0435 \u0440\u0435\u0448\u0451\u0442\u043E\u043A",
          // German
          "quanten",
          "photonik",
          "genomik",
          "proteomik",
          "topologisch",
          "homomorph",
          "zero-knowledge",
          "gitterbasiert",
          // Spanish
          "cu\xE1ntico",
          "fot\xF3nica",
          "gen\xF3mica",
          "prote\xF3mica",
          "topol\xF3gico",
          "homom\xF3rfico",
          // Portuguese
          "qu\xE2ntico",
          "fot\xF4nica",
          "gen\xF4mica",
          "prote\xF4mica",
          "topol\xF3gico",
          "homom\xF3rfico",
          // Korean
          "\uC591\uC790",
          "\uD3EC\uD1A0\uB2C9\uC2A4",
          "\uC720\uC804\uCCB4\uD559",
          "\uC704\uC0C1",
          "\uB3D9\uD615",
          // Arabic
          "\u0643\u0645\u064A",
          "\u0636\u0648\u0626\u064A\u0627\u062A",
          "\u062C\u064A\u0646\u0648\u0645\u064A\u0627\u062A",
          "\u0637\u0648\u0628\u0648\u0644\u0648\u062C\u064A",
          "\u062A\u0645\u0627\u062B\u0644\u064A"
        ],
        // Agentic task keywords - file ops, execution, multi-step, iterative work
        // Pruned: removed overly common words like "then", "first", "run", "test", "build"
        agenticTaskKeywords: [
          // English - File operations (clearly agentic)
          "read file",
          "read the file",
          "look at",
          "check the",
          "open the",
          "edit",
          "modify",
          "update the",
          "change the",
          "write to",
          "create file",
          // English - Execution (specific commands only)
          "execute",
          "deploy",
          "install",
          "npm",
          "pip",
          "compile",
          // English - Multi-step patterns (specific only)
          "after that",
          "and also",
          "once done",
          "step 1",
          "step 2",
          // English - Iterative work
          "fix",
          "debug",
          "until it works",
          "keep trying",
          "iterate",
          "make sure",
          "verify",
          "confirm",
          // Chinese (keep specific ones)
          "\u8BFB\u53D6\u6587\u4EF6",
          "\u67E5\u770B",
          "\u6253\u5F00",
          "\u7F16\u8F91",
          "\u4FEE\u6539",
          "\u66F4\u65B0",
          "\u521B\u5EFA",
          "\u6267\u884C",
          "\u90E8\u7F72",
          "\u5B89\u88C5",
          "\u7B2C\u4E00\u6B65",
          "\u7B2C\u4E8C\u6B65",
          "\u4FEE\u590D",
          "\u8C03\u8BD5",
          "\u76F4\u5230",
          "\u786E\u8BA4",
          "\u9A8C\u8BC1",
          // Spanish
          "leer archivo",
          "editar",
          "modificar",
          "actualizar",
          "ejecutar",
          "desplegar",
          "instalar",
          "paso 1",
          "paso 2",
          "arreglar",
          "depurar",
          "verificar",
          // Portuguese
          "ler arquivo",
          "editar",
          "modificar",
          "atualizar",
          "executar",
          "implantar",
          "instalar",
          "passo 1",
          "passo 2",
          "corrigir",
          "depurar",
          "verificar",
          // Korean
          "\uD30C\uC77C \uC77D\uAE30",
          "\uD3B8\uC9D1",
          "\uC218\uC815",
          "\uC5C5\uB370\uC774\uD2B8",
          "\uC2E4\uD589",
          "\uBC30\uD3EC",
          "\uC124\uCE58",
          "\uB2E8\uACC4 1",
          "\uB2E8\uACC4 2",
          "\uB514\uBC84\uADF8",
          "\uD655\uC778",
          // Arabic
          "\u0642\u0631\u0627\u0621\u0629 \u0645\u0644\u0641",
          "\u062A\u062D\u0631\u064A\u0631",
          "\u062A\u0639\u062F\u064A\u0644",
          "\u062A\u062D\u062F\u064A\u062B",
          "\u062A\u0646\u0641\u064A\u0630",
          "\u0646\u0634\u0631",
          "\u062A\u062B\u0628\u064A\u062A",
          "\u0627\u0644\u062E\u0637\u0648\u0629 1",
          "\u0627\u0644\u062E\u0637\u0648\u0629 2",
          "\u0625\u0635\u0644\u0627\u062D",
          "\u062A\u0635\u062D\u064A\u062D",
          "\u062A\u062D\u0642\u0642"
        ],
        // Dimension weights (sum to 1.0)
        dimensionWeights: {
          tokenCount: 0.08,
          codePresence: 0.15,
          reasoningMarkers: 0.18,
          technicalTerms: 0.1,
          creativeMarkers: 0.05,
          simpleIndicators: 0.02,
          // Reduced from 0.12 to make room for agenticTask
          multiStepPatterns: 0.12,
          questionComplexity: 0.05,
          imperativeVerbs: 0.03,
          constraintCount: 0.04,
          outputFormat: 0.03,
          referenceComplexity: 0.02,
          negationComplexity: 0.01,
          domainSpecificity: 0.02,
          agenticTask: 0.04
          // Reduced - agentic signals influence tier selection, not dominate it
        },
        // Tier boundaries on weighted score axis
        tierBoundaries: {
          simpleMedium: 0,
          mediumComplex: 0.3,
          // Raised from 0.18 - prevent simple tasks from reaching expensive COMPLEX tier
          complexReasoning: 0.5
          // Raised from 0.4 - reserve for true reasoning tasks
        },
        // Sigmoid steepness for confidence calibration
        confidenceSteepness: 12,
        // Below this confidence → ambiguous (null tier)
        confidenceThreshold: 0.7
      },
      // Auto (balanced) tier configs - current default smart routing
      // Benchmark-tuned 2026-03-16: balancing quality (retention) + latency
      tiers: {
        SIMPLE: {
          primary: "google/gemini-2.5-flash",
          // 1,238ms, IQ 20, 60% retention (best) — fast AND quality
          fallback: [
            "google/gemini-3-flash-preview",
            // 1,398ms, IQ 46 — smarter fallback
            "deepseek/deepseek-chat",
            // V4 Flash chat ($0.20/$0.40, 1M ctx) — repriced 2026-04-24
            "moonshot/kimi-k2.5",
            // 1,646ms, IQ 47, strong quality
            "google/gemini-3.1-flash-lite",
            // $0.25/$1.50, 1M context — newest flash-lite
            "google/gemini-2.5-flash-lite",
            // 1,353ms, $0.10/$0.40
            "openai/gpt-5.4-nano",
            // $0.20/$1.25, 1M context
            "xai/grok-4-fast-non-reasoning",
            // 1,143ms, $0.20/$0.50 — fast fallback
            "free/gpt-oss-120b"
            // 1,252ms, FREE fallback (hidden from /v1/models but direct calls work)
          ]
        },
        MEDIUM: {
          primary: "moonshot/kimi-k2.6",
          // $0.95/$4.00, 256K ctx, vision + reasoning — Moonshot flagship; promoted from K2.5 (2026-05-02) after BlockRun hid K2.5 from its UI on 2026-04-28
          fallback: [
            "moonshot/kimi-k2.5",
            // $0.60/$3.00 — graceful-degradation backstop while K2.6 stabilizes
            "google/gemini-3-flash-preview",
            // 1,398ms, IQ 46 — nearly same IQ, faster + cheaper
            "deepseek/deepseek-chat",
            // 1,431ms, IQ 32, 41% retention
            "google/gemini-2.5-flash",
            // 1,238ms, 60% retention
            "google/gemini-3.1-flash-lite",
            // $0.25/$1.50, 1M context
            "google/gemini-2.5-flash-lite",
            // 1,353ms, $0.10/$0.40
            "xai/grok-4-1-fast-non-reasoning",
            // 1,244ms, fast fallback
            "xai/grok-3-mini"
            // 1,202ms, $0.30/$0.50
          ]
        },
        COMPLEX: {
          primary: "google/gemini-3.1-pro",
          // 1,609ms, IQ 57 — fast flagship quality
          fallback: [
            "google/gemini-3-pro-preview",
            // 1,352ms, IQ 48 — quality-first fallback
            "google/gemini-3-flash-preview",
            // 1,398ms, IQ 46 — fast + smart
            "xai/grok-4-0709",
            // 1,348ms, IQ 41
            "google/gemini-2.5-pro",
            // 1,294ms
            "anthropic/claude-sonnet-4.6",
            // 2,110ms, IQ 52 — quality fallback
            "deepseek/deepseek-chat",
            // 1,431ms, IQ 32
            "google/gemini-2.5-flash",
            // 1,238ms, IQ 20 — cheap last resort
            "openai/gpt-5.5",
            // Newest OpenAI flagship — 1M+ ctx, native agent + computer use; benchmark TBD
            "openai/gpt-5.4"
            // 6,213ms, IQ 57 — previous flagship, benchmarked
          ]
        },
        REASONING: {
          primary: "xai/grok-4-1-fast-reasoning",
          // 1,454ms, $0.20/$0.50
          fallback: [
            "xai/grok-4-fast-reasoning",
            // 1,298ms, $0.20/$0.50
            "deepseek/deepseek-reasoner",
            // V4 Flash thinking ($0.20/$0.40, 1M ctx)
            "deepseek/deepseek-v4-pro",
            // V4 Pro flagship ($0.50/$1.00 promo through 2026-05-31, list $2/$4) — strongest open-weight reasoner
            "openai/o4-mini",
            // 2,328ms ($1.10/$4.40)
            "openai/o3"
            // 2,862ms
          ]
        }
      },
      // Eco tier configs - absolute cheapest (blockrun/eco)
      ecoTiers: {
        SIMPLE: {
          primary: "free/gpt-oss-120b",
          // FREE! $0.00/$0.00 — heavy user default
          fallback: [
            "free/gpt-oss-20b",
            // FREE — smaller, faster
            "free/mistral-small-4-119b",
            // FREE — 114 tok/s, fastest free chat
            "free/deepseek-v4-flash",
            // FREE — 1M context, ~5x faster than v4-pro
            "free/qwen3-next-80b-a3b-thinking",
            // FREE — 116 tok/s reasoning
            "google/gemini-3.1-flash-lite",
            // $0.25/$1.50 — newest flash-lite
            "openai/gpt-5.4-nano",
            // $0.20/$1.25 — fast nano
            "google/gemini-2.5-flash-lite",
            // $0.10/$0.40
            "xai/grok-4-fast-non-reasoning"
            // $0.20/$0.50
          ]
        },
        MEDIUM: {
          primary: "google/gemini-3.1-flash-lite",
          // $0.25/$1.50 — newest flash-lite
          fallback: [
            "openai/gpt-5.4-nano",
            // $0.20/$1.25
            "google/gemini-2.5-flash-lite",
            // $0.10/$0.40
            "xai/grok-4-fast-non-reasoning",
            "google/gemini-2.5-flash"
          ]
        },
        COMPLEX: {
          primary: "google/gemini-3.1-flash-lite",
          // $0.25/$1.50
          fallback: [
            "google/gemini-2.5-flash-lite",
            "xai/grok-4-0709",
            "google/gemini-2.5-flash",
            "deepseek/deepseek-chat"
          ]
        },
        REASONING: {
          primary: "xai/grok-4-1-fast-reasoning",
          // $0.20/$0.50
          fallback: [
            "xai/grok-4-fast-reasoning",
            "deepseek/deepseek-reasoner",
            // V4 Flash thinking — $0.20/$0.40
            "deepseek/deepseek-v4-pro"
            // V4 Pro flagship — $0.50/$1.00 promo, post-promo $2/$4
          ]
        }
      },
      // Premium tier configs - best quality (blockrun/premium)
      // codex=complex coding, kimi=simple coding, sonnet=reasoning/instructions, opus=architecture/PM/audits
      premiumTiers: {
        SIMPLE: {
          primary: "moonshot/kimi-k2.6",
          // $0.95/$4.00 - Moonshot flagship (256K ctx, vision + reasoning)
          fallback: [
            "moonshot/kimi-k2.5",
            // $0.60/$3.00 - proven reliable NVIDIA fallback when Moonshot direct API falters
            "google/gemini-2.5-flash",
            // 60% retention, fast growth
            "anthropic/claude-haiku-4.5",
            "google/gemini-2.5-flash-lite",
            "deepseek/deepseek-chat"
          ]
        },
        MEDIUM: {
          primary: "openai/gpt-5.3-codex",
          // $1.75/$14 - 400K context, 128K output, replaces 5.2
          fallback: [
            "moonshot/kimi-k2.6",
            // Moonshot flagship
            "moonshot/kimi-k2.5",
            "google/gemini-2.5-flash",
            // 60% retention, good coding capability
            "google/gemini-2.5-pro",
            "xai/grok-4-0709",
            "anthropic/claude-sonnet-4.6"
          ]
        },
        COMPLEX: {
          primary: "anthropic/claude-opus-4.7",
          // Best quality for complex tasks
          // Fallback chain de-Gemini'd 2026-04-22: when Anthropic 503s, Gemini is
          // also prone to "high demand" 503s (correlated failure — everyone falls
          // back to Google at the same time). Prefer xAI Grok → Moonshot → OpenAI
          // flagship → DeepSeek → NVIDIA free instead.
          fallback: [
            "anthropic/claude-opus-4.6",
            // in-family hot swap first
            "anthropic/claude-sonnet-4.6",
            "xai/grok-4-0709",
            // 503-resistant flagship
            "moonshot/kimi-k2.6",
            // Moonshot flagship, independent infra
            "moonshot/kimi-k2.5",
            "openai/gpt-5.5",
            // Newest OpenAI flagship — 1M+ ctx, native agent + computer use
            "openai/gpt-5.4",
            // Previous flagship (slow but stable, benchmarked at 6,213ms)
            "openai/gpt-5.3-codex",
            "deepseek/deepseek-chat",
            // Cheap, reliable
            "free/qwen3-coder-480b"
            // NVIDIA free ultimate backstop
          ]
        },
        REASONING: {
          primary: "anthropic/claude-sonnet-4.6",
          // 2,110ms, $3/$15 - best for reasoning/instructions
          fallback: [
            "anthropic/claude-opus-4.7",
            // Flagship Opus w/ adaptive thinking
            "anthropic/claude-opus-4.6",
            // 2,139ms
            "xai/grok-4-1-fast-reasoning",
            // 1,454ms, cheap fast reasoning
            "openai/o4-mini",
            // 2,328ms ($1.10/$4.40)
            "openai/o3"
            // 2,862ms
          ]
        }
      },
      // Agentic tier configs - models that excel at multi-step autonomous tasks
      agenticTiers: {
        SIMPLE: {
          primary: "openai/gpt-4o-mini",
          // $0.15/$0.60 - best tool compliance at lowest cost
          fallback: [
            "moonshot/kimi-k2.5",
            // 1,646ms, strong tool use quality
            "anthropic/claude-haiku-4.5",
            // 2,305ms
            "xai/grok-4-1-fast-non-reasoning"
            // 1,244ms, fast fallback
          ]
        },
        MEDIUM: {
          primary: "moonshot/kimi-k2.6",
          // $0.95/$4.00 — Moonshot flagship, strong tool use; promoted from K2.5 (2026-05-02) after BlockRun hid K2.5 from its UI on 2026-04-28
          fallback: [
            "moonshot/kimi-k2.5",
            // $0.60/$3.00 — graceful-degradation backstop while K2.6 stabilizes
            "xai/grok-4-1-fast-non-reasoning",
            // 1,244ms, fast fallback
            "openai/gpt-4o-mini",
            // 2,764ms, reliable tool calling
            "anthropic/claude-haiku-4.5",
            // 2,305ms
            "deepseek/deepseek-chat"
            // 1,431ms
          ]
        },
        COMPLEX: {
          primary: "anthropic/claude-sonnet-4.6",
          // 2,110ms — best agentic quality
          // Fallback chain de-Gemini'd 2026-04-22: Gemini's "high demand" 503s
          // correlate with Anthropic outages (everyone falls back together).
          // Prefer 503-resistant providers first.
          fallback: [
            "anthropic/claude-opus-4.7",
            // Flagship Opus — in-family hot swap
            "anthropic/claude-opus-4.6",
            // 2,139ms
            "xai/grok-4-0709",
            // 1,348ms — strong tool use, independent infra
            "moonshot/kimi-k2.5",
            // strong tool use, independent infra
            "openai/gpt-5.5",
            // Newest flagship — native agent + computer use (exactly the agentic-tier use case)
            "openai/gpt-5.4",
            // Previous flagship — 6,213ms, reliable
            "deepseek/deepseek-chat",
            // 1,431ms — cheap, reliable
            "free/qwen3-coder-480b"
            // NVIDIA free ultimate backstop
          ]
        },
        REASONING: {
          primary: "anthropic/claude-sonnet-4.6",
          // 2,110ms — strong tool use + reasoning
          fallback: [
            "anthropic/claude-opus-4.7",
            // Flagship Opus w/ adaptive thinking
            "anthropic/claude-opus-4.6",
            // 2,139ms
            "xai/grok-4-1-fast-reasoning",
            // 1,454ms
            "deepseek/deepseek-reasoner"
            // 1,454ms
          ]
        }
      },
      // Time-windowed promotions — auto-applied when active, ignored when expired
      promotions: [
        {
          name: "GLM-5.1 Launch Promo ($0.001 flat)",
          startDate: "2026-04-01",
          endDate: "2026-05-01",
          tierOverrides: {
            SIMPLE: { primary: "zai/glm-5.1" }
          },
          profiles: ["auto"]
          // only auto profile — eco stays free, premium stays premium
        }
      ],
      overrides: {
        maxTokensForceComplex: 1e5,
        structuredOutputMinTier: "MEDIUM",
        ambiguousDefaultTier: "MEDIUM"
        // agenticMode left undefined → auto-detect via tools/agenticScore.
        // Set to `true` to force agentic tiers; `false` to disable them entirely.
      }
    };
  }
});

// src/router/index.ts
function route(prompt, systemPrompt, maxOutputTokens, options) {
  const strategy = getStrategy("rules");
  return strategy.route(prompt, systemPrompt, maxOutputTokens, options);
}
var init_router = __esm({
  "src/router/index.ts"() {
    "use strict";
    init_strategy();
    init_strategy();
    init_selector();
    init_config();
  }
});

// src/top-models.json
var top_models_default;
var init_top_models = __esm({
  "src/top-models.json"() {
    top_models_default = [
      "auto",
      "free",
      "eco",
      "premium",
      "anthropic/claude-sonnet-4.6",
      "anthropic/claude-opus-4.7",
      "anthropic/claude-opus-4.6",
      "anthropic/claude-haiku-4.5",
      "openai/gpt-5.5",
      "openai/gpt-5.4",
      "openai/gpt-5.4-mini",
      "openai/gpt-5.4-pro",
      "openai/gpt-5.3-codex",
      "openai/gpt-5.4-nano",
      "google/gemini-3.1-pro",
      "google/gemini-3.1-flash-lite",
      "google/gemini-3-pro-preview",
      "google/gemini-3-flash-preview",
      "deepseek/deepseek-v4-pro",
      "deepseek/deepseek-chat",
      "deepseek/deepseek-reasoner",
      "moonshot/kimi-k2.6",
      "xai/grok-3",
      "xai/grok-4-0709",
      "xai/grok-4-1-fast-reasoning",
      "minimax/minimax-m2.7",
      "free/gpt-oss-120b",
      "free/gpt-oss-20b",
      "free/mistral-small-4-119b",
      "free/deepseek-v4-flash",
      "free/qwen3-next-80b-a3b-thinking",
      "free/qwen3-coder-480b",
      "free/glm-4.7",
      "free/llama-4-maverick",
      "free/nemotron-3-nano-omni-30b-a3b-reasoning",
      "zai/glm-5.1",
      "zai/glm-5",
      "zai/glm-5-turbo"
    ];
  }
});

// src/top-models.ts
function loadTopModels() {
  const parsed = top_models_default;
  if (!Array.isArray(parsed) || parsed.some((value) => typeof value !== "string" || !value.trim())) {
    throw new Error("top-models.json must be a JSON array of non-empty strings");
  }
  return [...parsed];
}
var TOP_MODELS;
var init_top_models2 = __esm({
  "src/top-models.ts"() {
    "use strict";
    init_top_models();
    TOP_MODELS = Object.freeze(loadTopModels());
  }
});

// src/models.ts
function resolveModelAlias(model) {
  const normalized = model.trim().toLowerCase();
  const resolved = MODEL_ALIASES[normalized];
  if (resolved) return resolved;
  if (normalized.startsWith("blockrun/")) {
    const withoutPrefix = normalized.slice("blockrun/".length);
    const resolvedWithoutPrefix = MODEL_ALIASES[withoutPrefix];
    if (resolvedWithoutPrefix) return resolvedWithoutPrefix;
    return withoutPrefix;
  }
  if (normalized.startsWith("openai/")) {
    const withoutPrefix = normalized.slice("openai/".length);
    const resolvedWithoutPrefix = MODEL_ALIASES[withoutPrefix];
    if (resolvedWithoutPrefix) return resolvedWithoutPrefix;
    const isVirtualProfile = BLOCKRUN_MODELS.some((m) => m.id === withoutPrefix);
    if (isVirtualProfile) return withoutPrefix;
  }
  if (normalized.startsWith("openai-codex/")) {
    const withoutPrefix = normalized.slice("openai-codex/".length);
    const resolvedWithoutPrefix = MODEL_ALIASES[withoutPrefix];
    if (resolvedWithoutPrefix) return resolvedWithoutPrefix;
    const isKnownModel = BLOCKRUN_MODELS.some((m) => m.id === withoutPrefix);
    if (isKnownModel) return withoutPrefix;
  }
  return model;
}
function getActivePromoPrice(model, now = /* @__PURE__ */ new Date()) {
  if (!model.promo) return void 0;
  const start = new Date(model.promo.startDate);
  const end = new Date(model.promo.endDate);
  if (now >= start && now < end) return model.promo.flatPrice;
  return void 0;
}
function toOpenClawModel(m) {
  return {
    id: m.id,
    name: m.name,
    api: "openai-completions",
    reasoning: m.reasoning ?? false,
    input: m.vision ? ["text", "image"] : ["text"],
    cost: {
      input: m.inputPrice,
      output: m.outputPrice,
      cacheRead: 0,
      cacheWrite: 0
    },
    contextWindow: m.contextWindow,
    maxTokens: m.maxOutput
  };
}
function buildProviderModels(baseUrl) {
  return {
    baseUrl: `${baseUrl}/v1`,
    api: "openai-completions",
    models: VISIBLE_OPENCLAW_MODELS
  };
}
function isAgenticModel(modelId) {
  const model = BLOCKRUN_MODELS.find(
    (m) => m.id === modelId || m.id === modelId.replace("blockrun/", "")
  );
  return model?.agentic ?? false;
}
function getAgenticModels() {
  return BLOCKRUN_MODELS.filter((m) => m.agentic).map((m) => m.id);
}
function supportsToolCalling(modelId) {
  const normalized = modelId.replace("blockrun/", "");
  const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);
  return model?.toolCalling ?? false;
}
function supportsVision(modelId) {
  const normalized = modelId.replace("blockrun/", "");
  const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);
  return model?.vision ?? false;
}
function getModelContextWindow(modelId) {
  const normalized = modelId.replace("blockrun/", "");
  const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);
  return model?.contextWindow;
}
function isReasoningModel(modelId) {
  const normalized = modelId.replace("blockrun/", "");
  const model = BLOCKRUN_MODELS.find((m) => m.id === normalized);
  return model?.reasoning ?? false;
}
var MODEL_ALIASES, BLOCKRUN_MODELS, ALIAS_MODELS, OPENCLAW_MODELS, TOP_MODELS_SET, VISIBLE_OPENCLAW_MODELS;
var init_models = __esm({
  "src/models.ts"() {
    "use strict";
    init_top_models2();
    MODEL_ALIASES = {
      // Claude - flagship opus is 4.7; sonnet stays at 4.6
      claude: "anthropic/claude-sonnet-4.6",
      "br-sonnet": "anthropic/claude-sonnet-4.6",
      sonnet: "anthropic/claude-sonnet-4.6",
      "sonnet-4": "anthropic/claude-sonnet-4.6",
      "sonnet-4.6": "anthropic/claude-sonnet-4.6",
      "sonnet-4-6": "anthropic/claude-sonnet-4.6",
      opus: "anthropic/claude-opus-4.7",
      "opus-4": "anthropic/claude-opus-4.7",
      "opus-4.7": "anthropic/claude-opus-4.7",
      "opus-4-7": "anthropic/claude-opus-4.7",
      "opus-4.6": "anthropic/claude-opus-4.6",
      "opus-4-6": "anthropic/claude-opus-4.6",
      haiku: "anthropic/claude-haiku-4.5",
      // Claude - provider/shortname patterns (common in agent frameworks)
      "anthropic/sonnet": "anthropic/claude-sonnet-4.6",
      "anthropic/opus": "anthropic/claude-opus-4.7",
      "anthropic/haiku": "anthropic/claude-haiku-4.5",
      "anthropic/claude": "anthropic/claude-sonnet-4.6",
      // Backward compatibility - generic opus-4 and older flagships point at 4.7;
      // explicit version pins (claude-opus-4-6) stay on 4.6 since server still routes it.
      "anthropic/claude-sonnet-4": "anthropic/claude-sonnet-4.6",
      "anthropic/claude-sonnet-4-6": "anthropic/claude-sonnet-4.6",
      "anthropic/claude-opus-4": "anthropic/claude-opus-4.7",
      "anthropic/claude-opus-4-7": "anthropic/claude-opus-4.7",
      "anthropic/claude-opus-4-6": "anthropic/claude-opus-4.6",
      "anthropic/claude-opus-4-5": "anthropic/claude-opus-4.5",
      "anthropic/claude-haiku-4": "anthropic/claude-haiku-4.5",
      "anthropic/claude-haiku-4-5": "anthropic/claude-haiku-4.5",
      // OpenAI
      gpt: "openai/gpt-4o",
      gpt4: "openai/gpt-4o",
      gpt5: "openai/gpt-5.5",
      "gpt-5.5": "openai/gpt-5.5",
      "gpt-5.4": "openai/gpt-5.4",
      "gpt-5.4-pro": "openai/gpt-5.4-pro",
      "gpt-5.4-nano": "openai/gpt-5.4-nano",
      nano: "openai/gpt-5.4-nano",
      "gpt-5-nano": "openai/gpt-5.4-nano",
      codex: "openai/gpt-5.3-codex",
      mini: "openai/gpt-4o-mini",
      o1: "openai/o1",
      o3: "openai/o3",
      // OpenAI Codex prefix aliases (OpenClaw v2026.4.5 openai-codex/ model ID format)
      "openai-codex/gpt-5.4-mini": "openai/gpt-5.4-mini",
      "gpt-5.4-mini": "openai/gpt-5.4-mini",
      // DeepSeek
      deepseek: "deepseek/deepseek-chat",
      "deepseek-chat": "deepseek/deepseek-chat",
      reasoner: "deepseek/deepseek-reasoner",
      // Kimi / Moonshot — K2.6 is the featured flagship on BlockRun (K2.5 hidden in
      // BlockRun's UI 2026-04-28). Bare aliases now resolve to K2.6. Users who
      // explicitly pinned "kimi-k2.5" continue to get K2.5 (cost-stability opt-in:
      // $0.60/$3.00 vs K2.6's $0.95/$4.00). NVIDIA-hosted K2.5 was retired 2026-04-21.
      kimi: "moonshot/kimi-k2.6",
      moonshot: "moonshot/kimi-k2.6",
      "kimi-k2": "moonshot/kimi-k2.6",
      "kimi-k2.6": "moonshot/kimi-k2.6",
      "kimi-k2.5": "moonshot/kimi-k2.5",
      "nvidia/kimi-k2.5": "moonshot/kimi-k2.5",
      // Google
      gemini: "google/gemini-2.5-pro",
      flash: "google/gemini-2.5-flash",
      "gemini-3.1-pro-preview": "google/gemini-3.1-pro",
      "google/gemini-3.1-pro-preview": "google/gemini-3.1-pro",
      "gemini-3.1-flash-lite": "google/gemini-3.1-flash-lite",
      "gemini-2.5-flash-lite": "google/gemini-2.5-flash-lite",
      // xAI
      grok: "xai/grok-3",
      "grok-fast": "xai/grok-4-fast-reasoning",
      "grok-code": "deepseek/deepseek-chat",
      // was grok-code-fast-1, delisted due to poor retention
      // Delisted model redirects — full model IDs that were previously valid but removed
      "grok-code-fast-1": "deepseek/deepseek-chat",
      // bare alias
      "xai/grok-code-fast-1": "deepseek/deepseek-chat",
      // delisted 2026-03-12
      "xai/grok-3-fast": "xai/grok-4-fast-reasoning",
      // delisted (too expensive)
      // NVIDIA — backward compat aliases (nvidia/xxx → free/xxx)
      // Default free model is gpt-oss-120b (heavy user demand). New free models
      // added 2026-04-29 — deepseek-v4-pro/flash, nemotron-omni — are additions,
      // not replacements. Retired-with-redirect entries below mirror BlockRun
      // server-side decommissioning of slow models (nemotron family, etc.).
      nvidia: "free/gpt-oss-120b",
      "gpt-120b": "free/gpt-oss-120b",
      "gpt-20b": "free/gpt-oss-20b",
      "nvidia/gpt-oss-120b": "free/gpt-oss-120b",
      "nvidia/gpt-oss-20b": "free/gpt-oss-20b",
      "nvidia/deepseek-v3.2": "free/deepseek-v4-flash",
      // v3.2 → v4-flash (v4-pro NVIDIA hung 2026-04-30)
      "free/deepseek-v3.2": "free/deepseek-v4-flash",
      // local pin redirect
      "nvidia/deepseek-v4-pro": "free/deepseek-v4-flash",
      // V4 Pro NVIDIA hung 2026-04-30
      "free/deepseek-v4-pro": "free/deepseek-v4-flash",
      // V4 Pro delisted — redirect pinned callers
      "nvidia/deepseek-v4-flash": "free/deepseek-v4-flash",
      "nvidia/nemotron-3-nano-omni-30b-a3b-reasoning": "free/nemotron-3-nano-omni-30b-a3b-reasoning",
      "nvidia/qwen3-coder-480b": "free/qwen3-coder-480b",
      "qwen/qwen3-coder-480b-a35b-instruct": "free/qwen3-coder-480b",
      "nvidia/glm-4.7": "free/glm-4.7",
      "nvidia/llama-4-maverick": "free/llama-4-maverick",
      "nvidia/qwen3-next-80b-a3b-thinking": "free/qwen3-next-80b-a3b-thinking",
      "nvidia/mistral-small-4-119b": "free/mistral-small-4-119b",
      // Retired free IDs → successors (mirror server-side redirects)
      "nvidia/nemotron-ultra-253b": "free/qwen3-next-80b-a3b-thinking",
      "nvidia/nemotron-3-super-120b": "free/qwen3-next-80b-a3b-thinking",
      "nvidia/nemotron-super-49b": "free/qwen3-next-80b-a3b-thinking",
      "nvidia/mistral-large-3-675b": "free/mistral-small-4-119b",
      "nvidia/devstral-2-123b": "free/qwen3-coder-480b",
      "free/nemotron-ultra-253b": "free/qwen3-next-80b-a3b-thinking",
      "free/nemotron-3-super-120b": "free/qwen3-next-80b-a3b-thinking",
      "free/nemotron-super-49b": "free/qwen3-next-80b-a3b-thinking",
      "free/mistral-large-3-675b": "free/mistral-small-4-119b",
      "free/devstral-2-123b": "free/qwen3-coder-480b",
      // Free model shorthand aliases
      "deepseek-free": "free/deepseek-v4-flash",
      // V4 Pro NVIDIA hung 2026-04-30 → flash
      "deepseek-v4-pro": "free/deepseek-v4-flash",
      // free shorthand → flash (pro hung)
      "deepseek-v4-flash": "free/deepseek-v4-flash",
      "v4-pro": "free/deepseek-v4-flash",
      // V4 Pro NVIDIA hung → flash
      "v4-flash": "free/deepseek-v4-flash",
      "mistral-free": "free/mistral-small-4-119b",
      "glm-free": "free/glm-4.7",
      "llama-free": "free/llama-4-maverick",
      "qwen-coder": "free/qwen3-coder-480b",
      "qwen-coder-free": "free/qwen3-coder-480b",
      "qwen-thinking": "free/qwen3-next-80b-a3b-thinking",
      "qwen3-next": "free/qwen3-next-80b-a3b-thinking",
      "mistral-small": "free/mistral-small-4-119b",
      // Vision-capable free model — BlockRun's first
      "nemotron-omni": "free/nemotron-3-nano-omni-30b-a3b-reasoning",
      "nano-omni": "free/nemotron-3-nano-omni-30b-a3b-reasoning",
      "vision-free": "free/nemotron-3-nano-omni-30b-a3b-reasoning",
      // Retired shorthand aliases redirect to successors
      nemotron: "free/qwen3-next-80b-a3b-thinking",
      "nemotron-ultra": "free/qwen3-next-80b-a3b-thinking",
      "nemotron-253b": "free/qwen3-next-80b-a3b-thinking",
      "nemotron-super": "free/qwen3-next-80b-a3b-thinking",
      "nemotron-49b": "free/qwen3-next-80b-a3b-thinking",
      "nemotron-120b": "free/qwen3-next-80b-a3b-thinking",
      devstral: "free/qwen3-coder-480b",
      "devstral-2": "free/qwen3-coder-480b",
      maverick: "free/llama-4-maverick",
      free: "free/gpt-oss-120b",
      // MiniMax
      minimax: "minimax/minimax-m2.7",
      "minimax-m2.7": "minimax/minimax-m2.7",
      "minimax-m2.5": "minimax/minimax-m2.5",
      // Z.AI GLM-5
      glm: "zai/glm-5.1",
      "glm-5": "zai/glm-5",
      "glm-5.1": "zai/glm-5.1",
      "glm-5-turbo": "zai/glm-5-turbo",
      // Routing profile aliases (common variations)
      "auto-router": "auto",
      router: "auto",
      // Note: auto, eco, premium are virtual routing profiles registered in BLOCKRUN_MODELS
      // They don't need aliases since they're already top-level model IDs
      // Image generation
      dalle: "openai/dall-e-3",
      "dall-e": "openai/dall-e-3",
      "gpt-image": "openai/gpt-image-1",
      "nano-banana": "google/nano-banana",
      banana: "google/nano-banana",
      "banana-pro": "google/nano-banana-pro",
      "nano-banana-pro": "google/nano-banana-pro",
      flux: "black-forest/flux-1.1-pro",
      "flux-pro": "black-forest/flux-1.1-pro",
      "grok-imagine": "xai/grok-imagine-image",
      "grok-imagine-pro": "xai/grok-imagine-image-pro",
      cogview: "zai/cogview-4",
      // Video generation
      "grok-video": "xai/grok-imagine-video",
      seedance: "bytedance/seedance-1.5-pro",
      "seedance-1.5": "bytedance/seedance-1.5-pro",
      "seedance-2-fast": "bytedance/seedance-2.0-fast",
      "seedance-2": "bytedance/seedance-2.0"
    };
    BLOCKRUN_MODELS = [
      // Smart routing meta-models — proxy replaces with actual model
      // NOTE: Model IDs are WITHOUT provider prefix (OpenClaw adds "blockrun/" automatically)
      {
        id: "auto",
        name: "Auto (Smart Router - Balanced)",
        inputPrice: 0,
        outputPrice: 0,
        contextWindow: 105e4,
        maxOutput: 128e3
      },
      {
        id: "free",
        name: "Free \u2192 Nemotron Ultra 253B",
        inputPrice: 0,
        outputPrice: 0,
        contextWindow: 131072,
        maxOutput: 16384,
        reasoning: true
      },
      {
        id: "eco",
        name: "Eco (Smart Router - Cost Optimized)",
        inputPrice: 0,
        outputPrice: 0,
        contextWindow: 105e4,
        maxOutput: 128e3
      },
      {
        id: "premium",
        name: "Premium (Smart Router - Best Quality)",
        inputPrice: 0,
        outputPrice: 0,
        contextWindow: 2e6,
        maxOutput: 2e5
      },
      // OpenAI GPT-5 Family
      {
        id: "openai/gpt-5.2",
        name: "GPT-5.2",
        version: "5.2",
        inputPrice: 1.75,
        outputPrice: 14,
        contextWindow: 4e5,
        maxOutput: 128e3,
        reasoning: true,
        vision: true,
        agentic: true,
        toolCalling: true
      },
      {
        id: "openai/gpt-5-mini",
        name: "GPT-5 Mini",
        version: "5.0",
        inputPrice: 0.25,
        outputPrice: 2,
        contextWindow: 2e5,
        maxOutput: 65536,
        toolCalling: true
      },
      {
        id: "openai/gpt-5-nano",
        name: "GPT-5 Nano",
        version: "5.0",
        inputPrice: 0.05,
        outputPrice: 0.4,
        contextWindow: 128e3,
        maxOutput: 32768,
        toolCalling: true,
        deprecated: true,
        fallbackModel: "openai/gpt-5.4-nano"
      },
      {
        id: "openai/gpt-5.2-pro",
        name: "GPT-5.2 Pro",
        version: "5.2",
        inputPrice: 21,
        outputPrice: 168,
        contextWindow: 4e5,
        maxOutput: 128e3,
        reasoning: true,
        toolCalling: true
      },
      // GPT-5.5 — newest visible flagship in blockrun. First fully retrained base since
      // GPT-4.5; 1M+ context, native agent + computer use. Costs 2x gpt-5.4 — routing
      // tiers still default to gpt-5.4 because it's benchmarked; users can pin 5.5.
      {
        id: "openai/gpt-5.5",
        name: "GPT-5.5",
        version: "5.5",
        inputPrice: 5,
        outputPrice: 30,
        contextWindow: 105e4,
        maxOutput: 128e3,
        reasoning: true,
        vision: true,
        agentic: true,
        toolCalling: true
      },
      // GPT-5.4 — flagship benchmarked into routing tiers
      {
        id: "openai/gpt-5.4",
        name: "GPT-5.4",
        version: "5.4",
        inputPrice: 2.5,
        outputPrice: 15,
        contextWindow: 4e5,
        maxOutput: 128e3,
        reasoning: true,
        vision: true,
        agentic: true,
        toolCalling: true
      },
      {
        id: "openai/gpt-5.4-mini",
        name: "GPT-5.4 Mini",
        version: "5.4",
        inputPrice: 0.75,
        outputPrice: 4.5,
        contextWindow: 4e5,
        maxOutput: 128e3,
        vision: true,
        agentic: true,
        toolCalling: true
      },
      {
        id: "openai/gpt-5.4-pro",
        name: "GPT-5.4 Pro",
        version: "5.4",
        inputPrice: 30,
        outputPrice: 180,
        contextWindow: 4e5,
        maxOutput: 128e3,
        reasoning: true,
        toolCalling: true
      },
      {
        id: "openai/gpt-5.4-nano",
        name: "GPT-5.4 Nano",
        version: "5.4",
        inputPrice: 0.2,
        outputPrice: 1.25,
        contextWindow: 105e4,
        maxOutput: 32768,
        toolCalling: true
      },
      // OpenAI GPT-5.3 Family
      {
        id: "openai/gpt-5.3",
        name: "GPT-5.3",
        version: "5.3",
        inputPrice: 1.75,
        outputPrice: 14,
        contextWindow: 128e3,
        maxOutput: 16e3,
        reasoning: true,
        vision: true,
        agentic: true,
        toolCalling: true
      },
      // OpenAI Codex Family
      {
        id: "openai/gpt-5.3-codex",
        name: "GPT-5.3 Codex",
        version: "5.3",
        inputPrice: 1.75,
        outputPrice: 14,
        contextWindow: 4e5,
        maxOutput: 128e3,
        agentic: true,
        toolCalling: true
      },
      // OpenAI GPT-4 Family
      {
        id: "openai/gpt-4.1",
        name: "GPT-4.1",
        version: "4.1",
        inputPrice: 2,
        outputPrice: 8,
        contextWindow: 128e3,
        maxOutput: 16384,
        vision: true,
        toolCalling: true
      },
      {
        id: "openai/gpt-4.1-mini",
        name: "GPT-4.1 Mini",
        version: "4.1",
        inputPrice: 0.4,
        outputPrice: 1.6,
        contextWindow: 128e3,
        maxOutput: 16384,
        toolCalling: true
      },
      {
        id: "openai/gpt-4.1-nano",
        name: "GPT-4.1 Nano",
        version: "4.1",
        inputPrice: 0.1,
        outputPrice: 0.4,
        contextWindow: 128e3,
        maxOutput: 16384,
        toolCalling: true
      },
      {
        id: "openai/gpt-4o",
        name: "GPT-4o",
        version: "4o",
        inputPrice: 2.5,
        outputPrice: 10,
        contextWindow: 128e3,
        maxOutput: 16384,
        vision: true,
        agentic: true,
        toolCalling: true
      },
      {
        id: "openai/gpt-4o-mini",
        name: "GPT-4o Mini",
        version: "4o-mini",
        inputPrice: 0.15,
        outputPrice: 0.6,
        contextWindow: 128e3,
        maxOutput: 16384,
        toolCalling: true
      },
      // OpenAI O-series (Reasoning)
      {
        id: "openai/o1",
        name: "o1",
        version: "1",
        inputPrice: 15,
        outputPrice: 60,
        contextWindow: 2e5,
        maxOutput: 1e5,
        reasoning: true,
        toolCalling: true
      },
      {
        id: "openai/o1-mini",
        name: "o1-mini",
        version: "1-mini",
        inputPrice: 1.1,
        outputPrice: 4.4,
        contextWindow: 128e3,
        maxOutput: 65536,
        reasoning: true,
        toolCalling: true
      },
      {
        id: "openai/o3",
        name: "o3",
        version: "3",
        inputPrice: 2,
        outputPrice: 8,
        contextWindow: 2e5,
        maxOutput: 1e5,
        reasoning: true,
        toolCalling: true
      },
      {
        id: "openai/o3-mini",
        name: "o3-mini",
        version: "3-mini",
        inputPrice: 1.1,
        outputPrice: 4.4,
        contextWindow: 128e3,
        maxOutput: 65536,
        reasoning: true,
        toolCalling: true
      },
      {
        id: "openai/o4-mini",
        name: "o4-mini",
        version: "4-mini",
        inputPrice: 1.1,
        outputPrice: 4.4,
        contextWindow: 128e3,
        maxOutput: 65536,
        reasoning: true,
        toolCalling: true
      },
      // Anthropic - all Claude models excel at agentic workflows
      // Use newest versions (4.6) with full provider prefix
      {
        id: "anthropic/claude-haiku-4.5",
        name: "Claude Haiku 4.5",
        version: "4.5",
        inputPrice: 1,
        outputPrice: 5,
        contextWindow: 2e5,
        maxOutput: 8192,
        vision: true,
        agentic: true,
        toolCalling: true
      },
      {
        id: "anthropic/claude-sonnet-4.6",
        name: "Claude Sonnet 4.6",
        version: "4.6",
        inputPrice: 3,
        outputPrice: 15,
        contextWindow: 2e5,
        maxOutput: 64e3,
        reasoning: true,
        vision: true,
        agentic: true,
        toolCalling: true
      },
      {
        id: "anthropic/claude-opus-4.5",
        name: "Claude Opus 4.5",
        version: "4.5",
        inputPrice: 5,
        outputPrice: 25,
        contextWindow: 2e5,
        maxOutput: 32e3,
        reasoning: true,
        vision: true,
        agentic: true,
        toolCalling: true
      },
      {
        id: "anthropic/claude-opus-4.6",
        name: "Claude Opus 4.6",
        version: "4.6",
        inputPrice: 5,
        outputPrice: 25,
        contextWindow: 1e6,
        maxOutput: 128e3,
        reasoning: true,
        vision: true,
        agentic: true,
        toolCalling: true
      },
      {
        id: "anthropic/claude-opus-4.7",
        name: "Claude Opus 4.7",
        version: "4.7",
        inputPrice: 5,
        outputPrice: 25,
        contextWindow: 1e6,
        maxOutput: 128e3,
        reasoning: true,
        vision: true,
        agentic: true,
        toolCalling: true
      },
      // Google
      {
        id: "google/gemini-3.1-pro",
        name: "Gemini 3.1 Pro",
        version: "3.1",
        inputPrice: 2,
        outputPrice: 12,
        contextWindow: 105e4,
        maxOutput: 65536,
        reasoning: true,
        vision: true,
        toolCalling: true
      },
      {
        id: "google/gemini-3-pro-preview",
        name: "Gemini 3 Pro Preview",
        version: "3.0",
        inputPrice: 2,
        outputPrice: 12,
        contextWindow: 105e4,
        maxOutput: 65536,
        reasoning: true,
        vision: true,
        toolCalling: true
      },
      {
        id: "google/gemini-3-flash-preview",
        name: "Gemini 3 Flash Preview",
        version: "3.0",
        inputPrice: 0.5,
        outputPrice: 3,
        contextWindow: 1e6,
        maxOutput: 65536,
        vision: true
      },
      {
        id: "google/gemini-2.5-pro",
        name: "Gemini 2.5 Pro",
        version: "2.5",
        inputPrice: 1.25,
        outputPrice: 10,
        contextWindow: 105e4,
        maxOutput: 65536,
        reasoning: true,
        vision: true,
        toolCalling: true
      },
      {
        id: "google/gemini-2.5-flash",
        name: "Gemini 2.5 Flash",
        version: "2.5",
        inputPrice: 0.3,
        outputPrice: 2.5,
        contextWindow: 1e6,
        maxOutput: 65536,
        vision: true,
        toolCalling: true
      },
      {
        id: "google/gemini-2.5-flash-lite",
        name: "Gemini 2.5 Flash Lite",
        version: "2.5",
        inputPrice: 0.1,
        outputPrice: 0.4,
        contextWindow: 1e6,
        maxOutput: 65536,
        toolCalling: true
      },
      {
        id: "google/gemini-3.1-flash-lite",
        name: "Gemini 3.1 Flash Lite",
        version: "3.1",
        inputPrice: 0.25,
        outputPrice: 1.5,
        contextWindow: 1e6,
        maxOutput: 8192,
        toolCalling: true
      },
      // DeepSeek
      {
        id: "deepseek/deepseek-chat",
        name: "DeepSeek V3.2 Chat",
        version: "3.2",
        inputPrice: 0.28,
        outputPrice: 0.42,
        contextWindow: 128e3,
        maxOutput: 8192,
        toolCalling: true
      },
      {
        id: "deepseek/deepseek-reasoner",
        name: "DeepSeek V3.2 Reasoner",
        version: "3.2",
        inputPrice: 0.28,
        outputPrice: 0.42,
        contextWindow: 128e3,
        maxOutput: 8192,
        reasoning: true,
        toolCalling: true
      },
      // Kimi K2.6 — Moonshot's current flagship (256K context, vision + reasoning). Only served via Moonshot direct API.
      {
        id: "moonshot/kimi-k2.6",
        name: "Kimi K2.6",
        version: "k2.6",
        inputPrice: 0.95,
        outputPrice: 4,
        contextWindow: 262144,
        maxOutput: 65536,
        reasoning: true,
        vision: true,
        agentic: true,
        toolCalling: true
      },
      // Kimi K2.5 — Moonshot direct is primary (better SLA). NVIDIA-hosted variant
      // retired 2026-04-21 (slow throughput) and now redirects to moonshot.
      {
        id: "moonshot/kimi-k2.5",
        name: "Kimi K2.5",
        version: "k2.5",
        inputPrice: 0.6,
        outputPrice: 3,
        contextWindow: 262144,
        maxOutput: 16384,
        reasoning: true,
        vision: true,
        agentic: true,
        toolCalling: true
      },
      {
        id: "nvidia/kimi-k2.5",
        name: "Kimi K2.5 (NVIDIA, retired)",
        version: "k2.5",
        inputPrice: 0.6,
        outputPrice: 3,
        contextWindow: 262144,
        maxOutput: 8192,
        reasoning: true,
        vision: true,
        agentic: true,
        toolCalling: true,
        deprecated: true,
        fallbackModel: "moonshot/kimi-k2.5"
      },
      // xAI / Grok
      {
        id: "xai/grok-3",
        name: "Grok 3",
        version: "3",
        inputPrice: 3,
        outputPrice: 15,
        contextWindow: 131072,
        maxOutput: 16384,
        reasoning: true,
        toolCalling: true
      },
      // grok-3-fast removed - too expensive ($5/$25), use grok-4-fast instead
      {
        id: "xai/grok-3-mini",
        name: "Grok 3 Mini",
        version: "3-mini",
        inputPrice: 0.3,
        outputPrice: 0.5,
        contextWindow: 131072,
        maxOutput: 16384,
        toolCalling: true
      },
      // xAI Grok 4 Family - Ultra-cheap fast models
      {
        id: "xai/grok-4-fast-reasoning",
        name: "Grok 4 Fast Reasoning",
        version: "4",
        inputPrice: 0.2,
        outputPrice: 0.5,
        contextWindow: 131072,
        maxOutput: 16384,
        reasoning: true,
        toolCalling: true
      },
      {
        id: "xai/grok-4-fast-non-reasoning",
        name: "Grok 4 Fast",
        version: "4",
        inputPrice: 0.2,
        outputPrice: 0.5,
        contextWindow: 131072,
        maxOutput: 16384,
        toolCalling: true
      },
      {
        id: "xai/grok-4-1-fast-reasoning",
        name: "Grok 4.1 Fast Reasoning",
        version: "4.1",
        inputPrice: 0.2,
        outputPrice: 0.5,
        contextWindow: 131072,
        maxOutput: 16384,
        reasoning: true,
        toolCalling: true
      },
      {
        id: "xai/grok-4-1-fast-non-reasoning",
        name: "Grok 4.1 Fast",
        version: "4.1",
        inputPrice: 0.2,
        outputPrice: 0.5,
        contextWindow: 131072,
        maxOutput: 16384,
        toolCalling: true
      },
      // xai/grok-code-fast-1 delisted 2026-03-12: poor retention (coding users churn),
      // no structured tool calling, alias "grok-code" redirected to deepseek-chat
      {
        id: "xai/grok-4-0709",
        name: "Grok 4 (0709)",
        version: "4-0709",
        inputPrice: 3,
        outputPrice: 15,
        contextWindow: 131072,
        maxOutput: 16384,
        reasoning: true,
        toolCalling: true
      },
      {
        id: "xai/grok-2-vision",
        name: "Grok 2 Vision",
        version: "2",
        inputPrice: 2,
        outputPrice: 10,
        contextWindow: 131072,
        maxOutput: 16384,
        vision: true,
        toolCalling: true
      },
      // xAI Grok 4.20 Family (hidden in picker; explicit-only — mirrors BlockRun hidden:true)
      {
        id: "xai/grok-4.20-reasoning",
        name: "Grok 4.20 Reasoning",
        version: "4.20",
        inputPrice: 2,
        outputPrice: 6,
        contextWindow: 2e6,
        maxOutput: 16384,
        reasoning: true,
        toolCalling: true
      },
      {
        id: "xai/grok-4.20-non-reasoning",
        name: "Grok 4.20",
        version: "4.20",
        inputPrice: 2,
        outputPrice: 6,
        contextWindow: 2e6,
        maxOutput: 16384,
        toolCalling: true
      },
      {
        id: "xai/grok-4.20-multi-agent",
        name: "Grok 4.20 Multi-Agent",
        version: "4.20",
        inputPrice: 2,
        outputPrice: 6,
        contextWindow: 2e6,
        maxOutput: 16384,
        reasoning: true,
        toolCalling: true
      },
      // MiniMax
      {
        id: "minimax/minimax-m2.7",
        name: "MiniMax M2.7",
        version: "m2.7",
        inputPrice: 0.3,
        outputPrice: 1.2,
        contextWindow: 204800,
        maxOutput: 16384,
        reasoning: true,
        agentic: true,
        toolCalling: true
      },
      {
        id: "minimax/minimax-m2.5",
        name: "MiniMax M2.5",
        version: "m2.5",
        inputPrice: 0.3,
        outputPrice: 1.2,
        contextWindow: 204800,
        maxOutput: 16384,
        reasoning: true,
        agentic: true,
        toolCalling: true,
        deprecated: true,
        fallbackModel: "minimax/minimax-m2.7"
      },
      // Free models (hosted by NVIDIA, billingMode: "free" on server)
      // IDs use "free/" prefix so users see them as free in the /model picker.
      // ClawRouter maps free/xxx → nvidia/xxx before sending to BlockRun upstream
      // (see toUpstreamModelId in src/proxy.ts). BlockRun's NVIDIA_MODEL_MAP in
      // src/lib/ai-providers.ts maps known IDs to upstream NIM names; for IDs not
      // in the map, BlockRun falls through to the bare name (modelMap[k] || k),
      // so new entries here only need to match BlockRun's catalog ID — NVIDIA NIM
      // accepts the bare name directly.
      // toolCalling intentionally omitted: structured function calling unverified.
      // 2026-04-29: kept gpt-oss-120b/20b as defaults (heavy user demand); added
      //   v4-pro / v4-flash (1M context, ~5x speed split) and nemotron-3-nano-omni
      //   (first vision-capable free model, 256K context, accepts text/image/video/audio).
      // 2026-04-21: slimmed to 8 models, retired nemotron family + mistral-large-3-675b
      //   + devstral-2-123b with successor redirects.
      {
        id: "free/gpt-oss-120b",
        name: "[Free] GPT-OSS 120B",
        version: "120b",
        inputPrice: 0,
        outputPrice: 0,
        contextWindow: 128e3,
        maxOutput: 16384
      },
      {
        id: "free/gpt-oss-20b",
        name: "[Free] GPT-OSS 20B",
        version: "20b",
        inputPrice: 0,
        outputPrice: 0,
        contextWindow: 128e3,
        maxOutput: 16384
      },
      {
        // V4 Flash: 284B / 13B active MoE, 1M context. ~5x faster than V4 Pro.
        // Strong on chat/summarization (MMLU-Pro 86.2). Caveat: weaker factual
        // recall (SimpleQA 34% vs Pro's 58%) — pick V4 Pro for fact-heavy loops.
        id: "free/deepseek-v4-flash",
        name: "[Free] DeepSeek V4 Flash",
        version: "v4-flash",
        inputPrice: 0,
        outputPrice: 0,
        contextWindow: 1e6,
        maxOutput: 16384,
        reasoning: true
      },
      {
        id: "free/qwen3-coder-480b",
        name: "[Free] Qwen3 Coder 480B",
        version: "480b",
        inputPrice: 0,
        outputPrice: 0,
        contextWindow: 131072,
        maxOutput: 16384
      },
      {
        id: "free/glm-4.7",
        name: "[Free] GLM-4.7",
        version: "4.7",
        inputPrice: 0,
        outputPrice: 0,
        contextWindow: 131072,
        maxOutput: 16384,
        reasoning: true
      },
      {
        id: "free/llama-4-maverick",
        name: "[Free] Llama 4 Maverick",
        version: "4-maverick",
        inputPrice: 0,
        outputPrice: 0,
        contextWindow: 131072,
        maxOutput: 16384,
        reasoning: true
      },
      {
        id: "free/qwen3-next-80b-a3b-thinking",
        name: "[Free] Qwen3-Next 80B Thinking",
        version: "80b-a3b-thinking",
        inputPrice: 0,
        outputPrice: 0,
        contextWindow: 131072,
        maxOutput: 16384,
        reasoning: true
      },
      {
        id: "free/mistral-small-4-119b",
        name: "[Free] Mistral Small 4 119B",
        version: "small-4-119b",
        inputPrice: 0,
        outputPrice: 0,
        contextWindow: 131072,
        maxOutput: 16384
      },
      {
        // Nemotron 3 Nano Omni: first vision-capable free model. 31B / 3.2B active
        // MoE, 256K context. ChartQA 90.3, DocVQA 95.6, MMMU 70.8. Accepts text,
        // images, video (up to 2min), audio (up to 1hr). Released 2026-04-27.
        id: "free/nemotron-3-nano-omni-30b-a3b-reasoning",
        name: "[Free] Nemotron 3 Nano Omni",
        version: "30b-a3b-omni-reasoning",
        inputPrice: 0,
        outputPrice: 0,
        contextWindow: 256e3,
        maxOutput: 16384,
        reasoning: true,
        vision: true
      },
      // Z.AI GLM-5 Models
      {
        id: "zai/glm-5.1",
        name: "GLM-5.1",
        version: "5.1",
        inputPrice: 1.4,
        outputPrice: 4.4,
        contextWindow: 2e5,
        maxOutput: 128e3,
        toolCalling: true,
        promo: { flatPrice: 1e-3, startDate: "2026-04-01", endDate: "2026-04-15" }
      },
      {
        id: "zai/glm-5",
        name: "GLM-5",
        version: "5",
        inputPrice: 1,
        outputPrice: 3.2,
        contextWindow: 2e5,
        maxOutput: 128e3,
        toolCalling: true,
        promo: { flatPrice: 1e-3, startDate: "2026-04-01", endDate: "2026-04-15" }
      },
      {
        id: "zai/glm-5-turbo",
        name: "GLM-5 Turbo",
        version: "5-turbo",
        inputPrice: 1.2,
        outputPrice: 4,
        contextWindow: 2e5,
        maxOutput: 128e3,
        toolCalling: true,
        promo: { flatPrice: 1e-3, startDate: "2026-04-01", endDate: "2026-04-15" }
      }
    ];
    ALIAS_MODELS = Object.entries(MODEL_ALIASES).map(([alias, targetId]) => {
      const target = BLOCKRUN_MODELS.find((m) => m.id === targetId);
      if (!target) return null;
      return toOpenClawModel({ ...target, id: alias, name: `${alias} \u2192 ${target.name}` });
    }).filter((m) => m !== null);
    OPENCLAW_MODELS = [
      ...BLOCKRUN_MODELS.map(toOpenClawModel),
      ...ALIAS_MODELS
    ];
    TOP_MODELS_SET = new Set(TOP_MODELS);
    VISIBLE_OPENCLAW_MODELS = OPENCLAW_MODELS.filter(
      (m) => TOP_MODELS_SET.has(m.id)
    );
  }
});

// src/logger.ts
import { appendFile, mkdir } from "fs/promises";
import { join as join2 } from "path";
import { homedir } from "os";
async function ensureDir() {
  if (dirReady) return;
  await mkdir(LOG_DIR, { recursive: true });
  dirReady = true;
}
async function logUsage(entry) {
  try {
    await ensureDir();
    const date = entry.timestamp.slice(0, 10);
    const file = join2(LOG_DIR, `usage-${date}.jsonl`);
    await appendFile(file, JSON.stringify(entry) + "\n");
  } catch {
  }
}
var LOG_DIR, dirReady;
var init_logger = __esm({
  "src/logger.ts"() {
    "use strict";
    LOG_DIR = join2(homedir(), ".openclaw", "blockrun", "logs");
    dirReady = false;
  }
});

// src/fs-read.ts
import { open } from "fs/promises";
import { openSync, readSync, closeSync, fstatSync } from "fs";
async function readTextFile(filePath) {
  const fh = await open(filePath, "r");
  try {
    const size5 = (await fh.stat()).size;
    const buf = Buffer.alloc(size5);
    let offset = 0;
    while (offset < size5) {
      const { bytesRead } = await fh.read(buf, offset, size5 - offset, offset);
      if (bytesRead === 0) break;
      offset += bytesRead;
    }
    return buf.subarray(0, offset).toString("utf-8");
  } finally {
    await fh.close();
  }
}
function readTextFileSync(filePath) {
  const fd = openSync(filePath, "r");
  try {
    const size5 = fstatSync(fd).size;
    const buf = Buffer.alloc(size5);
    let offset = 0;
    while (offset < size5) {
      const bytesRead = readSync(fd, buf, offset, size5 - offset, offset);
      if (bytesRead === 0) break;
      offset += bytesRead;
    }
    return buf.subarray(0, offset).toString("utf-8");
  } finally {
    closeSync(fd);
  }
}
var init_fs_read = __esm({
  "src/fs-read.ts"() {
    "use strict";
  }
});

// src/version.ts
import { createRequire } from "module";
import { fileURLToPath } from "url";
import { dirname, join as join3 } from "path";
var __filename2, __dirname, require2, pkg, VERSION, USER_AGENT;
var init_version4 = __esm({
  "src/version.ts"() {
    "use strict";
    __filename2 = fileURLToPath(import.meta.url);
    __dirname = dirname(__filename2);
    require2 = createRequire(import.meta.url);
    pkg = require2(join3(__dirname, "..", "package.json"));
    VERSION = pkg.version;
    USER_AGENT = `clawrouter/${VERSION}`;
  }
});

// src/stats.ts
import { readdir, unlink } from "fs/promises";
import { join as join4 } from "path";
import { homedir as homedir2 } from "os";
async function parseLogFile(filePath) {
  try {
    const content = await readTextFile(filePath);
    const lines = content.trim().split("\n").filter(Boolean);
    const entries = [];
    for (const line of lines) {
      try {
        const entry = JSON.parse(line);
        entries.push({
          timestamp: entry.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
          model: entry.model || "unknown",
          tier: entry.tier || "UNKNOWN",
          cost: entry.cost || 0,
          baselineCost: entry.baselineCost || entry.cost || 0,
          savings: entry.savings || 0,
          latencyMs: entry.latencyMs || 0
        });
      } catch {
      }
    }
    return entries;
  } catch {
    return [];
  }
}
async function getLogFiles() {
  try {
    const files = await readdir(LOG_DIR2);
    return files.filter((f) => f.startsWith("usage-") && f.endsWith(".jsonl")).sort().reverse();
  } catch {
    return [];
  }
}
function aggregateDay(date, entries) {
  const byTier = {};
  const byModel = {};
  let totalLatency = 0;
  for (const entry of entries) {
    if (!byTier[entry.tier]) byTier[entry.tier] = { count: 0, cost: 0 };
    byTier[entry.tier].count++;
    byTier[entry.tier].cost += entry.cost;
    if (!byModel[entry.model]) byModel[entry.model] = { count: 0, cost: 0 };
    byModel[entry.model].count++;
    byModel[entry.model].cost += entry.cost;
    totalLatency += entry.latencyMs;
  }
  const totalCost = entries.reduce((sum, e7) => sum + e7.cost, 0);
  const totalBaselineCost = entries.reduce((sum, e7) => sum + e7.baselineCost, 0);
  return {
    date,
    totalRequests: entries.length,
    totalCost,
    totalBaselineCost,
    totalSavings: totalBaselineCost - totalCost,
    avgLatencyMs: entries.length > 0 ? totalLatency / entries.length : 0,
    byTier,
    byModel
  };
}
async function getStats(days = 7) {
  const logFiles = await getLogFiles();
  const filesToRead = logFiles.slice(0, days);
  const dailyBreakdown = [];
  const allByTier = {};
  const allByModel = {};
  let totalRequests = 0;
  let totalCost = 0;
  let totalBaselineCost = 0;
  let totalLatency = 0;
  for (const file of filesToRead) {
    const date = file.replace("usage-", "").replace(".jsonl", "");
    const filePath = join4(LOG_DIR2, file);
    const entries = await parseLogFile(filePath);
    if (entries.length === 0) continue;
    const dayStats = aggregateDay(date, entries);
    dailyBreakdown.push(dayStats);
    totalRequests += dayStats.totalRequests;
    totalCost += dayStats.totalCost;
    totalBaselineCost += dayStats.totalBaselineCost;
    totalLatency += dayStats.avgLatencyMs * dayStats.totalRequests;
    for (const [tier, stats] of Object.entries(dayStats.byTier)) {
      if (!allByTier[tier]) allByTier[tier] = { count: 0, cost: 0 };
      allByTier[tier].count += stats.count;
      allByTier[tier].cost += stats.cost;
    }
    for (const [model, stats] of Object.entries(dayStats.byModel)) {
      if (!allByModel[model]) allByModel[model] = { count: 0, cost: 0 };
      allByModel[model].count += stats.count;
      allByModel[model].cost += stats.cost;
    }
  }
  const byTierWithPercentage = {};
  for (const [tier, stats] of Object.entries(allByTier)) {
    byTierWithPercentage[tier] = {
      ...stats,
      percentage: totalRequests > 0 ? stats.count / totalRequests * 100 : 0
    };
  }
  const byModelWithPercentage = {};
  for (const [model, stats] of Object.entries(allByModel)) {
    byModelWithPercentage[model] = {
      ...stats,
      percentage: totalRequests > 0 ? stats.count / totalRequests * 100 : 0
    };
  }
  const totalSavings = totalBaselineCost - totalCost;
  const savingsPercentage = totalBaselineCost > 0 ? totalSavings / totalBaselineCost * 100 : 0;
  let entriesWithBaseline = 0;
  for (const day of dailyBreakdown) {
    if (day.totalBaselineCost !== day.totalCost) {
      entriesWithBaseline += day.totalRequests;
    }
  }
  return {
    period: days === 1 ? "today" : `last ${days} days`,
    totalRequests,
    totalCost,
    totalBaselineCost,
    totalSavings,
    savingsPercentage,
    avgLatencyMs: totalRequests > 0 ? totalLatency / totalRequests : 0,
    avgCostPerRequest: totalRequests > 0 ? totalCost / totalRequests : 0,
    byTier: byTierWithPercentage,
    byModel: byModelWithPercentage,
    dailyBreakdown: dailyBreakdown.reverse(),
    // Oldest first for charts
    entriesWithBaseline
    // How many entries have valid baseline tracking
  };
}
function formatStatsAscii(stats) {
  const lines = [];
  lines.push("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557");
  lines.push(`\u2551          ClawRouter by BlockRun v${VERSION}`.padEnd(61) + "\u2551");
  lines.push("\u2551                Usage Statistics                            \u2551");
  lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
  lines.push(`\u2551  Period: ${stats.period.padEnd(49)}\u2551`);
  lines.push(`\u2551  Total Requests: ${stats.totalRequests.toString().padEnd(41)}\u2551`);
  lines.push(`\u2551  Total Cost: $${stats.totalCost.toFixed(4).padEnd(43)}\u2551`);
  lines.push(`\u2551  Baseline Cost (Opus 4.5): $${stats.totalBaselineCost.toFixed(4).padEnd(30)}\u2551`);
  const savingsLine = `\u2551  \u{1F4B0} Total Saved: $${stats.totalSavings.toFixed(4)} (${stats.savingsPercentage.toFixed(1)}%)`;
  if (stats.entriesWithBaseline < stats.totalRequests && stats.entriesWithBaseline > 0) {
    lines.push(savingsLine.padEnd(61) + "\u2551");
    const note = `\u2551     (based on ${stats.entriesWithBaseline}/${stats.totalRequests} tracked requests)`;
    lines.push(note.padEnd(61) + "\u2551");
  } else {
    lines.push(savingsLine.padEnd(61) + "\u2551");
  }
  lines.push(`\u2551  Avg Latency: ${stats.avgLatencyMs.toFixed(0)}ms`.padEnd(61) + "\u2551");
  lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
  lines.push("\u2551  Routing by Tier:                                          \u2551");
  const knownTiers = ["SIMPLE", "MEDIUM", "COMPLEX", "REASONING", "DIRECT"];
  const allTiers = Object.keys(stats.byTier);
  const otherTiers = allTiers.filter((t) => !knownTiers.includes(t));
  const tierOrder = [...knownTiers.filter((t) => stats.byTier[t]), ...otherTiers];
  for (const tier of tierOrder) {
    const data = stats.byTier[tier];
    if (data) {
      const bar = "\u2588".repeat(Math.min(20, Math.round(data.percentage / 5)));
      const displayTier = tier === "UNKNOWN" ? "OTHER" : tier;
      const line = `\u2551    ${displayTier.padEnd(10)} ${bar.padEnd(20)} ${data.percentage.toFixed(1).padStart(5)}% (${data.count})`;
      lines.push(line.padEnd(61) + "\u2551");
    }
  }
  lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
  lines.push("\u2551  Top Models:                                               \u2551");
  const sortedModels = Object.entries(stats.byModel).sort((a, b) => b[1].count - a[1].count).slice(0, 5);
  for (const [model, data] of sortedModels) {
    const shortModel = model.length > 25 ? model.slice(0, 22) + "..." : model;
    const line = `\u2551    ${shortModel.padEnd(25)} ${data.count.toString().padStart(5)} reqs  $${data.cost.toFixed(4)}`;
    lines.push(line.padEnd(61) + "\u2551");
  }
  if (stats.dailyBreakdown.length > 0) {
    lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
    lines.push("\u2551  Daily Breakdown:                                          \u2551");
    lines.push("\u2551    Date        Requests    Cost      Saved                 \u2551");
    for (const day of stats.dailyBreakdown.slice(-7)) {
      const saved = day.totalBaselineCost - day.totalCost;
      const line = `\u2551    ${day.date}   ${day.totalRequests.toString().padStart(6)}    $${day.totalCost.toFixed(4).padStart(8)}  $${saved.toFixed(4)}`;
      lines.push(line.padEnd(61) + "\u2551");
    }
  }
  lines.push("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D");
  return lines.join("\n");
}
async function formatRecentLogs(days = 1) {
  const logFiles = await getLogFiles();
  const filesToRead = logFiles.slice(0, days);
  const allEntries = [];
  for (const file of filesToRead) {
    const entries = await parseLogFile(join4(LOG_DIR2, file));
    allEntries.push(...entries);
  }
  allEntries.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
  const lines = [];
  lines.push("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557");
  lines.push(
    `\u2551  ClawRouter Request Log \u2014 last ${days === 1 ? "24h" : `${days} days`}`.padEnd(72) + "\u2551"
  );
  lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
  lines.push("\u2551  Time            \u2551  Model                   \u2551  Cost   \u2551  ms  \u2551 Status \u2551");
  lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256C\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256C\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256C\u2550\u2550\u2550\u2550\u2550\u2550\u256C\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
  if (allEntries.length === 0) {
    lines.push("\u2551  No requests found".padEnd(72) + "\u2551");
  }
  let totalCost = 0;
  for (const e7 of allEntries) {
    const time = e7.timestamp.slice(11, 19);
    const date = e7.timestamp.slice(5, 10);
    const displayTime = `${date} ${time}`;
    const model = e7.model.length > 24 ? e7.model.slice(0, 21) + "..." : e7.model;
    const cost = `$${e7.cost.toFixed(4)}`;
    const ms = e7.latencyMs > 9999 ? `${(e7.latencyMs / 1e3).toFixed(1)}s` : `${e7.latencyMs}ms`;
    const status = e7.status === "error" ? " ERROR  " : " OK     ";
    totalCost += e7.cost;
    lines.push(
      `\u2551  ${displayTime.padEnd(16)}\u2551  ${model.padEnd(24)}\u2551  ${cost.padStart(7)}\u2551  ${ms.padStart(4)}\u2551${status}\u2551`
    );
  }
  lines.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
  lines.push(
    `\u2551  ${allEntries.length} request${allEntries.length !== 1 ? "s" : ""}  Total spent: $${totalCost.toFixed(4)}`.padEnd(
      72
    ) + "\u2551"
  );
  lines.push(
    "\u2551  Logs: ~/.openclaw/blockrun/logs/  (JSONL \u2014 one entry per request)".padEnd(72) + "\u2551"
  );
  lines.push("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D");
  return lines.join("\n");
}
async function clearStats() {
  try {
    const files = await readdir(LOG_DIR2);
    const logFiles = files.filter((f) => f.startsWith("usage-") && f.endsWith(".jsonl"));
    await Promise.all(logFiles.map((f) => unlink(join4(LOG_DIR2, f))));
    return { deletedFiles: logFiles.length };
  } catch {
    return { deletedFiles: 0 };
  }
}
var LOG_DIR2;
var init_stats = __esm({
  "src/stats.ts"() {
    "use strict";
    init_fs_read();
    init_version4();
    LOG_DIR2 = join4(homedir2(), ".openclaw", "blockrun", "logs");
  }
});

// src/dedup.ts
import { createHash } from "crypto";
function canonicalize(obj) {
  if (obj === null || typeof obj !== "object") {
    return obj;
  }
  if (Array.isArray(obj)) {
    return obj.map(canonicalize);
  }
  const sorted = {};
  for (const key of Object.keys(obj).sort()) {
    sorted[key] = canonicalize(obj[key]);
  }
  return sorted;
}
function stripTimestamps(obj) {
  if (obj === null || typeof obj !== "object") {
    return obj;
  }
  if (Array.isArray(obj)) {
    return obj.map(stripTimestamps);
  }
  const result = {};
  for (const [key, value] of Object.entries(obj)) {
    if (key === "content" && typeof value === "string") {
      result[key] = value.replace(TIMESTAMP_PATTERN, "");
    } else {
      result[key] = stripTimestamps(value);
    }
  }
  return result;
}
var DEFAULT_TTL_MS2, MAX_BODY_SIZE, TIMESTAMP_PATTERN, RequestDeduplicator;
var init_dedup = __esm({
  "src/dedup.ts"() {
    "use strict";
    DEFAULT_TTL_MS2 = 3e4;
    MAX_BODY_SIZE = 1048576;
    TIMESTAMP_PATTERN = /^\[\w{3}\s+\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+\w+\]\s*/;
    RequestDeduplicator = class {
      inflight = /* @__PURE__ */ new Map();
      completed = /* @__PURE__ */ new Map();
      ttlMs;
      constructor(ttlMs = DEFAULT_TTL_MS2) {
        this.ttlMs = ttlMs;
      }
      /** Hash request body to create a dedup key. */
      static hash(body) {
        let content = body;
        try {
          const parsed = JSON.parse(body.toString());
          const stripped = stripTimestamps(parsed);
          const canonical = canonicalize(stripped);
          content = Buffer.from(JSON.stringify(canonical));
        } catch {
        }
        return createHash("sha256").update(content).digest("hex").slice(0, 16);
      }
      /** Check if a response is cached for this key. */
      getCached(key) {
        const entry = this.completed.get(key);
        if (!entry) return void 0;
        if (Date.now() - entry.completedAt > this.ttlMs) {
          this.completed.delete(key);
          return void 0;
        }
        return entry;
      }
      /** Check if a request with this key is currently in-flight. Returns a promise to wait on. */
      getInflight(key) {
        const entry = this.inflight.get(key);
        if (!entry) return void 0;
        return new Promise((resolve) => {
          entry.resolvers.push(resolve);
        });
      }
      /** Mark a request as in-flight. */
      markInflight(key) {
        this.inflight.set(key, {
          resolvers: []
        });
      }
      /** Complete an in-flight request — cache result and notify waiters. */
      complete(key, result) {
        if (result.body.length <= MAX_BODY_SIZE) {
          this.completed.set(key, result);
        }
        const entry = this.inflight.get(key);
        if (entry) {
          for (const resolve of entry.resolvers) {
            resolve(result);
          }
          this.inflight.delete(key);
        }
        this.prune();
      }
      /** Remove an in-flight entry on error (don't cache failures).
       *  Also rejects any waiters so they can retry independently. */
      removeInflight(key) {
        const entry = this.inflight.get(key);
        if (entry) {
          const errorBody = Buffer.from(
            JSON.stringify({
              error: { message: "Original request failed, please retry", type: "dedup_origin_failed" }
            })
          );
          for (const resolve of entry.resolvers) {
            resolve({
              status: 503,
              headers: { "content-type": "application/json" },
              body: errorBody,
              completedAt: Date.now()
            });
          }
          this.inflight.delete(key);
        }
      }
      /** Prune expired completed entries. */
      prune() {
        const now = Date.now();
        for (const [key, entry] of this.completed) {
          if (now - entry.completedAt > this.ttlMs) {
            this.completed.delete(key);
          }
        }
      }
    };
  }
});

// src/response-cache.ts
import { createHash as createHash2 } from "crypto";
function canonicalize2(obj) {
  if (obj === null || typeof obj !== "object") {
    return obj;
  }
  if (Array.isArray(obj)) {
    return obj.map(canonicalize2);
  }
  const sorted = {};
  for (const key of Object.keys(obj).sort()) {
    sorted[key] = canonicalize2(obj[key]);
  }
  return sorted;
}
function normalizeForCache(obj) {
  const result = {};
  for (const [key, value] of Object.entries(obj)) {
    if (["user", "request_id", "x-request-id"].includes(key)) {
      continue;
    }
    if (key === "messages" && Array.isArray(value)) {
      result[key] = value.map((msg) => {
        if (typeof msg === "object" && msg !== null) {
          const m = msg;
          if (typeof m.content === "string") {
            return { ...m, content: m.content.replace(TIMESTAMP_PATTERN2, "") };
          }
        }
        return msg;
      });
    } else {
      result[key] = value;
    }
  }
  return result;
}
var DEFAULT_CONFIG, TIMESTAMP_PATTERN2, ResponseCache;
var init_response_cache = __esm({
  "src/response-cache.ts"() {
    "use strict";
    DEFAULT_CONFIG = {
      maxSize: 200,
      defaultTTL: 600,
      maxItemSize: 1048576,
      // 1MB
      enabled: true
    };
    TIMESTAMP_PATTERN2 = /^\[\w{3}\s+\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}\s+\w+\]\s*/;
    ResponseCache = class {
      cache = /* @__PURE__ */ new Map();
      expirationHeap = [];
      config;
      // Stats for monitoring
      stats = {
        hits: 0,
        misses: 0,
        evictions: 0
      };
      constructor(config = {}) {
        const filtered = Object.fromEntries(
          Object.entries(config).filter(([, v]) => v !== void 0)
        );
        this.config = { ...DEFAULT_CONFIG, ...filtered };
      }
      /**
       * Generate cache key from request body.
       * Hashes: model + messages + temperature + max_tokens + other params
       */
      static generateKey(body) {
        try {
          const parsed = JSON.parse(typeof body === "string" ? body : body.toString());
          const normalized = normalizeForCache(parsed);
          const canonical = canonicalize2(normalized);
          const keyContent = JSON.stringify(canonical);
          return createHash2("sha256").update(keyContent).digest("hex").slice(0, 32);
        } catch {
          const content = typeof body === "string" ? body : body.toString();
          return createHash2("sha256").update(content).digest("hex").slice(0, 32);
        }
      }
      /**
       * Check if caching is enabled for this request.
       * Respects cache control headers and request params.
       */
      shouldCache(body, headers) {
        if (!this.config.enabled) return false;
        if (headers?.["cache-control"]?.includes("no-cache")) {
          return false;
        }
        try {
          const parsed = JSON.parse(typeof body === "string" ? body : body.toString());
          if (parsed.cache === false || parsed.no_cache === true) {
            return false;
          }
        } catch {
        }
        return true;
      }
      /**
       * Get cached response if available and not expired.
       */
      get(key) {
        const entry = this.cache.get(key);
        if (!entry) {
          this.stats.misses++;
          return void 0;
        }
        if (Date.now() > entry.expiresAt) {
          this.cache.delete(key);
          this.stats.misses++;
          return void 0;
        }
        this.stats.hits++;
        return entry;
      }
      /**
       * Cache a response with optional custom TTL.
       */
      set(key, response, ttlSeconds) {
        if (!this.config.enabled || this.config.maxSize <= 0) return;
        if (response.body.length > this.config.maxItemSize) {
          console.log(`[ResponseCache] Skipping cache - item too large: ${response.body.length} bytes`);
          return;
        }
        if (response.status >= 400) {
          return;
        }
        if (this.cache.size >= this.config.maxSize) {
          this.evict();
        }
        const now = Date.now();
        const ttl = ttlSeconds ?? this.config.defaultTTL;
        const expiresAt = now + ttl * 1e3;
        const entry = {
          ...response,
          cachedAt: now,
          expiresAt
        };
        this.cache.set(key, entry);
        this.expirationHeap.push({ expiresAt, key });
      }
      /**
       * Evict expired and oldest entries to make room.
       */
      evict() {
        const now = Date.now();
        this.expirationHeap.sort((a, b) => a.expiresAt - b.expiresAt);
        while (this.expirationHeap.length > 0) {
          const oldest = this.expirationHeap[0];
          const entry = this.cache.get(oldest.key);
          if (!entry || entry.expiresAt !== oldest.expiresAt) {
            this.expirationHeap.shift();
            continue;
          }
          if (oldest.expiresAt <= now) {
            this.cache.delete(oldest.key);
            this.expirationHeap.shift();
            this.stats.evictions++;
          } else {
            break;
          }
        }
        while (this.cache.size >= this.config.maxSize && this.expirationHeap.length > 0) {
          const oldest = this.expirationHeap.shift();
          if (this.cache.has(oldest.key)) {
            this.cache.delete(oldest.key);
            this.stats.evictions++;
          }
        }
      }
      /**
       * Get cache statistics.
       */
      getStats() {
        const total = this.stats.hits + this.stats.misses;
        const hitRate = total > 0 ? (this.stats.hits / total * 100).toFixed(1) + "%" : "0%";
        return {
          size: this.cache.size,
          maxSize: this.config.maxSize,
          hits: this.stats.hits,
          misses: this.stats.misses,
          evictions: this.stats.evictions,
          hitRate
        };
      }
      /**
       * Clear all cached entries.
       */
      clear() {
        this.cache.clear();
        this.expirationHeap = [];
      }
      /**
       * Check if cache is enabled.
       */
      isEnabled() {
        return this.config.enabled;
      }
    };
  }
});

// src/errors.ts
function isInsufficientFundsError(error) {
  return error instanceof Error && error.code === "INSUFFICIENT_FUNDS";
}
function isEmptyWalletError(error) {
  return error instanceof Error && error.code === "EMPTY_WALLET";
}
function isBalanceError(error) {
  return isInsufficientFundsError(error) || isEmptyWalletError(error);
}
function isRpcError(error) {
  return error instanceof Error && error.code === "RPC_ERROR";
}
var InsufficientFundsError2, EmptyWalletError, RpcError2;
var init_errors5 = __esm({
  "src/errors.ts"() {
    "use strict";
    InsufficientFundsError2 = class extends Error {
      code = "INSUFFICIENT_FUNDS";
      currentBalanceUSD;
      requiredUSD;
      walletAddress;
      constructor(opts) {
        const msg = [
          `Insufficient balance. Current: ${opts.currentBalanceUSD}, Required: ${opts.requiredUSD}`,
          `Options:`,
          `  1. Fund wallet: ${opts.walletAddress}`,
          `  2. Use free model: /model free`
        ].join("\n");
        super(msg);
        this.name = "InsufficientFundsError";
        this.currentBalanceUSD = opts.currentBalanceUSD;
        this.requiredUSD = opts.requiredUSD;
        this.walletAddress = opts.walletAddress;
      }
    };
    EmptyWalletError = class extends Error {
      code = "EMPTY_WALLET";
      walletAddress;
      constructor(walletAddress) {
        const msg = [
          `No USDC balance.`,
          `Options:`,
          `  1. Fund wallet: ${walletAddress}`,
          `  2. Use free model: /model free`,
          `  3. Uninstall: bash ~/.openclaw/extensions/clawrouter/scripts/uninstall.sh`
        ].join("\n");
        super(msg);
        this.name = "EmptyWalletError";
        this.walletAddress = walletAddress;
      }
    };
    RpcError2 = class extends Error {
      code = "RPC_ERROR";
      originalError;
      constructor(message, originalError) {
        super(`RPC error: ${message}. Check network connectivity.`);
        this.name = "RpcError";
        this.originalError = originalError;
      }
    };
  }
});

// src/balance.ts
var USDC_BASE, CACHE_TTL_MS, BALANCE_THRESHOLDS, BalanceMonitor;
var init_balance = __esm({
  "src/balance.ts"() {
    "use strict";
    init_esm();
    init_chains();
    init_errors5();
    USDC_BASE = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
    CACHE_TTL_MS = 3e4;
    BALANCE_THRESHOLDS = {
      /** Low balance warning threshold: $1.00 */
      LOW_BALANCE_MICROS: 1000000n,
      /** Effectively zero threshold: $0.0001 (covers dust/rounding) */
      ZERO_THRESHOLD: 100n
    };
    BalanceMonitor = class {
      client;
      walletAddress;
      /** Cached balance (null = not yet fetched) */
      cachedBalance = null;
      /** Timestamp when cache was last updated */
      cachedAt = 0;
      constructor(walletAddress) {
        this.walletAddress = walletAddress;
        this.client = createPublicClient({
          chain: base,
          transport: http(void 0, {
            timeout: 1e4
            // 10 second timeout to prevent hanging on slow RPC
          })
        });
      }
      /**
       * Check current USDC balance.
       * Uses cache if valid, otherwise fetches from RPC.
       */
      async checkBalance() {
        const now = Date.now();
        if (this.cachedBalance !== null && this.cachedBalance > 0n && now - this.cachedAt < CACHE_TTL_MS) {
          return this.buildInfo(this.cachedBalance);
        }
        const balance = await this.fetchBalance();
        if (balance > 0n) {
          this.cachedBalance = balance;
          this.cachedAt = now;
        }
        return this.buildInfo(balance);
      }
      /**
       * Check if balance is sufficient for an estimated cost.
       *
       * @param estimatedCostMicros - Estimated cost in USDC smallest unit (6 decimals)
       */
      async checkSufficient(estimatedCostMicros) {
        const info = await this.checkBalance();
        if (info.balance >= estimatedCostMicros) {
          return { sufficient: true, info };
        }
        const shortfall = estimatedCostMicros - info.balance;
        return {
          sufficient: false,
          info,
          shortfall: this.formatUSDC(shortfall)
        };
      }
      /**
       * Optimistically deduct estimated cost from cached balance.
       * Call this after a successful payment to keep cache accurate.
       *
       * @param amountMicros - Amount to deduct in USDC smallest unit
       */
      deductEstimated(amountMicros) {
        if (this.cachedBalance !== null && this.cachedBalance >= amountMicros) {
          this.cachedBalance -= amountMicros;
        }
      }
      /**
       * Invalidate cache, forcing next checkBalance() to fetch from RPC.
       * Call this after a payment failure to get accurate balance.
       */
      invalidate() {
        this.cachedBalance = null;
        this.cachedAt = 0;
      }
      /**
       * Force refresh balance from RPC (ignores cache).
       */
      async refresh() {
        this.invalidate();
        return this.checkBalance();
      }
      /**
       * Format USDC amount (in micros) as "$X.XX".
       */
      formatUSDC(amountMicros) {
        const dollars = Number(amountMicros) / 1e6;
        return `$${dollars.toFixed(2)}`;
      }
      /**
       * Get the wallet address being monitored.
       */
      getWalletAddress() {
        return this.walletAddress;
      }
      /** Fetch balance from RPC */
      async fetchBalance() {
        try {
          const balance = await this.client.readContract({
            address: USDC_BASE,
            abi: erc20Abi,
            functionName: "balanceOf",
            args: [this.walletAddress]
          });
          return balance;
        } catch (error) {
          throw new RpcError2(error instanceof Error ? error.message : "Unknown error", error);
        }
      }
      /** Build BalanceInfo from raw balance */
      buildInfo(balance) {
        return {
          balance,
          balanceUSD: this.formatUSDC(balance),
          isLow: balance < BALANCE_THRESHOLDS.LOW_BALANCE_MICROS,
          isEmpty: balance < BALANCE_THRESHOLDS.ZERO_THRESHOLD,
          walletAddress: this.walletAddress
        };
      }
    };
  }
});

// node_modules/@noble/hashes/utils.js
function isBytes7(a) {
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
}
function anumber5(n, title = "") {
  if (typeof n !== "number") {
    const prefix = title && `"${title}" `;
    throw new TypeError(`${prefix}expected number, got ${typeof n}`);
  }
  if (!Number.isSafeInteger(n) || n < 0) {
    const prefix = title && `"${title}" `;
    throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
  }
}
function abytes6(value, length, title = "") {
  const bytes = isBytes7(value);
  const len = value?.length;
  const needsLen = length !== void 0;
  if (!bytes || needsLen && len !== length) {
    const prefix = title && `"${title}" `;
    const ofLen = needsLen ? ` of length ${length}` : "";
    const got = bytes ? `length=${len}` : `type=${typeof value}`;
    const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
    if (!bytes)
      throw new TypeError(message);
    throw new RangeError(message);
  }
  return value;
}
function ahash4(h) {
  if (typeof h !== "function" || typeof h.create !== "function")
    throw new TypeError("Hash must wrapped by utils.createHasher");
  anumber5(h.outputLen);
  anumber5(h.blockLen);
  if (h.outputLen < 1)
    throw new Error('"outputLen" must be >= 1');
  if (h.blockLen < 1)
    throw new Error('"blockLen" must be >= 1');
}
function aexists4(instance, checkFinished = true) {
  if (instance.destroyed)
    throw new Error("Hash instance has been destroyed");
  if (checkFinished && instance.finished)
    throw new Error("Hash#digest() has already been called");
}
function aoutput4(out, instance) {
  abytes6(out, void 0, "digestInto() output");
  const min = instance.outputLen;
  if (out.length < min) {
    throw new RangeError('"digestInto() output" expected to be of length >=' + min);
  }
}
function clean4(...arrays) {
  for (let i = 0; i < arrays.length; i++) {
    arrays[i].fill(0);
  }
}
function createView4(arr) {
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
function rotr4(word, shift) {
  return word << 32 - shift | word >>> shift;
}
function rotl(word, shift) {
  return word << shift | word >>> 32 - shift >>> 0;
}
function bytesToHex4(bytes) {
  abytes6(bytes);
  if (hasHexBuiltin3)
    return bytes.toHex();
  let hex = "";
  for (let i = 0; i < bytes.length; i++) {
    hex += hexes5[bytes[i]];
  }
  return hex;
}
function asciiToBase163(ch) {
  if (ch >= asciis3._0 && ch <= asciis3._9)
    return ch - asciis3._0;
  if (ch >= asciis3.A && ch <= asciis3.F)
    return ch - (asciis3.A - 10);
  if (ch >= asciis3.a && ch <= asciis3.f)
    return ch - (asciis3.a - 10);
  return;
}
function hexToBytes4(hex) {
  if (typeof hex !== "string")
    throw new TypeError("hex string expected, got " + typeof hex);
  if (hasHexBuiltin3) {
    try {
      return Uint8Array.fromHex(hex);
    } catch (error) {
      if (error instanceof SyntaxError)
        throw new RangeError(error.message);
      throw error;
    }
  }
  const hl = hex.length;
  const al = hl / 2;
  if (hl % 2)
    throw new RangeError("hex string expected, got unpadded hex of length " + hl);
  const array = new Uint8Array(al);
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
    const n1 = asciiToBase163(hex.charCodeAt(hi));
    const n2 = asciiToBase163(hex.charCodeAt(hi + 1));
    if (n1 === void 0 || n2 === void 0) {
      const char = hex[hi] + hex[hi + 1];
      throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
    }
    array[ai] = n1 * 16 + n2;
  }
  return array;
}
function concatBytes6(...arrays) {
  let sum = 0;
  for (let i = 0; i < arrays.length; i++) {
    const a = arrays[i];
    abytes6(a);
    sum += a.length;
  }
  const res = new Uint8Array(sum);
  for (let i = 0, pad4 = 0; i < arrays.length; i++) {
    const a = arrays[i];
    res.set(a, pad4);
    pad4 += a.length;
  }
  return res;
}
function createHasher5(hashCons, info = {}) {
  const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
  const tmp = hashCons(void 0);
  hashC.outputLen = tmp.outputLen;
  hashC.blockLen = tmp.blockLen;
  hashC.canXOF = tmp.canXOF;
  hashC.create = (opts) => hashCons(opts);
  Object.assign(hashC, info);
  return Object.freeze(hashC);
}
function randomBytes4(bytesLength = 32) {
  anumber5(bytesLength, "bytesLength");
  const cr = typeof globalThis === "object" ? globalThis.crypto : null;
  if (typeof cr?.getRandomValues !== "function")
    throw new Error("crypto.getRandomValues must be defined");
  if (bytesLength > 65536)
    throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
  return cr.getRandomValues(new Uint8Array(bytesLength));
}
var hasHexBuiltin3, hexes5, asciis3, oidNist;
var init_utils10 = __esm({
  "node_modules/@noble/hashes/utils.js"() {
    "use strict";
    hasHexBuiltin3 = /* @__PURE__ */ (() => (
      // @ts-ignore
      typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
    ))();
    hexes5 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
    asciis3 = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
    oidNist = (suffix) => ({
      // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
      // Larger suffix values would need base-128 OID encoding and a different length byte.
      oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
    });
  }
});

// node_modules/@noble/hashes/_md.js
function Chi4(a, b, c) {
  return a & b ^ ~a & c;
}
function Maj4(a, b, c) {
  return a & b ^ a & c ^ b & c;
}
var HashMD4, SHA256_IV4, SHA512_IV4;
var init_md4 = __esm({
  "node_modules/@noble/hashes/_md.js"() {
    "use strict";
    init_utils10();
    HashMD4 = class {
      blockLen;
      outputLen;
      canXOF = false;
      padOffset;
      isLE;
      // For partial updates less than block size
      buffer;
      view;
      finished = false;
      length = 0;
      pos = 0;
      destroyed = false;
      constructor(blockLen, outputLen, padOffset, isLE3) {
        this.blockLen = blockLen;
        this.outputLen = outputLen;
        this.padOffset = padOffset;
        this.isLE = isLE3;
        this.buffer = new Uint8Array(blockLen);
        this.view = createView4(this.buffer);
      }
      update(data) {
        aexists4(this);
        abytes6(data);
        const { view, buffer: buffer2, blockLen } = this;
        const len = data.length;
        for (let pos = 0; pos < len; ) {
          const take = Math.min(blockLen - this.pos, len - pos);
          if (take === blockLen) {
            const dataView = createView4(data);
            for (; blockLen <= len - pos; pos += blockLen)
              this.process(dataView, pos);
            continue;
          }
          buffer2.set(data.subarray(pos, pos + take), this.pos);
          this.pos += take;
          pos += take;
          if (this.pos === blockLen) {
            this.process(view, 0);
            this.pos = 0;
          }
        }
        this.length += data.length;
        this.roundClean();
        return this;
      }
      digestInto(out) {
        aexists4(this);
        aoutput4(out, this);
        this.finished = true;
        const { buffer: buffer2, view, blockLen, isLE: isLE3 } = this;
        let { pos } = this;
        buffer2[pos++] = 128;
        clean4(this.buffer.subarray(pos));
        if (this.padOffset > blockLen - pos) {
          this.process(view, 0);
          pos = 0;
        }
        for (let i = pos; i < blockLen; i++)
          buffer2[i] = 0;
        view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE3);
        this.process(view, 0);
        const oview = createView4(out);
        const len = this.outputLen;
        if (len % 4)
          throw new Error("_sha2: outputLen must be aligned to 32bit");
        const outLen = len / 4;
        const state = this.get();
        if (outLen > state.length)
          throw new Error("_sha2: outputLen bigger than state");
        for (let i = 0; i < outLen; i++)
          oview.setUint32(4 * i, state[i], isLE3);
      }
      digest() {
        const { buffer: buffer2, outputLen } = this;
        this.digestInto(buffer2);
        const res = buffer2.slice(0, outputLen);
        this.destroy();
        return res;
      }
      _cloneInto(to) {
        to ||= new this.constructor();
        to.set(...this.get());
        const { blockLen, buffer: buffer2, length, finished: finished2, destroyed, pos } = this;
        to.destroyed = destroyed;
        to.finished = finished2;
        to.length = length;
        to.pos = pos;
        if (length % blockLen)
          to.buffer.set(buffer2);
        return to;
      }
      clone() {
        return this._cloneInto();
      }
    };
    SHA256_IV4 = /* @__PURE__ */ Uint32Array.from([
      1779033703,
      3144134277,
      1013904242,
      2773480762,
      1359893119,
      2600822924,
      528734635,
      1541459225
    ]);
    SHA512_IV4 = /* @__PURE__ */ Uint32Array.from([
      1779033703,
      4089235720,
      3144134277,
      2227873595,
      1013904242,
      4271175723,
      2773480762,
      1595750129,
      1359893119,
      2917565137,
      2600822924,
      725511199,
      528734635,
      4215389547,
      1541459225,
      327033209
    ]);
  }
});

// node_modules/@noble/hashes/_u64.js
function fromBig4(n, le = false) {
  if (le)
    return { h: Number(n & U32_MASK644), l: Number(n >> _32n4 & U32_MASK644) };
  return { h: Number(n >> _32n4 & U32_MASK644) | 0, l: Number(n & U32_MASK644) | 0 };
}
function split4(lst, le = false) {
  const len = lst.length;
  let Ah = new Uint32Array(len);
  let Al = new Uint32Array(len);
  for (let i = 0; i < len; i++) {
    const { h, l: l2 } = fromBig4(lst[i], le);
    [Ah[i], Al[i]] = [h, l2];
  }
  return [Ah, Al];
}
function add2(Ah, Al, Bh, Bl) {
  const l2 = (Al >>> 0) + (Bl >>> 0);
  return { h: Ah + Bh + (l2 / 2 ** 32 | 0) | 0, l: l2 | 0 };
}
var U32_MASK644, _32n4, shrSH2, shrSL2, rotrSH2, rotrSL2, rotrBH2, rotrBL2, add3L2, add3H2, add4L2, add4H2, add5L2, add5H2;
var init_u644 = __esm({
  "node_modules/@noble/hashes/_u64.js"() {
    "use strict";
    U32_MASK644 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
    _32n4 = /* @__PURE__ */ BigInt(32);
    shrSH2 = (h, _l, s3) => h >>> s3;
    shrSL2 = (h, l2, s3) => h << 32 - s3 | l2 >>> s3;
    rotrSH2 = (h, l2, s3) => h >>> s3 | l2 << 32 - s3;
    rotrSL2 = (h, l2, s3) => h << 32 - s3 | l2 >>> s3;
    rotrBH2 = (h, l2, s3) => h << 64 - s3 | l2 >>> s3 - 32;
    rotrBL2 = (h, l2, s3) => h >>> s3 - 32 | l2 << 64 - s3;
    add3L2 = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
    add3H2 = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
    add4L2 = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
    add4H2 = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
    add5L2 = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
    add5H2 = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
  }
});

// node_modules/@noble/hashes/sha2.js
var SHA256_K4, SHA256_W4, SHA2_32B, _SHA256, K5122, SHA512_Kh2, SHA512_Kl2, SHA512_W_H2, SHA512_W_L2, SHA2_64B, _SHA512, sha2566, sha5122;
var init_sha24 = __esm({
  "node_modules/@noble/hashes/sha2.js"() {
    "use strict";
    init_md4();
    init_u644();
    init_utils10();
    SHA256_K4 = /* @__PURE__ */ Uint32Array.from([
      1116352408,
      1899447441,
      3049323471,
      3921009573,
      961987163,
      1508970993,
      2453635748,
      2870763221,
      3624381080,
      310598401,
      607225278,
      1426881987,
      1925078388,
      2162078206,
      2614888103,
      3248222580,
      3835390401,
      4022224774,
      264347078,
      604807628,
      770255983,
      1249150122,
      1555081692,
      1996064986,
      2554220882,
      2821834349,
      2952996808,
      3210313671,
      3336571891,
      3584528711,
      113926993,
      338241895,
      666307205,
      773529912,
      1294757372,
      1396182291,
      1695183700,
      1986661051,
      2177026350,
      2456956037,
      2730485921,
      2820302411,
      3259730800,
      3345764771,
      3516065817,
      3600352804,
      4094571909,
      275423344,
      430227734,
      506948616,
      659060556,
      883997877,
      958139571,
      1322822218,
      1537002063,
      1747873779,
      1955562222,
      2024104815,
      2227730452,
      2361852424,
      2428436474,
      2756734187,
      3204031479,
      3329325298
    ]);
    SHA256_W4 = /* @__PURE__ */ new Uint32Array(64);
    SHA2_32B = class extends HashMD4 {
      constructor(outputLen) {
        super(64, outputLen, 8, false);
      }
      get() {
        const { A, B, C, D: D2, E, F, G, H } = this;
        return [A, B, C, D2, E, F, G, H];
      }
      // prettier-ignore
      set(A, B, C, D2, E, F, G, H) {
        this.A = A | 0;
        this.B = B | 0;
        this.C = C | 0;
        this.D = D2 | 0;
        this.E = E | 0;
        this.F = F | 0;
        this.G = G | 0;
        this.H = H | 0;
      }
      process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
          SHA256_W4[i] = view.getUint32(offset, false);
        for (let i = 16; i < 64; i++) {
          const W15 = SHA256_W4[i - 15];
          const W2 = SHA256_W4[i - 2];
          const s0 = rotr4(W15, 7) ^ rotr4(W15, 18) ^ W15 >>> 3;
          const s1 = rotr4(W2, 17) ^ rotr4(W2, 19) ^ W2 >>> 10;
          SHA256_W4[i] = s1 + SHA256_W4[i - 7] + s0 + SHA256_W4[i - 16] | 0;
        }
        let { A, B, C, D: D2, E, F, G, H } = this;
        for (let i = 0; i < 64; i++) {
          const sigma1 = rotr4(E, 6) ^ rotr4(E, 11) ^ rotr4(E, 25);
          const T1 = H + sigma1 + Chi4(E, F, G) + SHA256_K4[i] + SHA256_W4[i] | 0;
          const sigma0 = rotr4(A, 2) ^ rotr4(A, 13) ^ rotr4(A, 22);
          const T2 = sigma0 + Maj4(A, B, C) | 0;
          H = G;
          G = F;
          F = E;
          E = D2 + T1 | 0;
          D2 = C;
          C = B;
          B = A;
          A = T1 + T2 | 0;
        }
        A = A + this.A | 0;
        B = B + this.B | 0;
        C = C + this.C | 0;
        D2 = D2 + this.D | 0;
        E = E + this.E | 0;
        F = F + this.F | 0;
        G = G + this.G | 0;
        H = H + this.H | 0;
        this.set(A, B, C, D2, E, F, G, H);
      }
      roundClean() {
        clean4(SHA256_W4);
      }
      destroy() {
        this.destroyed = true;
        this.set(0, 0, 0, 0, 0, 0, 0, 0);
        clean4(this.buffer);
      }
    };
    _SHA256 = class extends SHA2_32B {
      // We cannot use array here since array allows indexing by variable
      // which means optimizer/compiler cannot use registers.
      A = SHA256_IV4[0] | 0;
      B = SHA256_IV4[1] | 0;
      C = SHA256_IV4[2] | 0;
      D = SHA256_IV4[3] | 0;
      E = SHA256_IV4[4] | 0;
      F = SHA256_IV4[5] | 0;
      G = SHA256_IV4[6] | 0;
      H = SHA256_IV4[7] | 0;
      constructor() {
        super(32);
      }
    };
    K5122 = /* @__PURE__ */ (() => split4([
      "0x428a2f98d728ae22",
      "0x7137449123ef65cd",
      "0xb5c0fbcfec4d3b2f",
      "0xe9b5dba58189dbbc",
      "0x3956c25bf348b538",
      "0x59f111f1b605d019",
      "0x923f82a4af194f9b",
      "0xab1c5ed5da6d8118",
      "0xd807aa98a3030242",
      "0x12835b0145706fbe",
      "0x243185be4ee4b28c",
      "0x550c7dc3d5ffb4e2",
      "0x72be5d74f27b896f",
      "0x80deb1fe3b1696b1",
      "0x9bdc06a725c71235",
      "0xc19bf174cf692694",
      "0xe49b69c19ef14ad2",
      "0xefbe4786384f25e3",
      "0x0fc19dc68b8cd5b5",
      "0x240ca1cc77ac9c65",
      "0x2de92c6f592b0275",
      "0x4a7484aa6ea6e483",
      "0x5cb0a9dcbd41fbd4",
      "0x76f988da831153b5",
      "0x983e5152ee66dfab",
      "0xa831c66d2db43210",
      "0xb00327c898fb213f",
      "0xbf597fc7beef0ee4",
      "0xc6e00bf33da88fc2",
      "0xd5a79147930aa725",
      "0x06ca6351e003826f",
      "0x142929670a0e6e70",
      "0x27b70a8546d22ffc",
      "0x2e1b21385c26c926",
      "0x4d2c6dfc5ac42aed",
      "0x53380d139d95b3df",
      "0x650a73548baf63de",
      "0x766a0abb3c77b2a8",
      "0x81c2c92e47edaee6",
      "0x92722c851482353b",
      "0xa2bfe8a14cf10364",
      "0xa81a664bbc423001",
      "0xc24b8b70d0f89791",
      "0xc76c51a30654be30",
      "0xd192e819d6ef5218",
      "0xd69906245565a910",
      "0xf40e35855771202a",
      "0x106aa07032bbd1b8",
      "0x19a4c116b8d2d0c8",
      "0x1e376c085141ab53",
      "0x2748774cdf8eeb99",
      "0x34b0bcb5e19b48a8",
      "0x391c0cb3c5c95a63",
      "0x4ed8aa4ae3418acb",
      "0x5b9cca4f7763e373",
      "0x682e6ff3d6b2b8a3",
      "0x748f82ee5defb2fc",
      "0x78a5636f43172f60",
      "0x84c87814a1f0ab72",
      "0x8cc702081a6439ec",
      "0x90befffa23631e28",
      "0xa4506cebde82bde9",
      "0xbef9a3f7b2c67915",
      "0xc67178f2e372532b",
      "0xca273eceea26619c",
      "0xd186b8c721c0c207",
      "0xeada7dd6cde0eb1e",
      "0xf57d4f7fee6ed178",
      "0x06f067aa72176fba",
      "0x0a637dc5a2c898a6",
      "0x113f9804bef90dae",
      "0x1b710b35131c471b",
      "0x28db77f523047d84",
      "0x32caab7b40c72493",
      "0x3c9ebe0a15c9bebc",
      "0x431d67c49c100d4c",
      "0x4cc5d4becb3e42b6",
      "0x597f299cfc657e2a",
      "0x5fcb6fab3ad6faec",
      "0x6c44198c4a475817"
    ].map((n) => BigInt(n))))();
    SHA512_Kh2 = /* @__PURE__ */ (() => K5122[0])();
    SHA512_Kl2 = /* @__PURE__ */ (() => K5122[1])();
    SHA512_W_H2 = /* @__PURE__ */ new Uint32Array(80);
    SHA512_W_L2 = /* @__PURE__ */ new Uint32Array(80);
    SHA2_64B = class extends HashMD4 {
      constructor(outputLen) {
        super(128, outputLen, 16, false);
      }
      // prettier-ignore
      get() {
        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
      }
      // prettier-ignore
      set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
        this.Ah = Ah | 0;
        this.Al = Al | 0;
        this.Bh = Bh | 0;
        this.Bl = Bl | 0;
        this.Ch = Ch | 0;
        this.Cl = Cl | 0;
        this.Dh = Dh | 0;
        this.Dl = Dl | 0;
        this.Eh = Eh | 0;
        this.El = El | 0;
        this.Fh = Fh | 0;
        this.Fl = Fl | 0;
        this.Gh = Gh | 0;
        this.Gl = Gl | 0;
        this.Hh = Hh | 0;
        this.Hl = Hl | 0;
      }
      process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4) {
          SHA512_W_H2[i] = view.getUint32(offset);
          SHA512_W_L2[i] = view.getUint32(offset += 4);
        }
        for (let i = 16; i < 80; i++) {
          const W15h = SHA512_W_H2[i - 15] | 0;
          const W15l = SHA512_W_L2[i - 15] | 0;
          const s0h = rotrSH2(W15h, W15l, 1) ^ rotrSH2(W15h, W15l, 8) ^ shrSH2(W15h, W15l, 7);
          const s0l = rotrSL2(W15h, W15l, 1) ^ rotrSL2(W15h, W15l, 8) ^ shrSL2(W15h, W15l, 7);
          const W2h = SHA512_W_H2[i - 2] | 0;
          const W2l = SHA512_W_L2[i - 2] | 0;
          const s1h = rotrSH2(W2h, W2l, 19) ^ rotrBH2(W2h, W2l, 61) ^ shrSH2(W2h, W2l, 6);
          const s1l = rotrSL2(W2h, W2l, 19) ^ rotrBL2(W2h, W2l, 61) ^ shrSL2(W2h, W2l, 6);
          const SUMl = add4L2(s0l, s1l, SHA512_W_L2[i - 7], SHA512_W_L2[i - 16]);
          const SUMh = add4H2(SUMl, s0h, s1h, SHA512_W_H2[i - 7], SHA512_W_H2[i - 16]);
          SHA512_W_H2[i] = SUMh | 0;
          SHA512_W_L2[i] = SUMl | 0;
        }
        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
        for (let i = 0; i < 80; i++) {
          const sigma1h = rotrSH2(Eh, El, 14) ^ rotrSH2(Eh, El, 18) ^ rotrBH2(Eh, El, 41);
          const sigma1l = rotrSL2(Eh, El, 14) ^ rotrSL2(Eh, El, 18) ^ rotrBL2(Eh, El, 41);
          const CHIh = Eh & Fh ^ ~Eh & Gh;
          const CHIl = El & Fl ^ ~El & Gl;
          const T1ll = add5L2(Hl, sigma1l, CHIl, SHA512_Kl2[i], SHA512_W_L2[i]);
          const T1h = add5H2(T1ll, Hh, sigma1h, CHIh, SHA512_Kh2[i], SHA512_W_H2[i]);
          const T1l = T1ll | 0;
          const sigma0h = rotrSH2(Ah, Al, 28) ^ rotrBH2(Ah, Al, 34) ^ rotrBH2(Ah, Al, 39);
          const sigma0l = rotrSL2(Ah, Al, 28) ^ rotrBL2(Ah, Al, 34) ^ rotrBL2(Ah, Al, 39);
          const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
          const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
          Hh = Gh | 0;
          Hl = Gl | 0;
          Gh = Fh | 0;
          Gl = Fl | 0;
          Fh = Eh | 0;
          Fl = El | 0;
          ({ h: Eh, l: El } = add2(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
          Dh = Ch | 0;
          Dl = Cl | 0;
          Ch = Bh | 0;
          Cl = Bl | 0;
          Bh = Ah | 0;
          Bl = Al | 0;
          const All = add3L2(T1l, sigma0l, MAJl);
          Ah = add3H2(All, T1h, sigma0h, MAJh);
          Al = All | 0;
        }
        ({ h: Ah, l: Al } = add2(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
        ({ h: Bh, l: Bl } = add2(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
        ({ h: Ch, l: Cl } = add2(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
        ({ h: Dh, l: Dl } = add2(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
        ({ h: Eh, l: El } = add2(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
        ({ h: Fh, l: Fl } = add2(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
        ({ h: Gh, l: Gl } = add2(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
        ({ h: Hh, l: Hl } = add2(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
      }
      roundClean() {
        clean4(SHA512_W_H2, SHA512_W_L2);
      }
      destroy() {
        this.destroyed = true;
        clean4(this.buffer);
        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
      }
    };
    _SHA512 = class extends SHA2_64B {
      Ah = SHA512_IV4[0] | 0;
      Al = SHA512_IV4[1] | 0;
      Bh = SHA512_IV4[2] | 0;
      Bl = SHA512_IV4[3] | 0;
      Ch = SHA512_IV4[4] | 0;
      Cl = SHA512_IV4[5] | 0;
      Dh = SHA512_IV4[6] | 0;
      Dl = SHA512_IV4[7] | 0;
      Eh = SHA512_IV4[8] | 0;
      El = SHA512_IV4[9] | 0;
      Fh = SHA512_IV4[10] | 0;
      Fl = SHA512_IV4[11] | 0;
      Gh = SHA512_IV4[12] | 0;
      Gl = SHA512_IV4[13] | 0;
      Hh = SHA512_IV4[14] | 0;
      Hl = SHA512_IV4[15] | 0;
      constructor() {
        super(64);
      }
    };
    sha2566 = /* @__PURE__ */ createHasher5(
      () => new _SHA256(),
      /* @__PURE__ */ oidNist(1)
    );
    sha5122 = /* @__PURE__ */ createHasher5(
      () => new _SHA512(),
      /* @__PURE__ */ oidNist(3)
    );
  }
});

// node_modules/@noble/curves/utils.js
function abool3(value, title = "") {
  if (typeof value !== "boolean") {
    const prefix = title && `"${title}" `;
    throw new TypeError(prefix + "expected boolean, got type=" + typeof value);
  }
  return value;
}
function abignumber(n) {
  if (typeof n === "bigint") {
    if (!isPosBig3(n))
      throw new RangeError("positive bigint expected, got " + n);
  } else
    anumber6(n);
  return n;
}
function asafenumber(value, title = "") {
  if (typeof value !== "number") {
    const prefix = title && `"${title}" `;
    throw new TypeError(prefix + "expected number, got type=" + typeof value);
  }
  if (!Number.isSafeInteger(value)) {
    const prefix = title && `"${title}" `;
    throw new RangeError(prefix + "expected safe integer, got " + value);
  }
}
function numberToHexUnpadded3(num2) {
  const hex = abignumber(num2).toString(16);
  return hex.length & 1 ? "0" + hex : hex;
}
function hexToNumber4(hex) {
  if (typeof hex !== "string")
    throw new TypeError("hex string expected, got " + typeof hex);
  return hex === "" ? _0n13 : BigInt("0x" + hex);
}
function bytesToNumberBE3(bytes) {
  return hexToNumber4(bytesToHex4(bytes));
}
function bytesToNumberLE3(bytes) {
  return hexToNumber4(bytesToHex4(copyBytes(abytes6(bytes)).reverse()));
}
function numberToBytesBE3(n, len) {
  anumber5(len);
  if (len === 0)
    throw new RangeError("zero length");
  n = abignumber(n);
  const hex = n.toString(16);
  if (hex.length > len * 2)
    throw new RangeError("number too large");
  return hexToBytes4(hex.padStart(len * 2, "0"));
}
function numberToBytesLE3(n, len) {
  return numberToBytesBE3(n, len).reverse();
}
function copyBytes(bytes) {
  return Uint8Array.from(abytes7(bytes));
}
function inRange3(n, min, max) {
  return isPosBig3(n) && isPosBig3(min) && isPosBig3(max) && min <= n && n < max;
}
function aInRange3(title, n, min, max) {
  if (!inRange3(n, min, max))
    throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
}
function bitLen3(n) {
  if (n < _0n13)
    throw new Error("expected non-negative bigint, got " + n);
  let len;
  for (len = 0; n > _0n13; n >>= _1n13, len += 1)
    ;
  return len;
}
function createHmacDrbg3(hashLen, qByteLen, hmacFn) {
  anumber5(hashLen, "hashLen");
  anumber5(qByteLen, "qByteLen");
  if (typeof hmacFn !== "function")
    throw new TypeError("hmacFn must be a function");
  const u8n3 = (len) => new Uint8Array(len);
  const NULL = Uint8Array.of();
  const byte0 = Uint8Array.of(0);
  const byte1 = Uint8Array.of(1);
  const _maxDrbgIters = 1e3;
  let v = u8n3(hashLen);
  let k = u8n3(hashLen);
  let i = 0;
  const reset = () => {
    v.fill(1);
    k.fill(0);
    i = 0;
  };
  const h = (...msgs) => hmacFn(k, concatBytes7(v, ...msgs));
  const reseed = (seed = NULL) => {
    k = h(byte0, seed);
    v = h();
    if (seed.length === 0)
      return;
    k = h(byte1, seed);
    v = h();
  };
  const gen3 = () => {
    if (i++ >= _maxDrbgIters)
      throw new Error("drbg: tried max amount of iterations");
    let len = 0;
    const out = [];
    while (len < qByteLen) {
      v = h();
      const sl = v.slice();
      out.push(sl);
      len += v.length;
    }
    return concatBytes7(...out);
  };
  const genUntil = (seed, pred) => {
    reset();
    reseed(seed);
    let res = void 0;
    while ((res = pred(gen3())) === void 0)
      reseed();
    reset();
    return res;
  };
  return genUntil;
}
function validateObject3(object, fields = {}, optFields = {}) {
  if (Object.prototype.toString.call(object) !== "[object Object]")
    throw new TypeError("expected valid options object");
  function checkField(fieldName, expectedType, isOpt) {
    if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName))
      throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
    const val = object[fieldName];
    if (isOpt && val === void 0)
      return;
    const current = typeof val;
    if (current !== expectedType || val === null)
      throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
  }
  const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
  iter(fields, false);
  iter(optFields, true);
}
var abytes7, anumber6, bytesToHex5, concatBytes7, hexToBytes5, isBytes8, randomBytes5, _0n13, _1n13, isPosBig3, bitMask3;
var init_utils11 = __esm({
  "node_modules/@noble/curves/utils.js"() {
    "use strict";
    init_utils10();
    abytes7 = (value, length, title) => abytes6(value, length, title);
    anumber6 = anumber5;
    bytesToHex5 = bytesToHex4;
    concatBytes7 = (...arrays) => concatBytes6(...arrays);
    hexToBytes5 = (hex) => hexToBytes4(hex);
    isBytes8 = isBytes7;
    randomBytes5 = (bytesLength) => randomBytes4(bytesLength);
    _0n13 = /* @__PURE__ */ BigInt(0);
    _1n13 = /* @__PURE__ */ BigInt(1);
    isPosBig3 = (n) => typeof n === "bigint" && _0n13 <= n;
    bitMask3 = (n) => (_1n13 << BigInt(n)) - _1n13;
  }
});

// node_modules/@noble/curves/abstract/modular.js
function mod3(a, b) {
  if (b <= _0n14)
    throw new Error("mod: expected positive modulus, got " + b);
  const result = a % b;
  return result >= _0n14 ? result : b + result;
}
function pow23(x, power, modulo2) {
  if (power < _0n14)
    throw new Error("pow2: expected non-negative exponent, got " + power);
  let res = x;
  while (power-- > _0n14) {
    res *= res;
    res %= modulo2;
  }
  return res;
}
function invert3(number, modulo2) {
  if (number === _0n14)
    throw new Error("invert: expected non-zero number");
  if (modulo2 <= _0n14)
    throw new Error("invert: expected positive modulus, got " + modulo2);
  let a = mod3(number, modulo2);
  let b = modulo2;
  let x = _0n14, y = _1n14, u = _1n14, v = _0n14;
  while (a !== _0n14) {
    const q = b / a;
    const r = b - a * q;
    const m = x - u * q;
    const n = y - v * q;
    b = a, a = r, x = u, y = v, u = m, v = n;
  }
  const gcd2 = b;
  if (gcd2 !== _1n14)
    throw new Error("invert: does not exist");
  return mod3(x, modulo2);
}
function assertIsSquare(Fp, root, n) {
  const F = Fp;
  if (!F.eql(F.sqr(root), n))
    throw new Error("Cannot find square root");
}
function sqrt3mod43(Fp, n) {
  const F = Fp;
  const p1div4 = (F.ORDER + _1n14) / _4n5;
  const root = F.pow(n, p1div4);
  assertIsSquare(F, root, n);
  return root;
}
function sqrt5mod83(Fp, n) {
  const F = Fp;
  const p5div8 = (F.ORDER - _5n3) / _8n3;
  const n2 = F.mul(n, _2n9);
  const v = F.pow(n2, p5div8);
  const nv = F.mul(n, v);
  const i = F.mul(F.mul(nv, _2n9), v);
  const root = F.mul(nv, F.sub(i, F.ONE));
  assertIsSquare(F, root, n);
  return root;
}
function sqrt9mod16(P2) {
  const Fp_ = Field3(P2);
  const tn = tonelliShanks3(P2);
  const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
  const c2 = tn(Fp_, c1);
  const c3 = tn(Fp_, Fp_.neg(c1));
  const c4 = (P2 + _7n3) / _16n;
  return ((Fp, n) => {
    const F = Fp;
    let tv1 = F.pow(n, c4);
    let tv2 = F.mul(tv1, c1);
    const tv3 = F.mul(tv1, c2);
    const tv4 = F.mul(tv1, c3);
    const e1 = F.eql(F.sqr(tv2), n);
    const e22 = F.eql(F.sqr(tv3), n);
    tv1 = F.cmov(tv1, tv2, e1);
    tv2 = F.cmov(tv4, tv3, e22);
    const e32 = F.eql(F.sqr(tv2), n);
    const root = F.cmov(tv1, tv2, e32);
    assertIsSquare(F, root, n);
    return root;
  });
}
function tonelliShanks3(P2) {
  if (P2 < _3n5)
    throw new Error("sqrt is not defined for small field");
  let Q = P2 - _1n14;
  let S = 0;
  while (Q % _2n9 === _0n14) {
    Q /= _2n9;
    S++;
  }
  let Z = _2n9;
  const _Fp = Field3(P2);
  while (FpLegendre3(_Fp, Z) === 1) {
    if (Z++ > 1e3)
      throw new Error("Cannot find square root: probably non-prime P");
  }
  if (S === 1)
    return sqrt3mod43;
  let cc = _Fp.pow(Z, Q);
  const Q1div2 = (Q + _1n14) / _2n9;
  return function tonelliSlow(Fp, n) {
    const F = Fp;
    if (F.is0(n))
      return n;
    if (FpLegendre3(F, n) !== 1)
      throw new Error("Cannot find square root");
    let M = S;
    let c = F.mul(F.ONE, cc);
    let t = F.pow(n, Q);
    let R = F.pow(n, Q1div2);
    while (!F.eql(t, F.ONE)) {
      if (F.is0(t))
        return F.ZERO;
      let i = 1;
      let t_tmp = F.sqr(t);
      while (!F.eql(t_tmp, F.ONE)) {
        i++;
        t_tmp = F.sqr(t_tmp);
        if (i === M)
          throw new Error("Cannot find square root");
      }
      const exponent = _1n14 << BigInt(M - i - 1);
      const b = F.pow(c, exponent);
      M = i;
      c = F.sqr(b);
      t = F.mul(t, c);
      R = F.mul(R, b);
    }
    return R;
  };
}
function FpSqrt3(P2) {
  if (P2 % _4n5 === _3n5)
    return sqrt3mod43;
  if (P2 % _8n3 === _5n3)
    return sqrt5mod83;
  if (P2 % _16n === _9n)
    return sqrt9mod16(P2);
  return tonelliShanks3(P2);
}
function validateField3(field) {
  const initial = {
    ORDER: "bigint",
    BYTES: "number",
    BITS: "number"
  };
  const opts = FIELD_FIELDS3.reduce((map, val) => {
    map[val] = "function";
    return map;
  }, initial);
  validateObject3(field, opts);
  asafenumber(field.BYTES, "BYTES");
  asafenumber(field.BITS, "BITS");
  if (field.BYTES < 1 || field.BITS < 1)
    throw new Error("invalid field: expected BYTES/BITS > 0");
  if (field.ORDER <= _1n14)
    throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
  return field;
}
function FpPow3(Fp, num2, power) {
  const F = Fp;
  if (power < _0n14)
    throw new Error("invalid exponent, negatives unsupported");
  if (power === _0n14)
    return F.ONE;
  if (power === _1n14)
    return num2;
  let p = F.ONE;
  let d = num2;
  while (power > _0n14) {
    if (power & _1n14)
      p = F.mul(p, d);
    d = F.sqr(d);
    power >>= _1n14;
  }
  return p;
}
function FpInvertBatch3(Fp, nums, passZero = false) {
  const F = Fp;
  const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
  const multipliedAcc = nums.reduce((acc, num2, i) => {
    if (F.is0(num2))
      return acc;
    inverted[i] = acc;
    return F.mul(acc, num2);
  }, F.ONE);
  const invertedAcc = F.inv(multipliedAcc);
  nums.reduceRight((acc, num2, i) => {
    if (F.is0(num2))
      return acc;
    inverted[i] = F.mul(acc, inverted[i]);
    return F.mul(acc, num2);
  }, invertedAcc);
  return inverted;
}
function FpLegendre3(Fp, n) {
  const F = Fp;
  const p1mod2 = (F.ORDER - _1n14) / _2n9;
  const powered = F.pow(n, p1mod2);
  const yes = F.eql(powered, F.ONE);
  const zero = F.eql(powered, F.ZERO);
  const no = F.eql(powered, F.neg(F.ONE));
  if (!yes && !zero && !no)
    throw new Error("invalid Legendre symbol result");
  return yes ? 1 : zero ? 0 : -1;
}
function nLength3(n, nBitLength) {
  if (nBitLength !== void 0)
    anumber6(nBitLength);
  if (n <= _0n14)
    throw new Error("invalid n length: expected positive n, got " + n);
  if (nBitLength !== void 0 && nBitLength < 1)
    throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
  const bits = bitLen3(n);
  if (nBitLength !== void 0 && nBitLength < bits)
    throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
  const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
  const nByteLength = Math.ceil(_nBitLength / 8);
  return { nBitLength: _nBitLength, nByteLength };
}
function Field3(ORDER, opts = {}) {
  return new _Field(ORDER, opts);
}
function getFieldBytesLength3(fieldOrder) {
  if (typeof fieldOrder !== "bigint")
    throw new Error("field order must be bigint");
  if (fieldOrder <= _1n14)
    throw new Error("field order must be greater than 1");
  const bitLength = bitLen3(fieldOrder - _1n14);
  return Math.ceil(bitLength / 8);
}
function getMinHashLength3(fieldOrder) {
  const length = getFieldBytesLength3(fieldOrder);
  return length + Math.ceil(length / 2);
}
function mapHashToField3(key, fieldOrder, isLE3 = false) {
  abytes7(key);
  const len = key.length;
  const fieldLen = getFieldBytesLength3(fieldOrder);
  const minLen = Math.max(getMinHashLength3(fieldOrder), 16);
  if (len < minLen || len > 1024)
    throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
  const num2 = isLE3 ? bytesToNumberLE3(key) : bytesToNumberBE3(key);
  const reduced = mod3(num2, fieldOrder - _1n14) + _1n14;
  return isLE3 ? numberToBytesLE3(reduced, fieldLen) : numberToBytesBE3(reduced, fieldLen);
}
var _0n14, _1n14, _2n9, _3n5, _4n5, _5n3, _7n3, _8n3, _9n, _16n, FIELD_FIELDS3, FIELD_SQRT, _Field;
var init_modular3 = __esm({
  "node_modules/@noble/curves/abstract/modular.js"() {
    "use strict";
    init_utils11();
    _0n14 = /* @__PURE__ */ BigInt(0);
    _1n14 = /* @__PURE__ */ BigInt(1);
    _2n9 = /* @__PURE__ */ BigInt(2);
    _3n5 = /* @__PURE__ */ BigInt(3);
    _4n5 = /* @__PURE__ */ BigInt(4);
    _5n3 = /* @__PURE__ */ BigInt(5);
    _7n3 = /* @__PURE__ */ BigInt(7);
    _8n3 = /* @__PURE__ */ BigInt(8);
    _9n = /* @__PURE__ */ BigInt(9);
    _16n = /* @__PURE__ */ BigInt(16);
    FIELD_FIELDS3 = [
      "create",
      "isValid",
      "is0",
      "neg",
      "inv",
      "sqrt",
      "sqr",
      "eql",
      "add",
      "sub",
      "mul",
      "pow",
      "div",
      "addN",
      "subN",
      "mulN",
      "sqrN"
    ];
    FIELD_SQRT = /* @__PURE__ */ new WeakMap();
    _Field = class {
      ORDER;
      BITS;
      BYTES;
      isLE;
      ZERO = _0n14;
      ONE = _1n14;
      _lengths;
      _mod;
      constructor(ORDER, opts = {}) {
        if (ORDER <= _1n14)
          throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
        let _nbitLength = void 0;
        this.isLE = false;
        if (opts != null && typeof opts === "object") {
          if (typeof opts.BITS === "number")
            _nbitLength = opts.BITS;
          if (typeof opts.sqrt === "function")
            Object.defineProperty(this, "sqrt", { value: opts.sqrt, enumerable: true });
          if (typeof opts.isLE === "boolean")
            this.isLE = opts.isLE;
          if (opts.allowedLengths)
            this._lengths = Object.freeze(opts.allowedLengths.slice());
          if (typeof opts.modFromBytes === "boolean")
            this._mod = opts.modFromBytes;
        }
        const { nBitLength, nByteLength } = nLength3(ORDER, _nbitLength);
        if (nByteLength > 2048)
          throw new Error("invalid field: expected ORDER of <= 2048 bytes");
        this.ORDER = ORDER;
        this.BITS = nBitLength;
        this.BYTES = nByteLength;
        Object.freeze(this);
      }
      create(num2) {
        return mod3(num2, this.ORDER);
      }
      isValid(num2) {
        if (typeof num2 !== "bigint")
          throw new TypeError("invalid field element: expected bigint, got " + typeof num2);
        return _0n14 <= num2 && num2 < this.ORDER;
      }
      is0(num2) {
        return num2 === _0n14;
      }
      // is valid and invertible
      isValidNot0(num2) {
        return !this.is0(num2) && this.isValid(num2);
      }
      isOdd(num2) {
        return (num2 & _1n14) === _1n14;
      }
      neg(num2) {
        return mod3(-num2, this.ORDER);
      }
      eql(lhs, rhs) {
        return lhs === rhs;
      }
      sqr(num2) {
        return mod3(num2 * num2, this.ORDER);
      }
      add(lhs, rhs) {
        return mod3(lhs + rhs, this.ORDER);
      }
      sub(lhs, rhs) {
        return mod3(lhs - rhs, this.ORDER);
      }
      mul(lhs, rhs) {
        return mod3(lhs * rhs, this.ORDER);
      }
      pow(num2, power) {
        return FpPow3(this, num2, power);
      }
      div(lhs, rhs) {
        return mod3(lhs * invert3(rhs, this.ORDER), this.ORDER);
      }
      // Same as above, but doesn't normalize
      sqrN(num2) {
        return num2 * num2;
      }
      addN(lhs, rhs) {
        return lhs + rhs;
      }
      subN(lhs, rhs) {
        return lhs - rhs;
      }
      mulN(lhs, rhs) {
        return lhs * rhs;
      }
      inv(num2) {
        return invert3(num2, this.ORDER);
      }
      sqrt(num2) {
        let sqrt = FIELD_SQRT.get(this);
        if (!sqrt)
          FIELD_SQRT.set(this, sqrt = FpSqrt3(this.ORDER));
        return sqrt(this, num2);
      }
      toBytes(num2) {
        return this.isLE ? numberToBytesLE3(num2, this.BYTES) : numberToBytesBE3(num2, this.BYTES);
      }
      fromBytes(bytes, skipValidation = false) {
        abytes7(bytes);
        const { _lengths: allowedLengths, BYTES, isLE: isLE3, ORDER, _mod: modFromBytes } = this;
        if (allowedLengths) {
          if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
            throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
          }
          const padded = new Uint8Array(BYTES);
          padded.set(bytes, isLE3 ? 0 : padded.length - bytes.length);
          bytes = padded;
        }
        if (bytes.length !== BYTES)
          throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
        let scalar = isLE3 ? bytesToNumberLE3(bytes) : bytesToNumberBE3(bytes);
        if (modFromBytes)
          scalar = mod3(scalar, ORDER);
        if (!skipValidation) {
          if (!this.isValid(scalar))
            throw new Error("invalid field element: outside of range 0..ORDER");
        }
        return scalar;
      }
      // TODO: we don't need it here, move out to separate fn
      invertBatch(lst) {
        return FpInvertBatch3(this, lst);
      }
      // We can't move this out because Fp6, Fp12 implement it
      // and it's unclear what to return in there.
      cmov(a, b, condition) {
        abool3(condition, "condition");
        return condition ? b : a;
      }
    };
    Object.freeze(_Field.prototype);
  }
});

// node_modules/@noble/curves/abstract/curve.js
function negateCt(condition, item) {
  const neg = item.negate();
  return condition ? neg : item;
}
function normalizeZ(c, points) {
  const invertedZs = FpInvertBatch3(c.Fp, points.map((p) => p.Z));
  return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
}
function validateW3(W, bits) {
  if (!Number.isSafeInteger(W) || W <= 0 || W > bits)
    throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
}
function calcWOpts3(W, scalarBits) {
  validateW3(W, scalarBits);
  const windows = Math.ceil(scalarBits / W) + 1;
  const windowSize = 2 ** (W - 1);
  const maxNumber = 2 ** W;
  const mask = bitMask3(W);
  const shiftBy = BigInt(W);
  return { windows, windowSize, mask, maxNumber, shiftBy };
}
function calcOffsets3(n, window, wOpts) {
  const { windowSize, mask, maxNumber, shiftBy } = wOpts;
  let wbits = Number(n & mask);
  let nextN = n >> shiftBy;
  if (wbits > windowSize) {
    wbits -= maxNumber;
    nextN += _1n15;
  }
  const offsetStart = window * windowSize;
  const offset = offsetStart + Math.abs(wbits) - 1;
  const isZero = wbits === 0;
  const isNeg = wbits < 0;
  const isNegF = window % 2 !== 0;
  const offsetF = offsetStart;
  return { nextN, offset, isZero, isNeg, isNegF, offsetF };
}
function getW3(P2) {
  return pointWindowSizes3.get(P2) || 1;
}
function assert0(n) {
  if (n !== _0n15)
    throw new Error("invalid wNAF");
}
function mulEndoUnsafe(Point3, point, k1, k2) {
  let acc = point;
  let p1 = Point3.ZERO;
  let p2 = Point3.ZERO;
  while (k1 > _0n15 || k2 > _0n15) {
    if (k1 & _1n15)
      p1 = p1.add(acc);
    if (k2 & _1n15)
      p2 = p2.add(acc);
    acc = acc.double();
    k1 >>= _1n15;
    k2 >>= _1n15;
  }
  return { p1, p2 };
}
function createField(order, field, isLE3) {
  if (field) {
    if (field.ORDER !== order)
      throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
    validateField3(field);
    return field;
  } else {
    return Field3(order, { isLE: isLE3 });
  }
}
function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
  if (FpFnLE === void 0)
    FpFnLE = type === "edwards";
  if (!CURVE || typeof CURVE !== "object")
    throw new Error(`expected valid ${type} CURVE object`);
  for (const p of ["p", "n", "h"]) {
    const val = CURVE[p];
    if (!(typeof val === "bigint" && val > _0n15))
      throw new Error(`CURVE.${p} must be positive bigint`);
  }
  const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
  const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE);
  const _b = type === "weierstrass" ? "b" : "d";
  const params = ["Gx", "Gy", "a", _b];
  for (const p of params) {
    if (!Fp.isValid(CURVE[p]))
      throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
  }
  CURVE = Object.freeze(Object.assign({}, CURVE));
  return { CURVE, Fp, Fn: Fn2 };
}
function createKeygen(randomSecretKey, getPublicKey) {
  return function keygen(seed) {
    const secretKey = randomSecretKey(seed);
    return { secretKey, publicKey: getPublicKey(secretKey) };
  };
}
var _0n15, _1n15, pointPrecomputes3, pointWindowSizes3, wNAF3;
var init_curve3 = __esm({
  "node_modules/@noble/curves/abstract/curve.js"() {
    "use strict";
    init_utils11();
    init_modular3();
    _0n15 = /* @__PURE__ */ BigInt(0);
    _1n15 = /* @__PURE__ */ BigInt(1);
    pointPrecomputes3 = /* @__PURE__ */ new WeakMap();
    pointWindowSizes3 = /* @__PURE__ */ new WeakMap();
    wNAF3 = class {
      BASE;
      ZERO;
      Fn;
      bits;
      // Parametrized with a given Point class (not individual point)
      constructor(Point3, bits) {
        this.BASE = Point3.BASE;
        this.ZERO = Point3.ZERO;
        this.Fn = Point3.Fn;
        this.bits = bits;
      }
      // non-const time multiplication ladder
      _unsafeLadder(elm, n, p = this.ZERO) {
        let d = elm;
        while (n > _0n15) {
          if (n & _1n15)
            p = p.add(d);
          d = d.double();
          n >>= _1n15;
        }
        return p;
      }
      /**
       * Creates a wNAF precomputation window. Used for caching.
       * Default window size is set by `utils.precompute()` and is equal to 8.
       * Number of precomputed points depends on the curve size:
       * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
       * - 𝑊 is the window size
       * - 𝑛 is the bitlength of the curve order.
       * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
       * @param point - Point instance
       * @param W - window size
       * @returns precomputed point tables flattened to a single array
       */
      precomputeWindow(point, W) {
        const { windows, windowSize } = calcWOpts3(W, this.bits);
        const points = [];
        let p = point;
        let base2 = p;
        for (let window = 0; window < windows; window++) {
          base2 = p;
          points.push(base2);
          for (let i = 1; i < windowSize; i++) {
            base2 = base2.add(p);
            points.push(base2);
          }
          p = base2.double();
        }
        return points;
      }
      /**
       * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
       * More compact implementation:
       * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
       * @returns real and fake (for const-time) points
       */
      wNAF(W, precomputes, n) {
        if (!this.Fn.isValid(n))
          throw new Error("invalid scalar");
        let p = this.ZERO;
        let f = this.BASE;
        const wo = calcWOpts3(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
          const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets3(n, window, wo);
          n = nextN;
          if (isZero) {
            f = f.add(negateCt(isNegF, precomputes[offsetF]));
          } else {
            p = p.add(negateCt(isNeg, precomputes[offset]));
          }
        }
        assert0(n);
        return { p, f };
      }
      /**
       * Implements unsafe EC multiplication using precomputed tables
       * and w-ary non-adjacent form.
       * @param acc - accumulator point to add result of multiplication
       * @returns point
       */
      wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
        const wo = calcWOpts3(W, this.bits);
        for (let window = 0; window < wo.windows; window++) {
          if (n === _0n15)
            break;
          const { nextN, offset, isZero, isNeg } = calcOffsets3(n, window, wo);
          n = nextN;
          if (isZero) {
            continue;
          } else {
            const item = precomputes[offset];
            acc = acc.add(isNeg ? item.negate() : item);
          }
        }
        assert0(n);
        return acc;
      }
      getPrecomputes(W, point, transform2) {
        let comp = pointPrecomputes3.get(point);
        if (!comp) {
          comp = this.precomputeWindow(point, W);
          if (W !== 1) {
            if (typeof transform2 === "function")
              comp = transform2(comp);
            pointPrecomputes3.set(point, comp);
          }
        }
        return comp;
      }
      cached(point, scalar, transform2) {
        const W = getW3(point);
        return this.wNAF(W, this.getPrecomputes(W, point, transform2), scalar);
      }
      unsafe(point, scalar, transform2, prev) {
        const W = getW3(point);
        if (W === 1)
          return this._unsafeLadder(point, scalar, prev);
        return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform2), scalar, prev);
      }
      // We calculate precomputes for elliptic curve point multiplication
      // using windowed method. This specifies window size and
      // stores precomputed values. Usually only base point would be precomputed.
      createCache(P2, W) {
        validateW3(W, this.bits);
        pointWindowSizes3.set(P2, W);
        pointPrecomputes3.delete(P2);
      }
      hasCache(elm) {
        return getW3(elm) !== 1;
      }
    };
  }
});

// node_modules/@noble/hashes/hmac.js
var _HMAC, hmac4;
var init_hmac4 = __esm({
  "node_modules/@noble/hashes/hmac.js"() {
    "use strict";
    init_utils10();
    _HMAC = class {
      oHash;
      iHash;
      blockLen;
      outputLen;
      canXOF = false;
      finished = false;
      destroyed = false;
      constructor(hash3, key) {
        ahash4(hash3);
        abytes6(key, void 0, "key");
        this.iHash = hash3.create();
        if (typeof this.iHash.update !== "function")
          throw new Error("Expected instance of class which extends utils.Hash");
        this.blockLen = this.iHash.blockLen;
        this.outputLen = this.iHash.outputLen;
        const blockLen = this.blockLen;
        const pad4 = new Uint8Array(blockLen);
        pad4.set(key.length > blockLen ? hash3.create().update(key).digest() : key);
        for (let i = 0; i < pad4.length; i++)
          pad4[i] ^= 54;
        this.iHash.update(pad4);
        this.oHash = hash3.create();
        for (let i = 0; i < pad4.length; i++)
          pad4[i] ^= 54 ^ 92;
        this.oHash.update(pad4);
        clean4(pad4);
      }
      update(buf) {
        aexists4(this);
        this.iHash.update(buf);
        return this;
      }
      digestInto(out) {
        aexists4(this);
        aoutput4(out, this);
        this.finished = true;
        const buf = out.subarray(0, this.outputLen);
        this.iHash.digestInto(buf);
        this.oHash.update(buf);
        this.oHash.digestInto(buf);
        this.destroy();
      }
      digest() {
        const out = new Uint8Array(this.oHash.outputLen);
        this.digestInto(out);
        return out;
      }
      _cloneInto(to) {
        to ||= Object.create(Object.getPrototypeOf(this), {});
        const { oHash, iHash, finished: finished2, destroyed, blockLen, outputLen } = this;
        to = to;
        to.finished = finished2;
        to.destroyed = destroyed;
        to.blockLen = blockLen;
        to.outputLen = outputLen;
        to.oHash = oHash._cloneInto(to.oHash);
        to.iHash = iHash._cloneInto(to.iHash);
        return to;
      }
      clone() {
        return this._cloneInto();
      }
      destroy() {
        this.destroyed = true;
        this.oHash.destroy();
        this.iHash.destroy();
      }
    };
    hmac4 = /* @__PURE__ */ (() => {
      const hmac_ = ((hash3, key, message) => new _HMAC(hash3, key).update(message).digest());
      hmac_.create = (hash3, key) => new _HMAC(hash3, key);
      return hmac_;
    })();
  }
});

// node_modules/@noble/curves/abstract/weierstrass.js
function _splitEndoScalar(k, basis, n) {
  aInRange3("scalar", k, _0n16, n);
  const [[a1, b1], [a2, b2]] = basis;
  const c1 = divNearest3(b2 * k, n);
  const c2 = divNearest3(-b1 * k, n);
  let k1 = k - c1 * a1 - c2 * a2;
  let k2 = -c1 * b1 - c2 * b2;
  const k1neg = k1 < _0n16;
  const k2neg = k2 < _0n16;
  if (k1neg)
    k1 = -k1;
  if (k2neg)
    k2 = -k2;
  const MAX_NUM = bitMask3(Math.ceil(bitLen3(n) / 2)) + _1n16;
  if (k1 < _0n16 || k1 >= MAX_NUM || k2 < _0n16 || k2 >= MAX_NUM) {
    throw new Error("splitScalar (endomorphism): failed for k");
  }
  return { k1neg, k1, k2neg, k2 };
}
function validateSigFormat(format) {
  if (!["compact", "recovered", "der"].includes(format))
    throw new Error('Signature format must be "compact", "recovered", or "der"');
  return format;
}
function validateSigOpts(opts, def) {
  validateObject3(opts);
  const optsn = {};
  for (let optName of Object.keys(def)) {
    optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
  }
  abool3(optsn.lowS, "lowS");
  abool3(optsn.prehash, "prehash");
  if (optsn.format !== void 0)
    validateSigFormat(optsn.format);
  return optsn;
}
function weierstrass3(params, extraOpts = {}) {
  const validated = createCurveFields("weierstrass", params, extraOpts);
  const Fp = validated.Fp;
  const Fn2 = validated.Fn;
  let CURVE = validated.CURVE;
  const { h: cofactor, n: CURVE_ORDER } = CURVE;
  validateObject3(extraOpts, {}, {
    allowInfinityPoint: "boolean",
    clearCofactor: "function",
    isTorsionFree: "function",
    fromBytes: "function",
    toBytes: "function",
    endo: "object"
  });
  const { endo, allowInfinityPoint } = extraOpts;
  if (endo) {
    if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) {
      throw new Error('invalid endo: expected "beta": bigint and "basises": array');
    }
  }
  const lengths = getWLengths(Fp, Fn2);
  function assertCompressionIsSupported() {
    if (!Fp.isOdd)
      throw new Error("compression is not supported: Field does not have .isOdd()");
  }
  function pointToBytes2(_c, point, isCompressed) {
    if (allowInfinityPoint && point.is0())
      return Uint8Array.of(0);
    const { x, y } = point.toAffine();
    const bx = Fp.toBytes(x);
    abool3(isCompressed, "isCompressed");
    if (isCompressed) {
      assertCompressionIsSupported();
      const hasEvenY = !Fp.isOdd(y);
      return concatBytes7(pprefix(hasEvenY), bx);
    } else {
      return concatBytes7(Uint8Array.of(4), bx, Fp.toBytes(y));
    }
  }
  function pointFromBytes(bytes) {
    abytes7(bytes, void 0, "Point");
    const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
    const length = bytes.length;
    const head = bytes[0];
    const tail = bytes.subarray(1);
    if (allowInfinityPoint && length === 1 && head === 0)
      return { x: Fp.ZERO, y: Fp.ZERO };
    if (length === comp && (head === 2 || head === 3)) {
      const x = Fp.fromBytes(tail);
      if (!Fp.isValid(x))
        throw new Error("bad point: is not on curve, wrong x");
      const y2 = weierstrassEquation(x);
      let y;
      try {
        y = Fp.sqrt(y2);
      } catch (sqrtError) {
        const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
        throw new Error("bad point: is not on curve, sqrt error" + err);
      }
      assertCompressionIsSupported();
      const evenY = Fp.isOdd(y);
      const evenH = (head & 1) === 1;
      if (evenH !== evenY)
        y = Fp.neg(y);
      return { x, y };
    } else if (length === uncomp && head === 4) {
      const L = Fp.BYTES;
      const x = Fp.fromBytes(tail.subarray(0, L));
      const y = Fp.fromBytes(tail.subarray(L, L * 2));
      if (!isValidXY(x, y))
        throw new Error("bad point: is not on curve");
      return { x, y };
    } else {
      throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
    }
  }
  const encodePoint = extraOpts.toBytes === void 0 ? pointToBytes2 : extraOpts.toBytes;
  const decodePoint = extraOpts.fromBytes === void 0 ? pointFromBytes : extraOpts.fromBytes;
  function weierstrassEquation(x) {
    const x2 = Fp.sqr(x);
    const x3 = Fp.mul(x2, x);
    return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
  }
  function isValidXY(x, y) {
    const left = Fp.sqr(y);
    const right = weierstrassEquation(x);
    return Fp.eql(left, right);
  }
  if (!isValidXY(CURVE.Gx, CURVE.Gy))
    throw new Error("bad curve params: generator point");
  const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n6), _4n6);
  const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
  if (Fp.is0(Fp.add(_4a3, _27b2)))
    throw new Error("bad curve params: a or b");
  function acoord(title, n, banZero = false) {
    if (!Fp.isValid(n) || banZero && Fp.is0(n))
      throw new Error(`bad point coordinate ${title}`);
    return n;
  }
  function aprjpoint(other) {
    if (!(other instanceof Point3))
      throw new Error("Weierstrass Point expected");
  }
  function splitEndoScalarN(k) {
    if (!endo || !endo.basises)
      throw new Error("no endo");
    return _splitEndoScalar(k, endo.basises, Fn2.ORDER);
  }
  function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
    k2p = new Point3(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
    k1p = negateCt(k1neg, k1p);
    k2p = negateCt(k2neg, k2p);
    return k1p.add(k2p);
  }
  class Point3 {
    // base / generator point
    static BASE = new Point3(CURVE.Gx, CURVE.Gy, Fp.ONE);
    // zero / infinity / identity point
    static ZERO = new Point3(Fp.ZERO, Fp.ONE, Fp.ZERO);
    // 0, 1, 0
    // math field
    static Fp = Fp;
    // scalar field
    static Fn = Fn2;
    X;
    Y;
    Z;
    /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
    constructor(X, Y, Z) {
      this.X = acoord("x", X);
      this.Y = acoord("y", Y, true);
      this.Z = acoord("z", Z);
      Object.freeze(this);
    }
    static CURVE() {
      return CURVE;
    }
    /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
    static fromAffine(p) {
      const { x, y } = p || {};
      if (!p || !Fp.isValid(x) || !Fp.isValid(y))
        throw new Error("invalid affine point");
      if (p instanceof Point3)
        throw new Error("projective point not allowed");
      if (Fp.is0(x) && Fp.is0(y))
        return Point3.ZERO;
      return new Point3(x, y, Fp.ONE);
    }
    static fromBytes(bytes) {
      const P2 = Point3.fromAffine(decodePoint(abytes7(bytes, void 0, "point")));
      P2.assertValidity();
      return P2;
    }
    static fromHex(hex) {
      return Point3.fromBytes(hexToBytes5(hex));
    }
    get x() {
      return this.toAffine().x;
    }
    get y() {
      return this.toAffine().y;
    }
    /**
     *
     * @param windowSize
     * @param isLazy - true will defer table computation until the first multiplication
     * @returns
     */
    precompute(windowSize = 8, isLazy = true) {
      wnaf.createCache(this, windowSize);
      if (!isLazy)
        this.multiply(_3n6);
      return this;
    }
    // TODO: return `this`
    /** A point on curve is valid if it conforms to equation. */
    assertValidity() {
      const p = this;
      if (p.is0()) {
        if (extraOpts.allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))
          return;
        throw new Error("bad point: ZERO");
      }
      const { x, y } = p.toAffine();
      if (!Fp.isValid(x) || !Fp.isValid(y))
        throw new Error("bad point: x or y not field elements");
      if (!isValidXY(x, y))
        throw new Error("bad point: equation left != right");
      if (!p.isTorsionFree())
        throw new Error("bad point: not in prime-order subgroup");
    }
    hasEvenY() {
      const { y } = this.toAffine();
      if (!Fp.isOdd)
        throw new Error("Field doesn't support isOdd");
      return !Fp.isOdd(y);
    }
    /** Compare one point to another. */
    equals(other) {
      aprjpoint(other);
      const { X: X1, Y: Y1, Z: Z1 } = this;
      const { X: X2, Y: Y2, Z: Z2 } = other;
      const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
      const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
      return U1 && U2;
    }
    /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
    negate() {
      return new Point3(this.X, Fp.neg(this.Y), this.Z);
    }
    // Renes-Costello-Batina exception-free doubling formula.
    // There is 30% faster Jacobian formula, but it is not complete.
    // https://eprint.iacr.org/2015/1060, algorithm 3
    // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
    double() {
      const { a, b } = CURVE;
      const b3 = Fp.mul(b, _3n6);
      const { X: X1, Y: Y1, Z: Z1 } = this;
      let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
      let t0 = Fp.mul(X1, X1);
      let t1 = Fp.mul(Y1, Y1);
      let t2 = Fp.mul(Z1, Z1);
      let t3 = Fp.mul(X1, Y1);
      t3 = Fp.add(t3, t3);
      Z3 = Fp.mul(X1, Z1);
      Z3 = Fp.add(Z3, Z3);
      X3 = Fp.mul(a, Z3);
      Y3 = Fp.mul(b3, t2);
      Y3 = Fp.add(X3, Y3);
      X3 = Fp.sub(t1, Y3);
      Y3 = Fp.add(t1, Y3);
      Y3 = Fp.mul(X3, Y3);
      X3 = Fp.mul(t3, X3);
      Z3 = Fp.mul(b3, Z3);
      t2 = Fp.mul(a, t2);
      t3 = Fp.sub(t0, t2);
      t3 = Fp.mul(a, t3);
      t3 = Fp.add(t3, Z3);
      Z3 = Fp.add(t0, t0);
      t0 = Fp.add(Z3, t0);
      t0 = Fp.add(t0, t2);
      t0 = Fp.mul(t0, t3);
      Y3 = Fp.add(Y3, t0);
      t2 = Fp.mul(Y1, Z1);
      t2 = Fp.add(t2, t2);
      t0 = Fp.mul(t2, t3);
      X3 = Fp.sub(X3, t0);
      Z3 = Fp.mul(t2, t1);
      Z3 = Fp.add(Z3, Z3);
      Z3 = Fp.add(Z3, Z3);
      return new Point3(X3, Y3, Z3);
    }
    // Renes-Costello-Batina exception-free addition formula.
    // There is 30% faster Jacobian formula, but it is not complete.
    // https://eprint.iacr.org/2015/1060, algorithm 1
    // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
    add(other) {
      aprjpoint(other);
      const { X: X1, Y: Y1, Z: Z1 } = this;
      const { X: X2, Y: Y2, Z: Z2 } = other;
      let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
      const a = CURVE.a;
      const b3 = Fp.mul(CURVE.b, _3n6);
      let t0 = Fp.mul(X1, X2);
      let t1 = Fp.mul(Y1, Y2);
      let t2 = Fp.mul(Z1, Z2);
      let t3 = Fp.add(X1, Y1);
      let t4 = Fp.add(X2, Y2);
      t3 = Fp.mul(t3, t4);
      t4 = Fp.add(t0, t1);
      t3 = Fp.sub(t3, t4);
      t4 = Fp.add(X1, Z1);
      let t5 = Fp.add(X2, Z2);
      t4 = Fp.mul(t4, t5);
      t5 = Fp.add(t0, t2);
      t4 = Fp.sub(t4, t5);
      t5 = Fp.add(Y1, Z1);
      X3 = Fp.add(Y2, Z2);
      t5 = Fp.mul(t5, X3);
      X3 = Fp.add(t1, t2);
      t5 = Fp.sub(t5, X3);
      Z3 = Fp.mul(a, t4);
      X3 = Fp.mul(b3, t2);
      Z3 = Fp.add(X3, Z3);
      X3 = Fp.sub(t1, Z3);
      Z3 = Fp.add(t1, Z3);
      Y3 = Fp.mul(X3, Z3);
      t1 = Fp.add(t0, t0);
      t1 = Fp.add(t1, t0);
      t2 = Fp.mul(a, t2);
      t4 = Fp.mul(b3, t4);
      t1 = Fp.add(t1, t2);
      t2 = Fp.sub(t0, t2);
      t2 = Fp.mul(a, t2);
      t4 = Fp.add(t4, t2);
      t0 = Fp.mul(t1, t4);
      Y3 = Fp.add(Y3, t0);
      t0 = Fp.mul(t5, t4);
      X3 = Fp.mul(t3, X3);
      X3 = Fp.sub(X3, t0);
      t0 = Fp.mul(t3, t1);
      Z3 = Fp.mul(t5, Z3);
      Z3 = Fp.add(Z3, t0);
      return new Point3(X3, Y3, Z3);
    }
    subtract(other) {
      aprjpoint(other);
      return this.add(other.negate());
    }
    is0() {
      return this.equals(Point3.ZERO);
    }
    /**
     * Constant time multiplication.
     * Uses wNAF method. Windowed method may be 10% faster,
     * but takes 2x longer to generate and consumes 2x memory.
     * Uses precomputes when available.
     * Uses endomorphism for Koblitz curves.
     * @param scalar - by which the point would be multiplied
     * @returns New point
     */
    multiply(scalar) {
      const { endo: endo2 } = extraOpts;
      if (!Fn2.isValidNot0(scalar))
        throw new RangeError("invalid scalar: out of range");
      let point, fake;
      const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point3, p));
      if (endo2) {
        const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
        const { p: k1p, f: k1f } = mul(k1);
        const { p: k2p, f: k2f } = mul(k2);
        fake = k1f.add(k2f);
        point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg);
      } else {
        const { p, f } = mul(scalar);
        point = p;
        fake = f;
      }
      return normalizeZ(Point3, [point, fake])[0];
    }
    /**
     * Non-constant-time multiplication. Uses double-and-add algorithm.
     * It's faster, but should only be used when you don't care about
     * an exposed secret key e.g. sig verification, which works over *public* keys.
     */
    multiplyUnsafe(scalar) {
      const { endo: endo2 } = extraOpts;
      const p = this;
      const sc = scalar;
      if (!Fn2.isValid(sc))
        throw new RangeError("invalid scalar: out of range");
      if (sc === _0n16 || p.is0())
        return Point3.ZERO;
      if (sc === _1n16)
        return p;
      if (wnaf.hasCache(this))
        return this.multiply(sc);
      if (endo2) {
        const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
        const { p1, p2 } = mulEndoUnsafe(Point3, p, k1, k2);
        return finishEndo(endo2.beta, p1, p2, k1neg, k2neg);
      } else {
        return wnaf.unsafe(p, sc);
      }
    }
    /**
     * Converts Projective point to affine (x, y) coordinates.
     * (X, Y, Z) ∋ (x=X/Z, y=Y/Z).
     * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
     */
    toAffine(invertedZ) {
      const p = this;
      let iz = invertedZ;
      const { X, Y, Z } = p;
      if (Fp.eql(Z, Fp.ONE))
        return { x: X, y: Y };
      const is0 = p.is0();
      if (iz == null)
        iz = is0 ? Fp.ONE : Fp.inv(Z);
      const x = Fp.mul(X, iz);
      const y = Fp.mul(Y, iz);
      const zz = Fp.mul(Z, iz);
      if (is0)
        return { x: Fp.ZERO, y: Fp.ZERO };
      if (!Fp.eql(zz, Fp.ONE))
        throw new Error("invZ was invalid");
      return { x, y };
    }
    /**
     * Checks whether Point is free of torsion elements (is in prime subgroup).
     * Always torsion-free for cofactor=1 curves.
     */
    isTorsionFree() {
      const { isTorsionFree } = extraOpts;
      if (cofactor === _1n16)
        return true;
      if (isTorsionFree)
        return isTorsionFree(Point3, this);
      return wnaf.unsafe(this, CURVE_ORDER).is0();
    }
    clearCofactor() {
      const { clearCofactor } = extraOpts;
      if (cofactor === _1n16)
        return this;
      if (clearCofactor)
        return clearCofactor(Point3, this);
      return this.multiplyUnsafe(cofactor);
    }
    isSmallOrder() {
      if (cofactor === _1n16)
        return this.is0();
      return this.clearCofactor().is0();
    }
    toBytes(isCompressed = true) {
      abool3(isCompressed, "isCompressed");
      this.assertValidity();
      return encodePoint(Point3, this, isCompressed);
    }
    toHex(isCompressed = true) {
      return bytesToHex5(this.toBytes(isCompressed));
    }
    toString() {
      return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
    }
  }
  const bits = Fn2.BITS;
  const wnaf = new wNAF3(Point3, extraOpts.endo ? Math.ceil(bits / 2) : bits);
  if (bits >= 8)
    Point3.BASE.precompute(8);
  Object.freeze(Point3.prototype);
  Object.freeze(Point3);
  return Point3;
}
function pprefix(hasEvenY) {
  return Uint8Array.of(hasEvenY ? 2 : 3);
}
function getWLengths(Fp, Fn2) {
  return {
    secretKey: Fn2.BYTES,
    publicKey: 1 + Fp.BYTES,
    publicKeyUncompressed: 1 + 2 * Fp.BYTES,
    publicKeyHasPrefix: true,
    // Raw compact `(r || s)` signature width; DER and recovered signatures use
    // different lengths outside this helper.
    signature: 2 * Fn2.BYTES
  };
}
function ecdh(Point3, ecdhOpts = {}) {
  const { Fn: Fn2 } = Point3;
  const randomBytes_ = ecdhOpts.randomBytes === void 0 ? randomBytes5 : ecdhOpts.randomBytes;
  const lengths = Object.assign(getWLengths(Point3.Fp, Fn2), {
    seed: Math.max(getMinHashLength3(Fn2.ORDER), 16)
  });
  function isValidSecretKey(secretKey) {
    try {
      const num2 = Fn2.fromBytes(secretKey);
      return Fn2.isValidNot0(num2);
    } catch (error) {
      return false;
    }
  }
  function isValidPublicKey(publicKey, isCompressed) {
    const { publicKey: comp, publicKeyUncompressed } = lengths;
    try {
      const l2 = publicKey.length;
      if (isCompressed === true && l2 !== comp)
        return false;
      if (isCompressed === false && l2 !== publicKeyUncompressed)
        return false;
      return !!Point3.fromBytes(publicKey);
    } catch (error) {
      return false;
    }
  }
  function randomSecretKey(seed) {
    seed = seed === void 0 ? randomBytes_(lengths.seed) : seed;
    return mapHashToField3(abytes7(seed, lengths.seed, "seed"), Fn2.ORDER);
  }
  function getPublicKey(secretKey, isCompressed = true) {
    return Point3.BASE.multiply(Fn2.fromBytes(secretKey)).toBytes(isCompressed);
  }
  function isProbPub(item) {
    const { secretKey, publicKey, publicKeyUncompressed } = lengths;
    const allowedLengths = Fn2._lengths;
    if (!isBytes8(item))
      return void 0;
    const l2 = abytes7(item, void 0, "key").length;
    const isPub = l2 === publicKey || l2 === publicKeyUncompressed;
    const isSec = l2 === secretKey || !!allowedLengths?.includes(l2);
    if (isPub && isSec)
      return void 0;
    return isPub;
  }
  function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
    if (isProbPub(secretKeyA) === true)
      throw new Error("first arg must be private key");
    if (isProbPub(publicKeyB) === false)
      throw new Error("second arg must be public key");
    const s3 = Fn2.fromBytes(secretKeyA);
    const b = Point3.fromBytes(publicKeyB);
    return b.multiply(s3).toBytes(isCompressed);
  }
  const utils2 = {
    isValidSecretKey,
    isValidPublicKey,
    randomSecretKey
  };
  const keygen = createKeygen(randomSecretKey, getPublicKey);
  Object.freeze(utils2);
  Object.freeze(lengths);
  return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point: Point3, utils: utils2, lengths });
}
function ecdsa(Point3, hash3, ecdsaOpts = {}) {
  const hash_ = hash3;
  ahash4(hash_);
  validateObject3(ecdsaOpts, {}, {
    hmac: "function",
    lowS: "boolean",
    randomBytes: "function",
    bits2int: "function",
    bits2int_modN: "function"
  });
  ecdsaOpts = Object.assign({}, ecdsaOpts);
  const randomBytes8 = ecdsaOpts.randomBytes === void 0 ? randomBytes5 : ecdsaOpts.randomBytes;
  const hmac5 = ecdsaOpts.hmac === void 0 ? (key, msg) => hmac4(hash_, key, msg) : ecdsaOpts.hmac;
  const { Fp, Fn: Fn2 } = Point3;
  const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn2;
  const { keygen, getPublicKey, getSharedSecret, utils: utils2, lengths } = ecdh(Point3, ecdsaOpts);
  const defaultSigOpts = {
    prehash: true,
    lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
    format: "compact",
    extraEntropy: false
  };
  const hasLargeRecoveryLifts = CURVE_ORDER * _2n10 + _1n16 < Fp.ORDER;
  function isBiggerThanHalfOrder(number) {
    const HALF = CURVE_ORDER >> _1n16;
    return number > HALF;
  }
  function validateRS(title, num2) {
    if (!Fn2.isValidNot0(num2))
      throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
    return num2;
  }
  function assertRecoverableCurve() {
    if (hasLargeRecoveryLifts)
      throw new Error('"recovered" sig type is not supported for cofactor >2 curves');
  }
  function validateSigLength(bytes, format) {
    validateSigFormat(format);
    const size5 = lengths.signature;
    const sizer = format === "compact" ? size5 : format === "recovered" ? size5 + 1 : void 0;
    return abytes7(bytes, sizer);
  }
  class Signature {
    r;
    s;
    recovery;
    constructor(r, s3, recovery) {
      this.r = validateRS("r", r);
      this.s = validateRS("s", s3);
      if (recovery != null) {
        assertRecoverableCurve();
        if (![0, 1, 2, 3].includes(recovery))
          throw new Error("invalid recovery id");
        this.recovery = recovery;
      }
      Object.freeze(this);
    }
    static fromBytes(bytes, format = defaultSigOpts.format) {
      validateSigLength(bytes, format);
      let recid;
      if (format === "der") {
        const { r: r2, s: s4 } = DER3.toSig(abytes7(bytes));
        return new Signature(r2, s4);
      }
      if (format === "recovered") {
        recid = bytes[0];
        format = "compact";
        bytes = bytes.subarray(1);
      }
      const L = lengths.signature / 2;
      const r = bytes.subarray(0, L);
      const s3 = bytes.subarray(L, L * 2);
      return new Signature(Fn2.fromBytes(r), Fn2.fromBytes(s3), recid);
    }
    static fromHex(hex, format) {
      return this.fromBytes(hexToBytes5(hex), format);
    }
    assertRecovery() {
      const { recovery } = this;
      if (recovery == null)
        throw new Error("invalid recovery id: must be present");
      return recovery;
    }
    addRecoveryBit(recovery) {
      return new Signature(this.r, this.s, recovery);
    }
    // Unlike the top-level helper below, this method expects a digest that has
    // already been hashed to the curve's message representative.
    recoverPublicKey(messageHash) {
      const { r, s: s3 } = this;
      const recovery = this.assertRecovery();
      const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;
      if (!Fp.isValid(radj))
        throw new Error("invalid recovery id: sig.r+curve.n != R.x");
      const x = Fp.toBytes(radj);
      const R = Point3.fromBytes(concatBytes7(pprefix((recovery & 1) === 0), x));
      const ir = Fn2.inv(radj);
      const h = bits2int_modN(abytes7(messageHash, void 0, "msgHash"));
      const u1 = Fn2.create(-h * ir);
      const u2 = Fn2.create(s3 * ir);
      const Q = Point3.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
      if (Q.is0())
        throw new Error("invalid recovery: point at infinify");
      Q.assertValidity();
      return Q;
    }
    // Signatures should be low-s, to prevent malleability.
    hasHighS() {
      return isBiggerThanHalfOrder(this.s);
    }
    toBytes(format = defaultSigOpts.format) {
      validateSigFormat(format);
      if (format === "der")
        return hexToBytes5(DER3.hexFromSig(this));
      const { r, s: s3 } = this;
      const rb = Fn2.toBytes(r);
      const sb = Fn2.toBytes(s3);
      if (format === "recovered") {
        assertRecoverableCurve();
        return concatBytes7(Uint8Array.of(this.assertRecovery()), rb, sb);
      }
      return concatBytes7(rb, sb);
    }
    toHex(format) {
      return bytesToHex5(this.toBytes(format));
    }
  }
  Object.freeze(Signature.prototype);
  Object.freeze(Signature);
  const bits2int = ecdsaOpts.bits2int === void 0 ? function bits2int_def(bytes) {
    if (bytes.length > 8192)
      throw new Error("input is too large");
    const num2 = bytesToNumberBE3(bytes);
    const delta = bytes.length * 8 - fnBits;
    return delta > 0 ? num2 >> BigInt(delta) : num2;
  } : ecdsaOpts.bits2int;
  const bits2int_modN = ecdsaOpts.bits2int_modN === void 0 ? function bits2int_modN_def(bytes) {
    return Fn2.create(bits2int(bytes));
  } : ecdsaOpts.bits2int_modN;
  const ORDER_MASK = bitMask3(fnBits);
  function int2octets(num2) {
    aInRange3("num < 2^" + fnBits, num2, _0n16, ORDER_MASK);
    return Fn2.toBytes(num2);
  }
  function validateMsgAndHash(message, prehash) {
    abytes7(message, void 0, "message");
    return prehash ? abytes7(hash_(message), void 0, "prehashed message") : message;
  }
  function prepSig(message, secretKey, opts) {
    const { lowS, prehash, extraEntropy: extraEntropy2 } = validateSigOpts(opts, defaultSigOpts);
    message = validateMsgAndHash(message, prehash);
    const h1int = bits2int_modN(message);
    const d = Fn2.fromBytes(secretKey);
    if (!Fn2.isValidNot0(d))
      throw new Error("invalid private key");
    const seedArgs = [int2octets(d), int2octets(h1int)];
    if (extraEntropy2 != null && extraEntropy2 !== false) {
      const e7 = extraEntropy2 === true ? randomBytes8(lengths.secretKey) : extraEntropy2;
      seedArgs.push(abytes7(e7, void 0, "extraEntropy"));
    }
    const seed = concatBytes7(...seedArgs);
    const m = h1int;
    function k2sig(kBytes) {
      const k = bits2int(kBytes);
      if (!Fn2.isValidNot0(k))
        return;
      const ik = Fn2.inv(k);
      const q = Point3.BASE.multiply(k).toAffine();
      const r = Fn2.create(q.x);
      if (r === _0n16)
        return;
      const s3 = Fn2.create(ik * Fn2.create(m + r * d));
      if (s3 === _0n16)
        return;
      let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n16);
      let normS = s3;
      if (lowS && isBiggerThanHalfOrder(s3)) {
        normS = Fn2.neg(s3);
        recovery ^= 1;
      }
      return new Signature(r, normS, hasLargeRecoveryLifts ? void 0 : recovery);
    }
    return { seed, k2sig };
  }
  function sign2(message, secretKey, opts = {}) {
    const { seed, k2sig } = prepSig(message, secretKey, opts);
    const drbg = createHmacDrbg3(hash_.outputLen, Fn2.BYTES, hmac5);
    const sig = drbg(seed, k2sig);
    return sig.toBytes(opts.format);
  }
  function verify(signature2, message, publicKey, opts = {}) {
    const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
    publicKey = abytes7(publicKey, void 0, "publicKey");
    message = validateMsgAndHash(message, prehash);
    if (!isBytes8(signature2)) {
      const end = signature2 instanceof Signature ? ", use sig.toBytes()" : "";
      throw new Error("verify expects Uint8Array signature" + end);
    }
    validateSigLength(signature2, format);
    try {
      const sig = Signature.fromBytes(signature2, format);
      const P2 = Point3.fromBytes(publicKey);
      if (lowS && sig.hasHighS())
        return false;
      const { r, s: s3 } = sig;
      const h = bits2int_modN(message);
      const is = Fn2.inv(s3);
      const u1 = Fn2.create(h * is);
      const u2 = Fn2.create(r * is);
      const R = Point3.BASE.multiplyUnsafe(u1).add(P2.multiplyUnsafe(u2));
      if (R.is0())
        return false;
      const v = Fn2.create(R.x);
      return v === r;
    } catch (e7) {
      return false;
    }
  }
  function recoverPublicKey3(signature2, message, opts = {}) {
    const { prehash } = validateSigOpts(opts, defaultSigOpts);
    message = validateMsgAndHash(message, prehash);
    return Signature.fromBytes(signature2, "recovered").recoverPublicKey(message).toBytes();
  }
  return Object.freeze({
    keygen,
    getPublicKey,
    getSharedSecret,
    utils: utils2,
    lengths,
    Point: Point3,
    sign: sign2,
    verify,
    recoverPublicKey: recoverPublicKey3,
    Signature,
    hash: hash_
  });
}
var divNearest3, DERErr3, DER3, _0n16, _1n16, _2n10, _3n6, _4n6;
var init_weierstrass3 = __esm({
  "node_modules/@noble/curves/abstract/weierstrass.js"() {
    "use strict";
    init_hmac4();
    init_utils10();
    init_utils11();
    init_curve3();
    init_modular3();
    divNearest3 = (num2, den) => (num2 + (num2 >= 0 ? den : -den) / _2n10) / den;
    DERErr3 = class extends Error {
      constructor(m = "") {
        super(m);
      }
    };
    DER3 = {
      // asn.1 DER encoding utils
      Err: DERErr3,
      // Basic building block is TLV (Tag-Length-Value)
      _tlv: {
        encode: (tag, data) => {
          const { Err: E } = DER3;
          asafenumber(tag, "tag");
          if (tag < 0 || tag > 255)
            throw new E("tlv.encode: wrong tag");
          if (typeof data !== "string")
            throw new TypeError('"data" expected string, got type=' + typeof data);
          if (data.length & 1)
            throw new E("tlv.encode: unpadded data");
          const dataLen = data.length / 2;
          const len = numberToHexUnpadded3(dataLen);
          if (len.length / 2 & 128)
            throw new E("tlv.encode: long form length too big");
          const lenLen = dataLen > 127 ? numberToHexUnpadded3(len.length / 2 | 128) : "";
          const t = numberToHexUnpadded3(tag);
          return t + lenLen + len + data;
        },
        // v - value, l - left bytes (unparsed)
        decode(tag, data) {
          const { Err: E } = DER3;
          data = abytes7(data, void 0, "DER data");
          let pos = 0;
          if (tag < 0 || tag > 255)
            throw new E("tlv.encode: wrong tag");
          if (data.length < 2 || data[pos++] !== tag)
            throw new E("tlv.decode: wrong tlv");
          const first = data[pos++];
          const isLong = !!(first & 128);
          let length = 0;
          if (!isLong)
            length = first;
          else {
            const lenLen = first & 127;
            if (!lenLen)
              throw new E("tlv.decode(long): indefinite length not supported");
            if (lenLen > 4)
              throw new E("tlv.decode(long): byte length is too big");
            const lengthBytes = data.subarray(pos, pos + lenLen);
            if (lengthBytes.length !== lenLen)
              throw new E("tlv.decode: length bytes not complete");
            if (lengthBytes[0] === 0)
              throw new E("tlv.decode(long): zero leftmost byte");
            for (const b of lengthBytes)
              length = length << 8 | b;
            pos += lenLen;
            if (length < 128)
              throw new E("tlv.decode(long): not minimal encoding");
          }
          const v = data.subarray(pos, pos + length);
          if (v.length !== length)
            throw new E("tlv.decode: wrong value length");
          return { v, l: data.subarray(pos + length) };
        }
      },
      // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,
      // since we always use positive integers here. It must always be empty:
      // - add zero byte if exists
      // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)
      _int: {
        encode(num2) {
          const { Err: E } = DER3;
          abignumber(num2);
          if (num2 < _0n16)
            throw new E("integer: negative integers are not allowed");
          let hex = numberToHexUnpadded3(num2);
          if (Number.parseInt(hex[0], 16) & 8)
            hex = "00" + hex;
          if (hex.length & 1)
            throw new E("unexpected DER parsing assertion: unpadded hex");
          return hex;
        },
        decode(data) {
          const { Err: E } = DER3;
          if (data.length < 1)
            throw new E("invalid signature integer: empty");
          if (data[0] & 128)
            throw new E("invalid signature integer: negative");
          if (data.length > 1 && data[0] === 0 && !(data[1] & 128))
            throw new E("invalid signature integer: unnecessary leading zero");
          return bytesToNumberBE3(data);
        }
      },
      toSig(bytes) {
        const { Err: E, _int: int, _tlv: tlv } = DER3;
        const data = abytes7(bytes, void 0, "signature");
        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
        if (seqLeftBytes.length)
          throw new E("invalid signature: left bytes after parsing");
        const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
        const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
        if (sLeftBytes.length)
          throw new E("invalid signature: left bytes after parsing");
        return { r: int.decode(rBytes), s: int.decode(sBytes) };
      },
      hexFromSig(sig) {
        const { _tlv: tlv, _int: int } = DER3;
        const rs = tlv.encode(2, int.encode(sig.r));
        const ss = tlv.encode(2, int.encode(sig.s));
        const seq = rs + ss;
        return tlv.encode(48, seq);
      }
    };
    Object.freeze(DER3._tlv);
    Object.freeze(DER3._int);
    Object.freeze(DER3);
    _0n16 = /* @__PURE__ */ BigInt(0);
    _1n16 = /* @__PURE__ */ BigInt(1);
    _2n10 = /* @__PURE__ */ BigInt(2);
    _3n6 = /* @__PURE__ */ BigInt(3);
    _4n6 = /* @__PURE__ */ BigInt(4);
  }
});

// node_modules/@noble/curves/secp256k1.js
function sqrtMod3(y) {
  const P2 = secp256k1_CURVE.p;
  const _3n7 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);
  const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);
  const b2 = y * y * y % P2;
  const b3 = b2 * b2 * y % P2;
  const b6 = pow23(b3, _3n7, P2) * b3 % P2;
  const b9 = pow23(b6, _3n7, P2) * b3 % P2;
  const b11 = pow23(b9, _2n11, P2) * b2 % P2;
  const b22 = pow23(b11, _11n, P2) * b11 % P2;
  const b44 = pow23(b22, _22n, P2) * b22 % P2;
  const b88 = pow23(b44, _44n, P2) * b44 % P2;
  const b176 = pow23(b88, _88n, P2) * b88 % P2;
  const b220 = pow23(b176, _44n, P2) * b44 % P2;
  const b223 = pow23(b220, _3n7, P2) * b3 % P2;
  const t1 = pow23(b223, _23n, P2) * b22 % P2;
  const t2 = pow23(t1, _6n, P2) * b2 % P2;
  const root = pow23(t2, _2n11, P2);
  if (!Fpk13.eql(Fpk13.sqr(root), y))
    throw new Error("Cannot find square root");
  return root;
}
var secp256k1_CURVE, secp256k1_ENDO, _2n11, Fpk13, Pointk1, secp256k13;
var init_secp256k13 = __esm({
  "node_modules/@noble/curves/secp256k1.js"() {
    "use strict";
    init_sha24();
    init_modular3();
    init_weierstrass3();
    secp256k1_CURVE = {
      p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
      n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
      h: BigInt(1),
      a: BigInt(0),
      b: BigInt(7),
      Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),
      Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
    };
    secp256k1_ENDO = {
      beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),
      basises: [
        [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],
        [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")]
      ]
    };
    _2n11 = /* @__PURE__ */ BigInt(2);
    Fpk13 = Field3(secp256k1_CURVE.p, { sqrt: sqrtMod3 });
    Pointk1 = /* @__PURE__ */ weierstrass3(secp256k1_CURVE, {
      Fp: Fpk13,
      endo: secp256k1_ENDO
    });
    secp256k13 = /* @__PURE__ */ ecdsa(Pointk1, sha2566);
  }
});

// node_modules/@noble/hashes/legacy.js
function ripemd_f(group, x, y, z) {
  if (group === 0)
    return x ^ y ^ z;
  if (group === 1)
    return x & y | ~x & z;
  if (group === 2)
    return (x | ~y) ^ z;
  if (group === 3)
    return x & z | y & ~z;
  return x ^ (y | ~z);
}
var Rho160, Id160, Pi160, idxLR, idxL, idxR, shifts160, shiftsL160, shiftsR160, Kl160, Kr160, BUF_160, _RIPEMD160, ripemd160;
var init_legacy = __esm({
  "node_modules/@noble/hashes/legacy.js"() {
    "use strict";
    init_md4();
    init_utils10();
    Rho160 = /* @__PURE__ */ Uint8Array.from([
      7,
      4,
      13,
      1,
      10,
      6,
      15,
      3,
      12,
      0,
      9,
      5,
      2,
      14,
      11,
      8
    ]);
    Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();
    Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();
    idxLR = /* @__PURE__ */ (() => {
      const L = [Id160];
      const R = [Pi160];
      const res = [L, R];
      for (let i = 0; i < 4; i++)
        for (let j of res)
          j.push(j[i].map((k) => Rho160[k]));
      return res;
    })();
    idxL = /* @__PURE__ */ (() => idxLR[0])();
    idxR = /* @__PURE__ */ (() => idxLR[1])();
    shifts160 = /* @__PURE__ */ [
      [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],
      [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],
      [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],
      [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],
      [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5]
    ].map((i) => Uint8Array.from(i));
    shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));
    shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));
    Kl160 = /* @__PURE__ */ Uint32Array.from([
      0,
      1518500249,
      1859775393,
      2400959708,
      2840853838
    ]);
    Kr160 = /* @__PURE__ */ Uint32Array.from([
      1352829926,
      1548603684,
      1836072691,
      2053994217,
      0
    ]);
    BUF_160 = /* @__PURE__ */ new Uint32Array(16);
    _RIPEMD160 = class extends HashMD4 {
      h0 = 1732584193 | 0;
      h1 = 4023233417 | 0;
      h2 = 2562383102 | 0;
      h3 = 271733878 | 0;
      h4 = 3285377520 | 0;
      constructor() {
        super(64, 20, 8, true);
      }
      get() {
        const { h0, h1, h2, h3, h4 } = this;
        return [h0, h1, h2, h3, h4];
      }
      set(h0, h1, h2, h3, h4) {
        this.h0 = h0 | 0;
        this.h1 = h1 | 0;
        this.h2 = h2 | 0;
        this.h3 = h3 | 0;
        this.h4 = h4 | 0;
      }
      process(view, offset) {
        for (let i = 0; i < 16; i++, offset += 4)
          BUF_160[i] = view.getUint32(offset, true);
        let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;
        for (let group = 0; group < 5; group++) {
          const rGroup = 4 - group;
          const hbl = Kl160[group], hbr = Kr160[group];
          const rl = idxL[group], rr = idxR[group];
          const sl = shiftsL160[group], sr = shiftsR160[group];
          for (let i = 0; i < 16; i++) {
            const tl = rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el | 0;
            al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl;
          }
          for (let i = 0; i < 16; i++) {
            const tr = rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er | 0;
            ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr;
          }
        }
        this.set(this.h1 + cl + dr | 0, this.h2 + dl + er | 0, this.h3 + el + ar | 0, this.h4 + al + br | 0, this.h0 + bl + cr | 0);
      }
      roundClean() {
        clean4(BUF_160);
      }
      destroy() {
        this.destroyed = true;
        clean4(this.buffer);
        this.set(0, 0, 0, 0, 0);
      }
    };
    ripemd160 = /* @__PURE__ */ createHasher5(() => new _RIPEMD160());
  }
});

// node_modules/@scure/base/index.js
function isBytes9(a) {
  return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
}
function isArrayOf2(isString, arr) {
  if (!Array.isArray(arr))
    return false;
  if (arr.length === 0)
    return true;
  if (isString) {
    return arr.every((item) => typeof item === "string");
  } else {
    return arr.every((item) => Number.isSafeInteger(item));
  }
}
function afn2(input) {
  if (typeof input !== "function")
    throw new TypeError("function expected");
  return true;
}
function astr2(label, input) {
  if (typeof input !== "string")
    throw new TypeError(`${label}: string expected`);
  return true;
}
function anumber7(n) {
  if (typeof n !== "number")
    throw new TypeError(`number expected, got ${typeof n}`);
  if (!Number.isSafeInteger(n))
    throw new RangeError(`invalid integer: ${n}`);
}
function aArr2(input) {
  if (!Array.isArray(input))
    throw new TypeError("array expected");
}
function astrArr2(label, input) {
  if (!isArrayOf2(true, input))
    throw new TypeError(`${label}: array of strings expected`);
}
function anumArr2(label, input) {
  if (!isArrayOf2(false, input))
    throw new TypeError(`${label}: array of numbers expected`);
}
// @__NO_SIDE_EFFECTS__
function chain2(...args) {
  const id = (a) => a;
  const wrap3 = (a, b) => (c) => a(b(c));
  const encode4 = args.map((x) => x.encode).reduceRight(wrap3, id);
  const decode2 = args.map((x) => x.decode).reduce(wrap3, id);
  return { encode: encode4, decode: decode2 };
}
// @__NO_SIDE_EFFECTS__
function alphabet2(letters) {
  const lettersA = typeof letters === "string" ? letters.split("") : letters;
  const len = lettersA.length;
  astrArr2("alphabet", lettersA);
  const indexes = new Map(lettersA.map((l2, i) => [l2, i]));
  return {
    encode: (digits) => {
      aArr2(digits);
      return digits.map((i) => {
        if (!Number.isSafeInteger(i) || i < 0 || i >= len)
          throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`);
        return lettersA[i];
      });
    },
    decode: (input) => {
      aArr2(input);
      return input.map((letter) => {
        astr2("alphabet.decode", letter);
        const i = indexes.get(letter);
        if (i === void 0)
          throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`);
        return i;
      });
    }
  };
}
// @__NO_SIDE_EFFECTS__
function join5(separator = "") {
  astr2("join", separator);
  return {
    encode: (from14) => {
      astrArr2("join.decode", from14);
      return from14.join(separator);
    },
    decode: (to) => {
      astr2("join.decode", to);
      return to.split(separator);
    }
  };
}
function convertRadix3(data, from14, to) {
  if (from14 < 2)
    throw new RangeError(`convertRadix: invalid from=${from14}, base cannot be less than 2`);
  if (to < 2)
    throw new RangeError(`convertRadix: invalid to=${to}, base cannot be less than 2`);
  aArr2(data);
  if (!data.length)
    return [];
  let pos = 0;
  const res = [];
  const digits = Array.from(data, (d) => {
    anumber7(d);
    if (d < 0 || d >= from14)
      throw new Error(`invalid integer: ${d}`);
    return d;
  });
  const dlen = digits.length;
  while (true) {
    let carry = 0;
    let done = true;
    for (let i = pos; i < dlen; i++) {
      const digit = digits[i];
      const fromCarry = from14 * carry;
      const digitBase = fromCarry + digit;
      if (!Number.isSafeInteger(digitBase) || fromCarry / from14 !== carry || digitBase - digit !== fromCarry) {
        throw new Error("convertRadix: carry overflow");
      }
      const div = digitBase / to;
      carry = digitBase % to;
      const rounded = Math.floor(div);
      digits[i] = rounded;
      if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)
        throw new Error("convertRadix: carry overflow");
      if (!done)
        continue;
      else if (!rounded)
        pos = i;
      else
        done = false;
    }
    res.push(carry);
    if (done)
      break;
  }
  for (let i = 0; i < data.length - 1 && data[i] === 0; i++)
    res.push(0);
  return res.reverse();
}
// @__NO_SIDE_EFFECTS__
function radix3(num2) {
  anumber7(num2);
  const _256 = 2 ** 8;
  return {
    encode: (bytes) => {
      if (!isBytes9(bytes))
        throw new TypeError("radix.encode input should be Uint8Array");
      return convertRadix3(Array.from(bytes), _256, num2);
    },
    decode: (digits) => {
      anumArr2("radix.decode", digits);
      return Uint8Array.from(convertRadix3(digits, num2, _256));
    }
  };
}
function checksum4(len, fn) {
  anumber7(len);
  if (len <= 0)
    throw new RangeError(`checksum length must be positive: ${len}`);
  afn2(fn);
  const _fn = fn;
  return {
    encode(data) {
      if (!isBytes9(data))
        throw new TypeError("checksum.encode: input should be Uint8Array");
      const sum = _fn(data).slice(0, len);
      const res = new Uint8Array(data.length + len);
      res.set(data);
      res.set(sum, data.length);
      return res;
    },
    decode(data) {
      if (!isBytes9(data))
        throw new TypeError("checksum.decode: input should be Uint8Array");
      const payload = data.slice(0, -len);
      const oldChecksum = data.slice(-len);
      const newChecksum = _fn(payload).slice(0, len);
      for (let i = 0; i < len; i++)
        if (newChecksum[i] !== oldChecksum[i])
          throw new Error("Invalid checksum");
      return payload;
    }
  };
}
var genBase58, base58, createBase58check;
var init_base3 = __esm({
  "node_modules/@scure/base/index.js"() {
    "use strict";
    genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => /* @__PURE__ */ chain2(/* @__PURE__ */ radix3(58), /* @__PURE__ */ alphabet2(abc), /* @__PURE__ */ join5(""));
    base58 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"));
    createBase58check = (sha2567) => {
      afn2(sha2567);
      const _sha256 = sha2567;
      return /* @__PURE__ */ chain2(checksum4(4, (data) => _sha256(_sha256(data))), base58);
    };
  }
});

// node_modules/@scure/bip32/index.js
var Point2, Fn, base58check, MASTER_SECRET, BITCOIN_VERSIONS, HARDENED_OFFSET, hash160, fromU32, toU32, HDKey;
var init_bip32 = __esm({
  "node_modules/@scure/bip32/index.js"() {
    "use strict";
    init_secp256k13();
    init_hmac4();
    init_legacy();
    init_sha24();
    init_utils10();
    init_base3();
    Point2 = /* @__PURE__ */ (() => secp256k13.Point)();
    Fn = /* @__PURE__ */ (() => Point2.Fn)();
    base58check = /* @__PURE__ */ createBase58check(sha2566);
    MASTER_SECRET = /* @__PURE__ */ (() => {
      return Uint8Array.from("Bitcoin seed".split(""), (char) => char.charCodeAt(0));
    })();
    BITCOIN_VERSIONS = { private: 76066276, public: 76067358 };
    HARDENED_OFFSET = 2147483648;
    hash160 = (data) => ripemd160(sha2566(data));
    fromU32 = (data) => createView4(data).getUint32(0, false);
    toU32 = (n) => {
      if (typeof n !== "number")
        throw new TypeError("invalid number, should be from 0 to 2**32-1, got " + n);
      if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1)
        throw new RangeError("invalid number, should be from 0 to 2**32-1, got " + n);
      const buf = new Uint8Array(4);
      createView4(buf).setUint32(0, n, false);
      return buf;
    };
    HDKey = class _HDKey {
      get fingerprint() {
        if (!this.pubHash) {
          throw new Error("No publicKey set!");
        }
        return fromU32(this.pubHash);
      }
      get identifier() {
        return this.pubHash;
      }
      get pubKeyHash() {
        return this.pubHash;
      }
      // Returns the live private key buffer for this instance.
      // Copy it first if you need an immutable snapshot.
      get privateKey() {
        return this._privateKey || null;
      }
      get publicKey() {
        return this._publicKey || null;
      }
      get privateExtendedKey() {
        const priv = this._privateKey;
        if (!priv) {
          throw new Error("No private key");
        }
        return base58check.encode(this.serialize(this.versions.private, concatBytes6(Uint8Array.of(0), priv)));
      }
      get publicExtendedKey() {
        if (!this._publicKey) {
          throw new Error("No public key");
        }
        return base58check.encode(this.serialize(this.versions.public, this._publicKey));
      }
      static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) {
        abytes6(seed);
        if (8 * seed.length < 128 || 8 * seed.length > 512) {
          throw new RangeError("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got " + seed.length);
        }
        const I = hmac4(sha5122, MASTER_SECRET, seed);
        const privateKey = I.slice(0, 32);
        const chainCode = I.slice(32);
        return new _HDKey({ versions, chainCode, privateKey });
      }
      static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) {
        const keyBuffer = base58check.decode(base58key);
        const keyView = createView4(keyBuffer);
        const version4 = keyView.getUint32(0, false);
        const opt = {
          versions,
          depth: keyBuffer[4],
          parentFingerprint: keyView.getUint32(5, false),
          index: keyView.getUint32(9, false),
          chainCode: keyBuffer.slice(13, 45)
        };
        const key = keyBuffer.slice(45);
        const isPriv = key[0] === 0;
        if (version4 !== versions[isPriv ? "private" : "public"]) {
          throw new Error("Version mismatch");
        }
        if (isPriv) {
          return new _HDKey({ ...opt, privateKey: key.slice(1) });
        } else {
          return new _HDKey({ ...opt, publicKey: key });
        }
      }
      static fromJSON(json) {
        return _HDKey.fromExtendedKey(json.xpriv);
      }
      versions;
      depth = 0;
      index = 0;
      chainCode = null;
      parentFingerprint = 0;
      _privateKey;
      _publicKey;
      pubHash;
      constructor(opt) {
        if (!opt || typeof opt !== "object") {
          throw new Error("HDKey.constructor must not be called directly");
        }
        this.versions = opt.versions || BITCOIN_VERSIONS;
        this.depth = opt.depth || 0;
        this.chainCode = opt.chainCode ? Uint8Array.from(opt.chainCode) : null;
        this.index = opt.index || 0;
        this.parentFingerprint = opt.parentFingerprint || 0;
        if (!this.depth) {
          if (this.parentFingerprint || this.index) {
            throw new Error("HDKey: zero depth with non-zero index/parent fingerprint");
          }
        }
        if (this.depth > 255) {
          throw new Error("HDKey: depth exceeds the serializable value 255");
        }
        if (opt.publicKey && opt.privateKey) {
          throw new Error("HDKey: publicKey and privateKey at same time.");
        }
        if (opt.privateKey) {
          if (!secp256k13.utils.isValidSecretKey(opt.privateKey))
            throw new Error("Invalid private key");
          this._privateKey = Uint8Array.from(opt.privateKey);
          this._publicKey = secp256k13.getPublicKey(this._privateKey, true);
        } else if (opt.publicKey) {
          this._publicKey = Point2.fromBytes(opt.publicKey).toBytes(true);
        } else {
          throw new Error("HDKey: no public or private key provided");
        }
        this.pubHash = hash160(this._publicKey);
      }
      derive(path2) {
        if (!/^[mM]'?/.test(path2)) {
          throw new Error('Path must start with "m" or "M"');
        }
        if (/^[mM]'?$/.test(path2)) {
          return this;
        }
        const parts = path2.replace(/^[mM]'?\//, "").split("/");
        let child = this;
        for (const c of parts) {
          const m = /^(\d+)('?)$/.exec(c);
          const m1 = m && m[1];
          if (!m || m.length !== 3 || typeof m1 !== "string")
            throw new Error("invalid child index: " + c);
          let idx = +m1;
          if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {
            throw new Error("Invalid index");
          }
          if (m[2] === "'") {
            idx += HARDENED_OFFSET;
          }
          child = child.deriveChild(idx);
        }
        return child;
      }
      /**
       * @param _I - Test-only override for the 64-byte HMAC-SHA512 output; normal callers must omit it.
       */
      deriveChild(index2, _I) {
        if (!this._publicKey || !this.chainCode) {
          throw new Error("No publicKey or chainCode set");
        }
        let data = toU32(index2);
        if (index2 >= HARDENED_OFFSET) {
          const priv = this._privateKey;
          if (!priv) {
            throw new Error("Could not derive hardened child key");
          }
          data = concatBytes6(Uint8Array.of(0), priv, data);
        } else {
          data = concatBytes6(this._publicKey, data);
        }
        const out = _I || hmac4(sha5122, this.chainCode, data);
        abytes6(out, 64);
        const childTweak = out.slice(0, 32);
        const chainCode = out.slice(32);
        const opt = {
          versions: this.versions,
          chainCode,
          depth: this.depth + 1,
          parentFingerprint: this.fingerprint,
          index: index2
        };
        if (opt.depth > 255) {
          throw new Error("HDKey: depth exceeds the serializable value 255");
        }
        try {
          const ctweak = Fn.fromBytes(childTweak);
          if (this._privateKey) {
            const added = Fn.create(Fn.fromBytes(this._privateKey) + ctweak);
            if (!Fn.isValidNot0(added)) {
              throw new Error("The tweak was out of range or the resulted private key is invalid");
            }
            opt.privateKey = Fn.toBytes(added);
          } else {
            const point = Point2.fromBytes(this._publicKey);
            const added = ctweak === 0n ? point : point.add(Point2.BASE.multiply(ctweak));
            if (added.equals(Point2.ZERO)) {
              throw new Error("The tweak was equal to negative P, which made the result key invalid");
            }
            opt.publicKey = added.toBytes(true);
          }
          return new _HDKey(opt);
        } catch (err) {
          return this.deriveChild(index2 + 1);
        }
      }
      sign(hash3) {
        if (!this._privateKey) {
          throw new Error("No privateKey set!");
        }
        abytes6(hash3, 32);
        return secp256k13.sign(hash3, this._privateKey, { prehash: false });
      }
      verify(hash3, signature2) {
        abytes6(hash3, 32);
        abytes6(signature2, 64);
        if (!this._publicKey) {
          throw new Error("No publicKey set!");
        }
        return secp256k13.verify(signature2, hash3, this._publicKey, { prehash: false });
      }
      wipePrivateData() {
        if (this._privateKey) {
          this._privateKey.fill(0);
          this._privateKey = void 0;
        }
        return this;
      }
      toJSON() {
        return {
          xpriv: this.privateExtendedKey,
          xpub: this.publicExtendedKey
        };
      }
      serialize(version4, key) {
        if (!this.chainCode) {
          throw new Error("No chainCode set");
        }
        abytes6(key, 33);
        return concatBytes6(toU32(version4), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key);
      }
    };
  }
});

// node_modules/@solana/errors/dist/index.node.mjs
function encodeValue(value) {
  if (Array.isArray(value)) {
    const commaSeparatedValues = value.map(encodeValue).join(
      "%2C%20"
      /* ", " */
    );
    return "%5B" + commaSeparatedValues + /* "]" */
    "%5D";
  } else if (typeof value === "bigint") {
    return `${value}n`;
  } else {
    return encodeURIComponent(
      String(
        value != null && Object.getPrototypeOf(value) === null ? (
          // Plain objects with no prototype don't have a `toString` method.
          // Convert them before stringifying them.
          { ...value }
        ) : value
      )
    );
  }
}
function encodeObjectContextEntry([key, value]) {
  return `${key}=${encodeValue(value)}`;
}
function encodeContextObject(context) {
  const searchParamsString = Object.entries(context).map(encodeObjectContextEntry).join("&");
  return Buffer.from(searchParamsString, "utf8").toString("base64");
}
function getHumanReadableErrorMessage(code, context = {}) {
  const messageFormatString = SolanaErrorMessages[code];
  if (messageFormatString.length === 0) {
    return "";
  }
  let state;
  function commitStateUpTo(endIndex) {
    if (state[TYPE] === 2) {
      const variableName = messageFormatString.slice(state[START_INDEX] + 1, endIndex);
      fragments.push(
        variableName in context ? (
          // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
          `${context[variableName]}`
        ) : `$${variableName}`
      );
    } else if (state[TYPE] === 1) {
      fragments.push(messageFormatString.slice(state[START_INDEX], endIndex));
    }
  }
  const fragments = [];
  messageFormatString.split("").forEach((char, ii) => {
    if (ii === 0) {
      state = {
        [START_INDEX]: 0,
        [TYPE]: messageFormatString[0] === "\\" ? 0 : messageFormatString[0] === "$" ? 2 : 1
        /* Text */
      };
      return;
    }
    let nextState;
    switch (state[TYPE]) {
      case 0:
        nextState = {
          [START_INDEX]: ii,
          [TYPE]: 1
          /* Text */
        };
        break;
      case 1:
        if (char === "\\") {
          nextState = {
            [START_INDEX]: ii,
            [TYPE]: 0
            /* EscapeSequence */
          };
        } else if (char === "$") {
          nextState = {
            [START_INDEX]: ii,
            [TYPE]: 2
            /* Variable */
          };
        }
        break;
      case 2:
        if (char === "\\") {
          nextState = {
            [START_INDEX]: ii,
            [TYPE]: 0
            /* EscapeSequence */
          };
        } else if (char === "$") {
          nextState = {
            [START_INDEX]: ii,
            [TYPE]: 2
            /* Variable */
          };
        } else if (!char.match(/\w/)) {
          nextState = {
            [START_INDEX]: ii,
            [TYPE]: 1
            /* Text */
          };
        }
        break;
    }
    if (nextState) {
      if (state !== nextState) {
        commitStateUpTo(ii);
      }
      state = nextState;
    }
  });
  commitStateUpTo();
  return fragments.join("");
}
function getErrorMessage(code, context = {}) {
  if (process.env.NODE_ENV !== "production") {
    return getHumanReadableErrorMessage(code, context);
  } else {
    let decodingAdviceMessage = `Solana error #${code}; Decode this error by running \`npx @solana/errors decode -- ${code}`;
    if (Object.keys(context).length) {
      decodingAdviceMessage += ` '${encodeContextObject(context)}'`;
    }
    return `${decodingAdviceMessage}\``;
  }
}
function isSolanaError(e7, code) {
  const isSolanaError2 = e7 instanceof Error && e7.name === "SolanaError";
  if (isSolanaError2) {
    if (code !== void 0) {
      return e7.context.__code === code;
    }
    return true;
  }
  return false;
}
function safeCaptureStackTrace(...args) {
  if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") {
    Error.captureStackTrace(...args);
  }
}
function getSolanaErrorFromRpcError({ errorCodeBaseOffset, getErrorContext, orderedErrorNames, rpcEnumError }, constructorOpt) {
  let rpcErrorName;
  let rpcErrorContext;
  if (typeof rpcEnumError === "string") {
    rpcErrorName = rpcEnumError;
  } else {
    rpcErrorName = Object.keys(rpcEnumError)[0];
    rpcErrorContext = rpcEnumError[rpcErrorName];
  }
  const codeOffset = orderedErrorNames.indexOf(rpcErrorName);
  const errorCode = errorCodeBaseOffset + codeOffset;
  const errorContext = getErrorContext(errorCode, rpcErrorName, rpcErrorContext);
  const err = new SolanaError(errorCode, errorContext);
  safeCaptureStackTrace(err, constructorOpt);
  return err;
}
function getSolanaErrorFromInstructionError(index2, instructionError) {
  const numberIndex = Number(index2);
  return getSolanaErrorFromRpcError(
    {
      errorCodeBaseOffset: 4615001,
      getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {
        if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN) {
          return {
            errorName: rpcErrorName,
            index: numberIndex,
            ...rpcErrorContext !== void 0 ? { instructionErrorContext: rpcErrorContext } : null
          };
        } else if (errorCode === SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM) {
          return {
            code: Number(rpcErrorContext),
            index: numberIndex
          };
        }
        return { index: numberIndex };
      },
      orderedErrorNames: ORDERED_ERROR_NAMES,
      rpcEnumError: instructionError
    },
    getSolanaErrorFromInstructionError
  );
}
function getSolanaErrorFromTransactionError(transactionError) {
  if (typeof transactionError === "object" && "InstructionError" in transactionError) {
    return getSolanaErrorFromInstructionError(
      ...transactionError.InstructionError
    );
  }
  return getSolanaErrorFromRpcError(
    {
      errorCodeBaseOffset: 7050001,
      getErrorContext(errorCode, rpcErrorName, rpcErrorContext) {
        if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN) {
          return {
            errorName: rpcErrorName,
            ...rpcErrorContext !== void 0 ? { transactionErrorContext: rpcErrorContext } : null
          };
        } else if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION) {
          return {
            index: Number(rpcErrorContext)
          };
        } else if (errorCode === SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT || errorCode === SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED) {
          return {
            accountIndex: Number(rpcErrorContext.account_index)
          };
        }
      },
      orderedErrorNames: ORDERED_ERROR_NAMES2,
      rpcEnumError: transactionError
    },
    getSolanaErrorFromTransactionError
  );
}
function getSolanaErrorFromJsonRpcError(putativeErrorResponse) {
  let out;
  if (isRpcErrorResponse(putativeErrorResponse)) {
    const { code: rawCode, data, message } = putativeErrorResponse;
    const code = Number(rawCode);
    if (code === SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE) {
      const { err, ...preflightErrorContext } = data;
      const causeObject = err ? { cause: getSolanaErrorFromTransactionError(err) } : null;
      out = new SolanaError(SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE, {
        ...preflightErrorContext,
        ...causeObject
      });
    } else {
      let errorContext;
      switch (code) {
        case SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR:
        case SOLANA_ERROR__JSON_RPC__INVALID_PARAMS:
        case SOLANA_ERROR__JSON_RPC__INVALID_REQUEST:
        case SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND:
        case SOLANA_ERROR__JSON_RPC__PARSE_ERROR:
        case SOLANA_ERROR__JSON_RPC__SCAN_ERROR:
        case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP:
        case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE:
        case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET:
        case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX:
        case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED:
        case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED:
        case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE:
        case SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION:
          errorContext = { __serverMessage: message };
          break;
        default:
          if (typeof data === "object" && !Array.isArray(data)) {
            errorContext = data;
          }
      }
      out = new SolanaError(code, errorContext);
    }
  } else {
    const message = typeof putativeErrorResponse === "object" && putativeErrorResponse !== null && "message" in putativeErrorResponse && typeof putativeErrorResponse.message === "string" ? putativeErrorResponse.message : "Malformed JSON-RPC error with no message attribute";
    out = new SolanaError(SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR, { error: putativeErrorResponse, message });
  }
  safeCaptureStackTrace(out, getSolanaErrorFromJsonRpcError);
  return out;
}
function isRpcErrorResponse(value) {
  return typeof value === "object" && value !== null && "code" in value && "message" in value && (typeof value.code === "number" || typeof value.code === "bigint") && typeof value.message === "string";
}
function unwrapSimulationError(error) {
  const simulationCodes = [
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,
    SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT
  ];
  if (isSolanaError(error) && !!error.cause && simulationCodes.includes(error.context.__code)) {
    return error.cause;
  }
  return error;
}
var SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED, SOLANA_ERROR__INVALID_NONCE, SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND, SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE, SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH, SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE, SOLANA_ERROR__MALFORMED_BIGINT_STRING, SOLANA_ERROR__MALFORMED_NUMBER_STRING, SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE, SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR, SOLANA_ERROR__JSON_RPC__PARSE_ERROR, SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR, SOLANA_ERROR__JSON_RPC__INVALID_PARAMS, SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND, SOLANA_ERROR__JSON_RPC__INVALID_REQUEST, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH, SOLANA_ERROR__JSON_RPC__SCAN_ERROR, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE, SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP, SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH, SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE, SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS, SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY, SOLANA_ERROR__ADDRESSES__MALFORMED_PDA, SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE, SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED, SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE, SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED, SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER, SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS, SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND, SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND, SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT, SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT, SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED, SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT, SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED, SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY, SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED, SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH, SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH, SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH, SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE, SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY, SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS, SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA, SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH, SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN, SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL, SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS, SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID, SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED, SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT, SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION, SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID, SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND, SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED, SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE, SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED, SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX, SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED, SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED, SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING, SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC, SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR, SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED, SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE, SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT, SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID, SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH, SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT, SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED, SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC, SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED, SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION, SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE, SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE, SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE, SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE, SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY, SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR, SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT, SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER, SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW, SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR, SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER, SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED, SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED, SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED, SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS, SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS, SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER, SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER, SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS, SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING, SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED, SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED, SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE, SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE, SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH, SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH, SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO, SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH, SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH, SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY, SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING, SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH, SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE, SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE, SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE, SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES, SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE, SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME, SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME, SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE, SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING, SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE, SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND, SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING, SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING, SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING, SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING, SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING, SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING, SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE, SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION, SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES, SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH, SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT, SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT, SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE, SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN, SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE, SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE, SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND, SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND, SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE, SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED, SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND, SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP, SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX, SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION, SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE, SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE, SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING, SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT, SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT, SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT, SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT, SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS, SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT, SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT, SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT, SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION, SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT, SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED, SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT, SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED, SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED, SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION, SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN, SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE, SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN, SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN, SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED, SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND, SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT, SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH, SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH, SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH, SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH, SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH, SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS, SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE, SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT, SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT, SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE, SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT, SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE, SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE, SOLANA_ERROR__CODECS__INVALID_CONSTANT, SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE, SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL, SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES, SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS, SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY, SOLANA_ERROR__RPC__INTEGER_OVERFLOW, SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT, SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING, SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE, SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING, SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED, SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND, SolanaErrorMessages, START_INDEX, TYPE, SolanaError, ORDERED_ERROR_NAMES, ORDERED_ERROR_NAMES2;
var init_index_node = __esm({
  "node_modules/@solana/errors/dist/index.node.mjs"() {
    "use strict";
    SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED = 1;
    SOLANA_ERROR__INVALID_NONCE = 2;
    SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND = 3;
    SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE = 4;
    SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH = 5;
    SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE = 6;
    SOLANA_ERROR__MALFORMED_BIGINT_STRING = 7;
    SOLANA_ERROR__MALFORMED_NUMBER_STRING = 8;
    SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE = 9;
    SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR = 10;
    SOLANA_ERROR__JSON_RPC__PARSE_ERROR = -32700;
    SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR = -32603;
    SOLANA_ERROR__JSON_RPC__INVALID_PARAMS = -32602;
    SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND = -32601;
    SOLANA_ERROR__JSON_RPC__INVALID_REQUEST = -32600;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE = -32019;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY = -32018;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE = -32017;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED = -32016;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION = -32015;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET = -32014;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH = -32013;
    SOLANA_ERROR__JSON_RPC__SCAN_ERROR = -32012;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE = -32011;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX = -32010;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED = -32009;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT = -32008;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED = -32007;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE = -32006;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY = -32005;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE = -32004;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE = -32003;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE = -32002;
    SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP = -32001;
    SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH = 28e5;
    SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE = 2800001;
    SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS = 2800002;
    SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY = 2800003;
    SOLANA_ERROR__ADDRESSES__MALFORMED_PDA = 2800004;
    SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE = 2800005;
    SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED = 2800006;
    SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED = 2800007;
    SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE = 2800008;
    SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED = 2800009;
    SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER = 2800010;
    SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS = 2800011;
    SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND = 323e4;
    SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND = 32300001;
    SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT = 3230002;
    SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT = 3230003;
    SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED = 3230004;
    SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT = 361e4;
    SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED = 3610001;
    SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED = 3610002;
    SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED = 3610003;
    SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED = 3610004;
    SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED = 3610005;
    SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED = 3610006;
    SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY = 3610007;
    SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED = 3611e3;
    SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH = 3704e3;
    SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH = 3704001;
    SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH = 3704002;
    SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE = 3704003;
    SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY = 3704004;
    SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS = 4128e3;
    SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA = 4128001;
    SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH = 4128002;
    SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN = 4615e3;
    SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR = 4615001;
    SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT = 4615002;
    SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA = 4615003;
    SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA = 4615004;
    SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL = 4615005;
    SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS = 4615006;
    SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID = 4615007;
    SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE = 4615008;
    SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED = 4615009;
    SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT = 4615010;
    SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION = 4615011;
    SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID = 4615012;
    SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND = 4615013;
    SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED = 4615014;
    SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE = 4615015;
    SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED = 4615016;
    SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX = 4615017;
    SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED = 4615018;
    SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED = 4615019;
    SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS = 4615020;
    SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED = 4615021;
    SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE = 4615022;
    SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED = 4615023;
    SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 4615024;
    SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC = 4615025;
    SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM = 4615026;
    SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR = 4615027;
    SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED = 4615028;
    SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE = 4615029;
    SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT = 4615030;
    SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID = 4615031;
    SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH = 4615032;
    SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT = 4615033;
    SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED = 4615034;
    SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED = 4615035;
    SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS = 4615036;
    SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC = 4615037;
    SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED = 4615038;
    SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION = 4615039;
    SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE = 4615040;
    SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE = 4615041;
    SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE = 4615042;
    SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE = 4615043;
    SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY = 4615044;
    SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR = 4615045;
    SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT = 4615046;
    SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER = 4615047;
    SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW = 4615048;
    SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR = 4615049;
    SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER = 4615050;
    SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED = 4615051;
    SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED = 4615052;
    SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED = 4615053;
    SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS = 4615054;
    SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS = 5508e3;
    SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER = 5508001;
    SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER = 5508002;
    SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER = 5508003;
    SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER = 5508004;
    SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER = 5508005;
    SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER = 5508006;
    SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER = 5508007;
    SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER = 5508008;
    SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS = 5508009;
    SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING = 5508010;
    SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED = 5508011;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED = 5607e3;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE = 5607001;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE = 5607002;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH = 5607003;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH = 5607004;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO = 5607005;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED = 5607006;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH = 5607007;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH = 5607008;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY = 5607009;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO = 5607010;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING = 5607011;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH = 5607012;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE = 5607013;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION = 5607014;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED = 5607015;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE = 5607016;
    SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE = 5607017;
    SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES = 5663e3;
    SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE = 5663001;
    SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME = 5663002;
    SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME = 5663003;
    SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE = 5663004;
    SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING = 5663005;
    SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE = 5663006;
    SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND = 5663007;
    SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING = 5663008;
    SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING = 5663009;
    SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING = 5663010;
    SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING = 5663011;
    SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING = 5663012;
    SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING = 5663013;
    SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE = 5663014;
    SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION = 5663015;
    SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES = 5663016;
    SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH = 5663017;
    SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT = 5663018;
    SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT = 5663019;
    SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT = 5663020;
    SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED = 5663021;
    SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE = 5663022;
    SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN = 705e4;
    SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE = 7050001;
    SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE = 7050002;
    SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND = 7050003;
    SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND = 7050004;
    SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE = 7050005;
    SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE = 7050006;
    SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED = 7050007;
    SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND = 7050008;
    SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP = 7050009;
    SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE = 7050010;
    SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX = 7050011;
    SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE = 7050012;
    SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION = 7050013;
    SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE = 7050014;
    SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE = 7050015;
    SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING = 7050016;
    SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT = 7050017;
    SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION = 7050018;
    SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT = 7050019;
    SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT = 7050020;
    SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT = 7050021;
    SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS = 7050022;
    SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND = 7050023;
    SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER = 7050024;
    SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA = 7050025;
    SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX = 7050026;
    SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT = 7050027;
    SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT = 7050028;
    SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT = 7050029;
    SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION = 7050030;
    SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT = 7050031;
    SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED = 7050032;
    SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT = 7050033;
    SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED = 7050034;
    SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED = 7050035;
    SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION = 7050036;
    SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN = 7618e3;
    SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE = 7618001;
    SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN = 7618002;
    SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN = 7618003;
    SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED = 7618004;
    SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND = 7618005;
    SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN = 7618006;
    SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN = 7618007;
    SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT = 7618008;
    SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT = 7618009;
    SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY = 8078e3;
    SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH = 8078001;
    SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH = 8078002;
    SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH = 8078003;
    SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH = 8078004;
    SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH = 8078005;
    SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH = 8078006;
    SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS = 8078007;
    SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE = 8078008;
    SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT = 8078009;
    SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT = 8078010;
    SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE = 8078011;
    SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE = 8078012;
    SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH = 8078013;
    SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE = 8078014;
    SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT = 8078015;
    SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE = 8078016;
    SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE = 8078017;
    SOLANA_ERROR__CODECS__INVALID_CONSTANT = 8078018;
    SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE = 8078019;
    SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL = 8078020;
    SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES = 8078021;
    SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS = 8078022;
    SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY = 8078023;
    SOLANA_ERROR__RPC__INTEGER_OVERFLOW = 81e5;
    SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN = 8100001;
    SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR = 8100002;
    SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD = 8100003;
    SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN = 819e4;
    SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID = 8190001;
    SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED = 8190002;
    SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED = 8190003;
    SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT = 8190004;
    SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING = 99e5;
    SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE = 9900001;
    SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING = 9900002;
    SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE = 9900003;
    SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED = 9900004;
    SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND = 9900005;
    SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND = 9900006;
    SolanaErrorMessages = {
      [SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND]: "Account not found at address: $address",
      [SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED]: "Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",
      [SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT]: "Expected decoded account at address: $address",
      [SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT]: "Failed to decode account data at address: $address",
      [SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND]: "Accounts not found at addresses: $addresses",
      [SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED]: "Unable to find a viable program address bump seed.",
      [SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS]: "$putativeAddress is not a base58-encoded address.",
      [SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH]: "Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",
      [SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY]: "The `CryptoKey` must be an `Ed25519` public key.",
      [SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS]: "$putativeOffCurveAddress is not a base58-encoded off-curve address.",
      [SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE]: "Invalid seeds; point must fall off the Ed25519 curve.",
      [SOLANA_ERROR__ADDRESSES__MALFORMED_PDA]: "Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",
      [SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED]: "A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",
      [SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED]: "The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",
      [SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE]: "Expected program derived address bump to be in the range [0, 255], got: $bump.",
      [SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER]: "Program address cannot end with PDA marker.",
      [SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE]: "Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",
      [SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE]: "Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",
      [SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED]: "The network has progressed past the last block for which this transaction could have been committed.",
      [SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY]: "Codec [$codecDescription] cannot decode empty byte arrays.",
      [SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS]: "Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",
      [SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL]: "Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",
      [SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH]: "Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",
      [SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH]: "Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",
      [SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH]: "Encoder and decoder must either both be fixed-size or variable-size.",
      [SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE]: "Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",
      [SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH]: "Expected a fixed-size codec, got a variable-size one.",
      [SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH]: "Codec [$codecDescription] expected a positive byte length, got $bytesLength.",
      [SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH]: "Expected a variable-size codec, got a fixed-size one.",
      [SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE]: "Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",
      [SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH]: "Codec [$codecDescription] expected $expected bytes, got $bytesLength.",
      [SOLANA_ERROR__CODECS__INVALID_CONSTANT]: "Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",
      [SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT]: "Invalid discriminated union variant. Expected one of [$variants], got $value.",
      [SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT]: "Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",
      [SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT]: "Invalid literal union variant. Expected one of [$variants], got $value.",
      [SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS]: "Expected [$codecDescription] to have $expected items, got $actual.",
      [SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE]: "Invalid value $value for base $base with alphabet $alphabet.",
      [SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE]: "Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",
      [SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE]: "Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",
      [SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE]: "Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",
      [SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES]: "Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",
      [SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE]: "Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",
      [SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY]: "This decoder expected a byte array of exactly $expectedLength bytes, but $numExcessBytes unexpected excess bytes remained after decoding. Are you sure that you have chosen the correct decoder for this data?",
      [SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED]: "No random values implementation could be found.",
      [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED]: "instruction requires an uninitialized account",
      [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED]: "instruction tries to borrow reference for an account which is already borrowed",
      [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]: "instruction left account with an outstanding borrowed reference",
      [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED]: "program other than the account's owner changed the size of the account data",
      [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL]: "account data too small for instruction",
      [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE]: "instruction expected an executable account",
      [SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT]: "An account does not have enough lamports to be rent-exempt",
      [SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW]: "Program arithmetic overflowed",
      [SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR]: "Failed to serialize or deserialize account data: $encodedData",
      [SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS]: "Builtin programs must consume compute units",
      [SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH]: "Cross-program invocation call depth too deep",
      [SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED]: "Computational budget exceeded",
      [SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM]: "custom program error: #$code",
      [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX]: "instruction contains duplicate accounts",
      [SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC]: "instruction modifications of multiply-passed account differ",
      [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT]: "executable accounts must be rent exempt",
      [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED]: "instruction changed executable accounts data",
      [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE]: "instruction changed the balance of an executable account",
      [SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED]: "instruction changed executable bit of an account",
      [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED]: "instruction modified data of an account it does not own",
      [SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND]: "instruction spent from the balance of an account it does not own",
      [SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR]: "generic instruction error",
      [SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER]: "Provided owner is not allowed",
      [SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE]: "Account is immutable",
      [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY]: "Incorrect authority provided",
      [SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID]: "incorrect program id for instruction",
      [SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS]: "insufficient funds for instruction",
      [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA]: "invalid account data for instruction",
      [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER]: "Invalid account owner",
      [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT]: "invalid program argument",
      [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR]: "program returned invalid error code",
      [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA]: "invalid instruction data",
      [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC]: "Failed to reallocate account data",
      [SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS]: "Provided seeds do not result in a valid address",
      [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED]: "Accounts data allocations exceeded the maximum allowed per transaction",
      [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED]: "Max accounts exceeded",
      [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED]: "Max instruction trace length exceeded",
      [SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED]: "Length of the seed is too long for address generation",
      [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT]: "An account required by the instruction is missing",
      [SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE]: "missing required signature for instruction",
      [SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID]: "instruction illegally modified the program id of an account",
      [SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS]: "insufficient account keys for instruction",
      [SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION]: "Cross-program invocation with unauthorized signer or writable account",
      [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE]: "Failed to create program execution environment",
      [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE]: "Program failed to compile",
      [SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE]: "Program failed to complete",
      [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED]: "instruction modified data of a read-only account",
      [SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE]: "instruction changed the balance of a read-only account",
      [SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED]: "Cross-program invocation reentrancy not allowed for this instruction",
      [SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED]: "instruction modified rent epoch of an account",
      [SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION]: "sum of account balances before and after instruction do not match",
      [SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT]: "instruction requires an initialized account",
      [SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN]: "",
      [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID]: "Unsupported program id",
      [SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR]: "Unsupported sysvar",
      [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND]: "Invalid instruction plan kind: $kind.",
      [SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN]: "The provided instruction plan is empty.",
      [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND]: "No failed transaction plan result was found in the provided transaction plan result.",
      [SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED]: "This transaction plan executor does not support non-divisible sequential plans. To support them, you may create your own executor such that multi-transaction atomicity is preserved \u2014 e.g. by targetting RPCs that support transaction bundles.",
      [SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN]: "The provided transaction plan failed to execute. See the `transactionPlanResult` attribute for more details. Note that the `cause` property is deprecated, and a future version will not set it.",
      [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN]: "The provided message has insufficient capacity to accommodate the next instruction(s) in this plan. Expected at least $numBytesRequired free byte(s), got $numFreeBytes byte(s).",
      [SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND]: "Invalid transaction plan kind: $kind.",
      [SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE]: "No more instructions to pack; the message packer has completed the instruction plan.",
      [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN]: "Unexpected instruction plan. Expected $expectedKind plan, got $actualKind plan.",
      [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN]: "Unexpected transaction plan. Expected $expectedKind plan, got $actualKind plan.",
      [SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT]: "Unexpected transaction plan result. Expected $expectedKind plan, got $actualKind plan.",
      [SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT]: "Expected a successful transaction plan result. I.e. there is at least one failed or cancelled transaction in the plan.",
      [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS]: "The instruction does not have any accounts.",
      [SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA]: "The instruction does not have any data.",
      [SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH]: "Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",
      [SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH]: "Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",
      [SOLANA_ERROR__INVALID_NONCE]: "The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",
      [SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING]: "Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",
      [SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED]: "Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",
      [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE]: "Invariant violation: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",
      [SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING]: "Invariant violation: WebSocket message iterator is missing state storage. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",
      [SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE]: "Invariant violation: Switch statement non-exhaustive. Received unexpected value `$unexpectedValue`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",
      [SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR]: "JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",
      [SOLANA_ERROR__JSON_RPC__INVALID_PARAMS]: "JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",
      [SOLANA_ERROR__JSON_RPC__INVALID_REQUEST]: "JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",
      [SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND]: "JSON-RPC error: The method does not exist / is not available ($__serverMessage)",
      [SOLANA_ERROR__JSON_RPC__PARSE_ERROR]: "JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",
      [SOLANA_ERROR__JSON_RPC__SCAN_ERROR]: "$__serverMessage",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP]: "$__serverMessage",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE]: "$__serverMessage",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET]: "$__serverMessage",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE]: "Epoch rewards period still active at slot $slot",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX]: "$__serverMessage",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED]: "$__serverMessage",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE]: "Failed to query long-term storage; please try again",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED]: "Minimum context slot has not been reached",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY]: "Node is unhealthy; behind by $numSlotsBehind slots",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT]: "No snapshot",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE]: "Transaction simulation failed",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY]: "Rewards cannot be found because slot $slot is not the epoch boundary. This may be due to gap in the queried node's local ledger or long-term storage",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED]: "$__serverMessage",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE]: "Transaction history is not available from this node",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE]: "$__serverMessage",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH]: "Transaction signature length mismatch",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE]: "Transaction signature verification failure",
      [SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION]: "$__serverMessage",
      [SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH]: "Key pair bytes must be of length 64, got $byteLength.",
      [SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH]: "Expected private key bytes with length 32. Actual length: $actualLength.",
      [SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH]: "Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",
      [SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY]: "The provided private key does not match the provided public key.",
      [SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE]: "Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",
      [SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE]: "Lamports value must be in the range [0, 2e64-1]",
      [SOLANA_ERROR__MALFORMED_BIGINT_STRING]: "`$value` cannot be parsed as a `BigInt`",
      [SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR]: "$message",
      [SOLANA_ERROR__MALFORMED_NUMBER_STRING]: "`$value` cannot be parsed as a `Number`",
      [SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND]: "No nonce account could be found at address `$nonceAccountAddress`",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH]: "Expected base58 encoded application domain to decode to a byte array of length 32. Actual length: $actualLength.",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE]: "Attempted to sign an offchain message with an address that is not a signer for it",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE]: "Expected base58-encoded application domain string of length in the range [32, 44]. Actual length: $actualLength.",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH]: "The signer addresses in this offchain message envelope do not match the list of required signers in the message preamble. These unexpected signers were present in the envelope: `[$unexpectedSigners]`. These required signers were missing from the envelope `[$missingSigners]`.",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED]: "The message body provided has a byte-length of $actualBytes. The maximum allowable byte-length is $maxBytes",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH]: "Expected message format $expectedMessageFormat, got $actualMessageFormat",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH]: "The message length specified in the message preamble is $specifiedLength bytes. The actual length of the message is $actualLength bytes.",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY]: "Offchain message content must be non-empty",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO]: "Offchain message must specify the address of at least one required signer",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO]: "Offchain message envelope must reserve space for at least one signature",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH]: "The offchain message preamble specifies $numRequiredSignatures required signature(s), got $signaturesLength.",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED]: "The signatories of this offchain message must be listed in lexicographical order",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE]: "An address must be listed no more than once among the signatories of an offchain message",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING]: "Offchain message is missing signatures for addresses: $addresses.",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE]: "Offchain message signature verification failed. Signature mismatch for required signatories [$signatoriesWithInvalidSignatures]. Missing signatures for signatories [$signatoriesWithMissingSignatures]",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE]: "The message body provided contains characters whose codes fall outside the allowed range. In order to ensure clear-signing compatiblity with hardware wallets, the message may only contain line feeds and characters in the range [\\x20-\\x7e].",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION]: "Expected offchain message version $expectedVersion. Got $actualVersion.",
      [SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED]: "This version of Kit does not support decoding offchain messages with version $unsupportedVersion. The current max supported version is 0.",
      [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN]: "The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",
      [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED]: "WebSocket was closed before payload could be added to the send buffer",
      [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED]: "WebSocket connection closed",
      [SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT]: "WebSocket failed to connect",
      [SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID]: "Failed to obtain a subscription id from the server",
      [SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD]: "Could not find an API plan for RPC method: `$method`",
      [SOLANA_ERROR__RPC__INTEGER_OVERFLOW]: "The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was `$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds `Number.MAX_SAFE_INTEGER`.",
      [SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR]: "HTTP error ($statusCode): $message",
      [SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN]: "HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",
      [SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS]: "Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",
      [SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER]: "The provided value does not implement the `KeyPairSigner` interface",
      [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER]: "The provided value does not implement the `MessageModifyingSigner` interface",
      [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER]: "The provided value does not implement the `MessagePartialSigner` interface",
      [SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER]: "The provided value does not implement any of the `MessageSigner` interfaces",
      [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER]: "The provided value does not implement the `TransactionModifyingSigner` interface",
      [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER]: "The provided value does not implement the `TransactionPartialSigner` interface",
      [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER]: "The provided value does not implement the `TransactionSendingSigner` interface",
      [SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER]: "The provided value does not implement any of the `TransactionSigner` interfaces",
      [SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS]: "More than one `TransactionSendingSigner` was identified.",
      [SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING]: "No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",
      [SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED]: "Wallet account signers do not support signing multiple messages/transactions in a single operation",
      [SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY]: "Cannot export a non-extractable key.",
      [SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED]: "No digest implementation could be found.",
      [SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT]: "Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",
      [SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED]: "This runtime does not support the generation of Ed25519 key pairs.\n\nInstall @solana/webcrypto-ed25519-polyfill and call its `install` function before generating keys in environments that do not support Ed25519.\n\nFor a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20.",
      [SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED]: "No signature verification implementation could be found.",
      [SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED]: "No key generation implementation could be found.",
      [SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED]: "No signing implementation could be found.",
      [SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED]: "No key export implementation could be found.",
      [SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE]: "Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",
      [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING]: "Transaction processing left an account with an outstanding borrowed reference",
      [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE]: "Account in use",
      [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE]: "Account loaded twice",
      [SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND]: "Attempt to debit an account but found no record of a prior credit.",
      [SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND]: "Transaction loads an address table account that doesn't exist",
      [SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED]: "This transaction has already been processed",
      [SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND]: "Blockhash not found",
      [SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP]: "Loader call chain is too deep",
      [SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE]: "Transactions are currently disabled due to cluster maintenance",
      [SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION]: "Transaction contains a duplicate instruction ($index) that is not allowed",
      [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE]: "Insufficient funds for fee",
      [SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT]: "Transaction results in an account ($accountIndex) with insufficient funds for rent",
      [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE]: "This account may not be used to pay transaction fees",
      [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX]: "Transaction contains an invalid account reference",
      [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA]: "Transaction loads an address table account with invalid data",
      [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX]: "Transaction address table lookup uses an invalid index",
      [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER]: "Transaction loads an address table account with an invalid owner",
      [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT]: "LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",
      [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION]: "This program may not be used for executing instructions",
      [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT]: "Transaction leaves an account with a lower balance than rent-exempt minimum",
      [SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT]: "Transaction loads a writable account that cannot be written",
      [SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED]: "Transaction exceeded max loaded accounts data size cap",
      [SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE]: "Transaction requires a fee but has no signature present",
      [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND]: "Attempt to load a program that does not exist",
      [SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED]: "Execution of the program referenced by account at index $accountIndex is temporarily restricted.",
      [SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED]: "ResanitizationNeeded",
      [SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE]: "Transaction failed to sanitize accounts offsets correctly",
      [SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE]: "Transaction did not pass signature verification",
      [SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS]: "Transaction locked too many accounts",
      [SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION]: "Sum of account balances before and after transaction do not match",
      [SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN]: "The transaction failed with the error `$errorName`",
      [SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION]: "Transaction version is unsupported",
      [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT]: "Transaction would exceed account data limit within the block",
      [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT]: "Transaction would exceed total account data limit",
      [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT]: "Transaction would exceed max account limit within the block",
      [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT]: "Transaction would exceed max Block Cost Limit",
      [SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT]: "Transaction would exceed max Vote Cost Limit",
      [SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION]: "Attempted to sign a transaction with an address that is not a signer for it",
      [SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING]: "Transaction is missing an address at index: $index.",
      [SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES]: "Transaction has no expected signers therefore it cannot be encoded",
      [SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT]: "Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",
      [SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME]: "Transaction does not have a blockhash lifetime",
      [SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME]: "Transaction is not a durable nonce transaction",
      [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING]: "Contents of these address lookup tables unknown: $lookupTableAddresses",
      [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE]: "Lookup of address at index $highestRequestedIndex failed for lookup table `$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table may have been extended since its contents were retrieved",
      [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING]: "No fee payer set in CompiledTransaction",
      [SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND]: "Could not find program address at index $index",
      [SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT]: "Failed to estimate the compute unit consumption for this transaction message. This is likely because simulating the transaction failed. Inspect the `cause` property of this error to learn more",
      [SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT]: "Transaction failed when it was simulated in order to estimate the compute unit consumption. The compute unit estimate provided is for a transaction that failed when simulated and may not be representative of the compute units this transaction would consume if successful. Inspect the `cause` property of this error to learn more",
      [SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING]: "Transaction is missing a fee payer.",
      [SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING]: "Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",
      [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE]: "Transaction first instruction is not advance nonce account instruction.",
      [SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING]: "Transaction with no instructions cannot be durable nonce transaction.",
      [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES]: "This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",
      [SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE]: "This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",
      [SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH]: "The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.",
      [SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING]: "Transaction is missing signatures for addresses: $addresses.",
      [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE]: "Transaction version must be in the range [0, 127]. `$actualVersion` given",
      [SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED]: "This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.",
      [SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE]: "The transaction has a durable nonce lifetime (with nonce `$nonce`), but the nonce account address is in a lookup table. The lifetime constraint cannot be constructed without fetching the lookup tables for the transaction."
    };
    START_INDEX = "i";
    TYPE = "t";
    SolanaError = class extends Error {
      /**
       * Indicates the root cause of this {@link SolanaError}, if any.
       *
       * For example, a transaction error might have an instruction error as its root cause. In this
       * case, you will be able to access the instruction error on the transaction error as `cause`.
       */
      cause = this.cause;
      /**
       * Contains context that can assist in understanding or recovering from a {@link SolanaError}.
       */
      context;
      constructor(...[code, contextAndErrorOptions]) {
        let context;
        let errorOptions;
        if (contextAndErrorOptions) {
          Object.entries(Object.getOwnPropertyDescriptors(contextAndErrorOptions)).forEach(([name, descriptor]) => {
            if (name === "cause") {
              errorOptions = { cause: descriptor.value };
            } else {
              if (context === void 0) {
                context = {
                  __code: code
                };
              }
              Object.defineProperty(context, name, descriptor);
            }
          });
        }
        const message = getErrorMessage(code, context);
        super(message, errorOptions);
        this.context = Object.freeze(
          context === void 0 ? {
            __code: code
          } : context
        );
        this.name = "SolanaError";
      }
    };
    ORDERED_ERROR_NAMES = [
      // Keep synced with RPC source: https://github.com/anza-xyz/solana-sdk/blob/master/instruction-error/src/lib.rs
      // If this list ever gets too large, consider implementing a compression strategy like this:
      // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47
      "GenericError",
      "InvalidArgument",
      "InvalidInstructionData",
      "InvalidAccountData",
      "AccountDataTooSmall",
      "InsufficientFunds",
      "IncorrectProgramId",
      "MissingRequiredSignature",
      "AccountAlreadyInitialized",
      "UninitializedAccount",
      "UnbalancedInstruction",
      "ModifiedProgramId",
      "ExternalAccountLamportSpend",
      "ExternalAccountDataModified",
      "ReadonlyLamportChange",
      "ReadonlyDataModified",
      "DuplicateAccountIndex",
      "ExecutableModified",
      "RentEpochModified",
      "NotEnoughAccountKeys",
      "AccountDataSizeChanged",
      "AccountNotExecutable",
      "AccountBorrowFailed",
      "AccountBorrowOutstanding",
      "DuplicateAccountOutOfSync",
      "Custom",
      "InvalidError",
      "ExecutableDataModified",
      "ExecutableLamportChange",
      "ExecutableAccountNotRentExempt",
      "UnsupportedProgramId",
      "CallDepth",
      "MissingAccount",
      "ReentrancyNotAllowed",
      "MaxSeedLengthExceeded",
      "InvalidSeeds",
      "InvalidRealloc",
      "ComputationalBudgetExceeded",
      "PrivilegeEscalation",
      "ProgramEnvironmentSetupFailure",
      "ProgramFailedToComplete",
      "ProgramFailedToCompile",
      "Immutable",
      "IncorrectAuthority",
      "BorshIoError",
      "AccountNotRentExempt",
      "InvalidAccountOwner",
      "ArithmeticOverflow",
      "UnsupportedSysvar",
      "IllegalOwner",
      "MaxAccountsDataAllocationsExceeded",
      "MaxAccountsExceeded",
      "MaxInstructionTraceLengthExceeded",
      "BuiltinProgramsMustConsumeComputeUnits"
    ];
    ORDERED_ERROR_NAMES2 = [
      // Keep synced with RPC source: https://github.com/anza-xyz/agave/blob/master/sdk/src/transaction/error.rs
      // If this list ever gets too large, consider implementing a compression strategy like this:
      // https://gist.github.com/steveluscher/aaa7cbbb5433b1197983908a40860c47
      "AccountInUse",
      "AccountLoadedTwice",
      "AccountNotFound",
      "ProgramAccountNotFound",
      "InsufficientFundsForFee",
      "InvalidAccountForFee",
      "AlreadyProcessed",
      "BlockhashNotFound",
      // `InstructionError` intentionally omitted; delegated to `getSolanaErrorFromInstructionError`
      "CallChainTooDeep",
      "MissingSignatureForFee",
      "InvalidAccountIndex",
      "SignatureFailure",
      "InvalidProgramForExecution",
      "SanitizeFailure",
      "ClusterMaintenance",
      "AccountBorrowOutstanding",
      "WouldExceedMaxBlockCostLimit",
      "UnsupportedVersion",
      "InvalidWritableAccount",
      "WouldExceedMaxAccountCostLimit",
      "WouldExceedAccountDataBlockLimit",
      "TooManyAccountLocks",
      "AddressLookupTableNotFound",
      "InvalidAddressLookupTableOwner",
      "InvalidAddressLookupTableData",
      "InvalidAddressLookupTableIndex",
      "InvalidRentPayingAccount",
      "WouldExceedMaxVoteCostLimit",
      "WouldExceedAccountDataTotalLimit",
      "DuplicateInstruction",
      "InsufficientFundsForRent",
      "MaxLoadedAccountsDataSizeExceeded",
      "InvalidLoadedAccountsDataSizeLimit",
      "ResanitizationNeeded",
      "ProgramExecutionTemporarilyRestricted",
      "UnbalancedTransaction"
    ];
  }
});

// node_modules/@solana/codecs-core/dist/index.node.mjs
function padBytes2(bytes, length) {
  if (bytes.length >= length) return bytes;
  const paddedBytes = new Uint8Array(length).fill(0);
  paddedBytes.set(bytes);
  return paddedBytes;
}
function containsBytes(data, bytes, offset) {
  const slice4 = offset === 0 && data.length === bytes.length ? data : data.slice(offset, offset + bytes.length);
  return bytesEqual(slice4, bytes);
}
function bytesEqual(bytes1, bytes2) {
  return bytes1.length === bytes2.length && bytes1.every((value, index2) => value === bytes2[index2]);
}
function getEncodedSize(value, encoder5) {
  return "fixedSize" in encoder5 ? encoder5.fixedSize : encoder5.getSizeFromValue(value);
}
function createEncoder(encoder5) {
  return Object.freeze({
    ...encoder5,
    encode: (value) => {
      const bytes = new Uint8Array(getEncodedSize(value, encoder5));
      encoder5.write(value, bytes, 0);
      return bytes;
    }
  });
}
function createDecoder(decoder2) {
  return Object.freeze({
    ...decoder2,
    decode: (bytes, offset = 0) => decoder2.read(bytes, offset)[0]
  });
}
function createCodec(codec) {
  return Object.freeze({
    ...codec,
    decode: (bytes, offset = 0) => codec.read(bytes, offset)[0],
    encode: (value) => {
      const bytes = new Uint8Array(getEncodedSize(value, codec));
      codec.write(value, bytes, 0);
      return bytes;
    }
  });
}
function isFixedSize(codec) {
  return "fixedSize" in codec && typeof codec.fixedSize === "number";
}
function assertIsFixedSize(codec) {
  if (!isFixedSize(codec)) {
    throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH);
  }
}
function isVariableSize(codec) {
  return !isFixedSize(codec);
}
function assertIsVariableSize(codec) {
  if (!isVariableSize(codec)) {
    throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH);
  }
}
function combineCodec(encoder5, decoder2) {
  if (isFixedSize(encoder5) !== isFixedSize(decoder2)) {
    throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH);
  }
  if (isFixedSize(encoder5) && isFixedSize(decoder2) && encoder5.fixedSize !== decoder2.fixedSize) {
    throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH, {
      decoderFixedSize: decoder2.fixedSize,
      encoderFixedSize: encoder5.fixedSize
    });
  }
  if (!isFixedSize(encoder5) && !isFixedSize(decoder2) && encoder5.maxSize !== decoder2.maxSize) {
    throw new SolanaError(SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH, {
      decoderMaxSize: decoder2.maxSize,
      encoderMaxSize: encoder5.maxSize
    });
  }
  return {
    ...decoder2,
    ...encoder5,
    decode: decoder2.decode,
    encode: encoder5.encode,
    read: decoder2.read,
    write: encoder5.write
  };
}
function addEncoderSentinel(encoder5, sentinel) {
  const write = ((value, bytes, offset) => {
    const encoderBytes = encoder5.encode(value);
    if (findSentinelIndex(encoderBytes, sentinel) >= 0) {
      throw new SolanaError(SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL, {
        encodedBytes: encoderBytes,
        hexEncodedBytes: hexBytes(encoderBytes),
        hexSentinel: hexBytes(sentinel),
        sentinel
      });
    }
    bytes.set(encoderBytes, offset);
    offset += encoderBytes.length;
    bytes.set(sentinel, offset);
    offset += sentinel.length;
    return offset;
  });
  if (isFixedSize(encoder5)) {
    return createEncoder({ ...encoder5, fixedSize: encoder5.fixedSize + sentinel.length, write });
  }
  return createEncoder({
    ...encoder5,
    ...encoder5.maxSize != null ? { maxSize: encoder5.maxSize + sentinel.length } : {},
    getSizeFromValue: (value) => encoder5.getSizeFromValue(value) + sentinel.length,
    write
  });
}
function addDecoderSentinel(decoder2, sentinel) {
  const read = ((bytes, offset) => {
    const candidateBytes = offset === 0 ? bytes : bytes.slice(offset);
    const sentinelIndex = findSentinelIndex(candidateBytes, sentinel);
    if (sentinelIndex === -1) {
      throw new SolanaError(SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES, {
        decodedBytes: candidateBytes,
        hexDecodedBytes: hexBytes(candidateBytes),
        hexSentinel: hexBytes(sentinel),
        sentinel
      });
    }
    const preSentinelBytes = candidateBytes.slice(0, sentinelIndex);
    return [decoder2.decode(preSentinelBytes), offset + preSentinelBytes.length + sentinel.length];
  });
  if (isFixedSize(decoder2)) {
    return createDecoder({ ...decoder2, fixedSize: decoder2.fixedSize + sentinel.length, read });
  }
  return createDecoder({
    ...decoder2,
    ...decoder2.maxSize != null ? { maxSize: decoder2.maxSize + sentinel.length } : {},
    read
  });
}
function addCodecSentinel(codec, sentinel) {
  return combineCodec(addEncoderSentinel(codec, sentinel), addDecoderSentinel(codec, sentinel));
}
function findSentinelIndex(bytes, sentinel) {
  return bytes.findIndex((byte, index2, arr) => {
    if (sentinel.length === 1) return byte === sentinel[0];
    return containsBytes(arr, sentinel, index2);
  });
}
function hexBytes(bytes) {
  return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
}
function assertByteArrayIsNotEmptyForCodec(codecDescription, bytes, offset = 0) {
  if (bytes.length - offset <= 0) {
    throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY, {
      codecDescription
    });
  }
}
function assertByteArrayHasEnoughBytesForCodec(codecDescription, expected, bytes, offset = 0) {
  const bytesLength = bytes.length - offset;
  if (bytesLength < expected) {
    throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH, {
      bytesLength,
      codecDescription,
      expected
    });
  }
}
function assertByteArrayOffsetIsNotOutOfRange(codecDescription, offset, bytesLength) {
  if (offset < 0 || offset > bytesLength) {
    throw new SolanaError(SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE, {
      bytesLength,
      codecDescription,
      offset
    });
  }
}
function addEncoderSizePrefix(encoder5, prefix) {
  const write = ((value, bytes, offset) => {
    const encoderBytes = encoder5.encode(value);
    offset = prefix.write(encoderBytes.length, bytes, offset);
    bytes.set(encoderBytes, offset);
    return offset + encoderBytes.length;
  });
  if (isFixedSize(prefix) && isFixedSize(encoder5)) {
    return createEncoder({ ...encoder5, fixedSize: prefix.fixedSize + encoder5.fixedSize, write });
  }
  const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : prefix.maxSize ?? null;
  const encoderMaxSize = isFixedSize(encoder5) ? encoder5.fixedSize : encoder5.maxSize ?? null;
  const maxSize = prefixMaxSize !== null && encoderMaxSize !== null ? prefixMaxSize + encoderMaxSize : null;
  return createEncoder({
    ...encoder5,
    ...maxSize !== null ? { maxSize } : {},
    getSizeFromValue: (value) => {
      const encoderSize = getEncodedSize(value, encoder5);
      return getEncodedSize(encoderSize, prefix) + encoderSize;
    },
    write
  });
}
function addDecoderSizePrefix(decoder2, prefix) {
  const read = ((bytes, offset) => {
    const [bigintSize, decoderOffset] = prefix.read(bytes, offset);
    const size5 = Number(bigintSize);
    offset = decoderOffset;
    if (offset > 0 || bytes.length > size5) {
      bytes = bytes.slice(offset, offset + size5);
    }
    assertByteArrayHasEnoughBytesForCodec("addDecoderSizePrefix", size5, bytes);
    return [decoder2.decode(bytes), offset + size5];
  });
  if (isFixedSize(prefix) && isFixedSize(decoder2)) {
    return createDecoder({ ...decoder2, fixedSize: prefix.fixedSize + decoder2.fixedSize, read });
  }
  const prefixMaxSize = isFixedSize(prefix) ? prefix.fixedSize : prefix.maxSize ?? null;
  const decoderMaxSize = isFixedSize(decoder2) ? decoder2.fixedSize : decoder2.maxSize ?? null;
  const maxSize = prefixMaxSize !== null && decoderMaxSize !== null ? prefixMaxSize + decoderMaxSize : null;
  return createDecoder({ ...decoder2, ...maxSize !== null ? { maxSize } : {}, read });
}
function addCodecSizePrefix(codec, prefix) {
  return combineCodec(addEncoderSizePrefix(codec, prefix), addDecoderSizePrefix(codec, prefix));
}
function toArrayBuffer(bytes, offset, length) {
  const bytesOffset = bytes.byteOffset + (offset ?? 0);
  const bytesLength = length ?? bytes.byteLength;
  let buffer2;
  if (typeof SharedArrayBuffer === "undefined") {
    buffer2 = bytes.buffer;
  } else if (bytes.buffer instanceof SharedArrayBuffer) {
    buffer2 = new ArrayBuffer(bytes.length);
    new Uint8Array(buffer2).set(new Uint8Array(bytes));
  } else {
    buffer2 = bytes.buffer;
  }
  return (bytesOffset === 0 || bytesOffset === -bytes.byteLength) && bytesLength === bytes.byteLength ? buffer2 : buffer2.slice(bytesOffset, bytesOffset + bytesLength);
}
function createDecoderThatConsumesEntireByteArray(decoder2) {
  return createDecoder({
    ...decoder2,
    read(bytes, offset) {
      const [value, newOffset] = decoder2.read(bytes, offset);
      if (bytes.length > newOffset) {
        throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY, {
          expectedLength: newOffset,
          numExcessBytes: bytes.length - newOffset
        });
      }
      return [value, newOffset];
    }
  });
}
function fixEncoderSize(encoder5, fixedBytes) {
  return createEncoder({
    fixedSize: fixedBytes,
    write: (value, bytes, offset) => {
      const variableByteArray = encoder5.encode(value);
      const fixedByteArray = variableByteArray.length > fixedBytes ? variableByteArray.slice(0, fixedBytes) : variableByteArray;
      bytes.set(fixedByteArray, offset);
      return offset + fixedBytes;
    }
  });
}
function fixDecoderSize(decoder2, fixedBytes) {
  return createDecoder({
    fixedSize: fixedBytes,
    read: (bytes, offset) => {
      assertByteArrayHasEnoughBytesForCodec("fixCodecSize", fixedBytes, bytes, offset);
      if (offset > 0 || bytes.length > fixedBytes) {
        bytes = bytes.slice(offset, offset + fixedBytes);
      }
      if (isFixedSize(decoder2)) {
        bytes = fixBytes(bytes, decoder2.fixedSize);
      }
      const [value] = decoder2.read(bytes, 0);
      return [value, offset + fixedBytes];
    }
  });
}
function fixCodecSize(codec, fixedBytes) {
  return combineCodec(fixEncoderSize(codec, fixedBytes), fixDecoderSize(codec, fixedBytes));
}
function offsetEncoder(encoder5, config) {
  return createEncoder({
    ...encoder5,
    write: (value, bytes, preOffset) => {
      const wrapBytes = (offset) => modulo(offset, bytes.length);
      const newPreOffset = config.preOffset ? config.preOffset({ bytes, preOffset, wrapBytes }) : preOffset;
      assertByteArrayOffsetIsNotOutOfRange("offsetEncoder", newPreOffset, bytes.length);
      const postOffset = encoder5.write(value, bytes, newPreOffset);
      const newPostOffset = config.postOffset ? config.postOffset({ bytes, newPreOffset, postOffset, preOffset, wrapBytes }) : postOffset;
      assertByteArrayOffsetIsNotOutOfRange("offsetEncoder", newPostOffset, bytes.length);
      return newPostOffset;
    }
  });
}
function offsetDecoder(decoder2, config) {
  return createDecoder({
    ...decoder2,
    read: (bytes, preOffset) => {
      const wrapBytes = (offset) => modulo(offset, bytes.length);
      const newPreOffset = config.preOffset ? config.preOffset({ bytes, preOffset, wrapBytes }) : preOffset;
      assertByteArrayOffsetIsNotOutOfRange("offsetDecoder", newPreOffset, bytes.length);
      const [value, postOffset] = decoder2.read(bytes, newPreOffset);
      const newPostOffset = config.postOffset ? config.postOffset({ bytes, newPreOffset, postOffset, preOffset, wrapBytes }) : postOffset;
      assertByteArrayOffsetIsNotOutOfRange("offsetDecoder", newPostOffset, bytes.length);
      return [value, newPostOffset];
    }
  });
}
function offsetCodec(codec, config) {
  return combineCodec(offsetEncoder(codec, config), offsetDecoder(codec, config));
}
function modulo(dividend, divisor) {
  if (divisor === 0) return 0;
  return (dividend % divisor + divisor) % divisor;
}
function resizeEncoder(encoder5, resize) {
  if (isFixedSize(encoder5)) {
    const fixedSize = resize(encoder5.fixedSize);
    if (fixedSize < 0) {
      throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {
        bytesLength: fixedSize,
        codecDescription: "resizeEncoder"
      });
    }
    return createEncoder({ ...encoder5, fixedSize });
  }
  return createEncoder({
    ...encoder5,
    getSizeFromValue: (value) => {
      const newSize = resize(encoder5.getSizeFromValue(value));
      if (newSize < 0) {
        throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {
          bytesLength: newSize,
          codecDescription: "resizeEncoder"
        });
      }
      return newSize;
    }
  });
}
function resizeDecoder(decoder2, resize) {
  if (isFixedSize(decoder2)) {
    const fixedSize = resize(decoder2.fixedSize);
    if (fixedSize < 0) {
      throw new SolanaError(SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH, {
        bytesLength: fixedSize,
        codecDescription: "resizeDecoder"
      });
    }
    return createDecoder({ ...decoder2, fixedSize });
  }
  return decoder2;
}
function resizeCodec(codec, resize) {
  return combineCodec(resizeEncoder(codec, resize), resizeDecoder(codec, resize));
}
function padLeftEncoder(encoder5, offset) {
  return offsetEncoder(
    resizeEncoder(encoder5, (size5) => size5 + offset),
    { preOffset: ({ preOffset }) => preOffset + offset }
  );
}
function padRightEncoder(encoder5, offset) {
  return offsetEncoder(
    resizeEncoder(encoder5, (size5) => size5 + offset),
    { postOffset: ({ postOffset }) => postOffset + offset }
  );
}
function padLeftDecoder(decoder2, offset) {
  return offsetDecoder(
    resizeDecoder(decoder2, (size5) => size5 + offset),
    { preOffset: ({ preOffset }) => preOffset + offset }
  );
}
function padRightDecoder(decoder2, offset) {
  return offsetDecoder(
    resizeDecoder(decoder2, (size5) => size5 + offset),
    { postOffset: ({ postOffset }) => postOffset + offset }
  );
}
function padLeftCodec(codec, offset) {
  return combineCodec(padLeftEncoder(codec, offset), padLeftDecoder(codec, offset));
}
function padRightCodec(codec, offset) {
  return combineCodec(padRightEncoder(codec, offset), padRightDecoder(codec, offset));
}
function copySourceToTargetInReverse(source, target_WILL_MUTATE, sourceOffset, sourceLength, targetOffset = 0) {
  while (sourceOffset < --sourceLength) {
    const leftValue = source[sourceOffset];
    target_WILL_MUTATE[sourceOffset + targetOffset] = source[sourceLength];
    target_WILL_MUTATE[sourceLength + targetOffset] = leftValue;
    sourceOffset++;
  }
  if (sourceOffset === sourceLength) {
    target_WILL_MUTATE[sourceOffset + targetOffset] = source[sourceOffset];
  }
}
function reverseEncoder(encoder5) {
  assertIsFixedSize(encoder5);
  return createEncoder({
    ...encoder5,
    write: (value, bytes, offset) => {
      const newOffset = encoder5.write(value, bytes, offset);
      copySourceToTargetInReverse(
        bytes,
        bytes,
        offset,
        offset + encoder5.fixedSize
      );
      return newOffset;
    }
  });
}
function reverseDecoder(decoder2) {
  assertIsFixedSize(decoder2);
  return createDecoder({
    ...decoder2,
    read: (bytes, offset) => {
      const reversedBytes = bytes.slice();
      copySourceToTargetInReverse(
        bytes,
        reversedBytes,
        offset,
        offset + decoder2.fixedSize
      );
      return decoder2.read(reversedBytes, offset);
    }
  });
}
function reverseCodec(codec) {
  return combineCodec(reverseEncoder(codec), reverseDecoder(codec));
}
function transformEncoder(encoder5, unmap) {
  return createEncoder({
    ...isVariableSize(encoder5) ? { ...encoder5, getSizeFromValue: (value) => encoder5.getSizeFromValue(unmap(value)) } : encoder5,
    write: (value, bytes, offset) => encoder5.write(unmap(value), bytes, offset)
  });
}
function transformDecoder(decoder2, map) {
  return createDecoder({
    ...decoder2,
    read: (bytes, offset) => {
      const [value, newOffset] = decoder2.read(bytes, offset);
      return [map(value, bytes, offset), newOffset];
    }
  });
}
function transformCodec(codec, unmap, map) {
  return createCodec({
    ...transformEncoder(codec, unmap),
    read: map ? transformDecoder(codec, map).read : codec.read
  });
}
var mergeBytes, fixBytes;
var init_index_node2 = __esm({
  "node_modules/@solana/codecs-core/dist/index.node.mjs"() {
    "use strict";
    init_index_node();
    mergeBytes = (byteArrays) => {
      const nonEmptyByteArrays = byteArrays.filter((arr) => arr.length);
      if (nonEmptyByteArrays.length === 0) {
        return byteArrays.length ? byteArrays[0] : new Uint8Array();
      }
      if (nonEmptyByteArrays.length === 1) {
        return nonEmptyByteArrays[0];
      }
      const totalLength = nonEmptyByteArrays.reduce((total, arr) => total + arr.length, 0);
      const result = new Uint8Array(totalLength);
      let offset = 0;
      nonEmptyByteArrays.forEach((arr) => {
        result.set(arr, offset);
        offset += arr.length;
      });
      return result;
    };
    fixBytes = (bytes, length) => padBytes2(bytes.length <= length ? bytes : bytes.slice(0, length), length);
  }
});

// node_modules/@solana/codecs-strings/dist/index.node.mjs
function assertValidBaseString(alphabet4, testValue, givenValue = testValue) {
  if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) {
    throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {
      alphabet: alphabet4,
      base: alphabet4.length,
      value: givenValue
    });
  }
}
function partitionLeadingZeroes(value, zeroCharacter) {
  const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));
  return [leadingZeros, tailChars];
}
function getBigIntFromBaseX(value, alphabet4) {
  const base2 = BigInt(alphabet4.length);
  let sum = 0n;
  for (const char of value) {
    sum *= base2;
    sum += BigInt(alphabet4.indexOf(char));
  }
  return sum;
}
function getBaseXFromBigInt(value, alphabet4) {
  const base2 = BigInt(alphabet4.length);
  const tailChars = [];
  while (value > 0n) {
    tailChars.unshift(alphabet4[Number(value % base2)]);
    value /= base2;
  }
  return tailChars.join("");
}
function charCodeToBase163(char) {
  if (char >= 48 && char <= 57) return char - 48;
  if (char >= 65 && char <= 70) return char - (65 - 10);
  if (char >= 97 && char <= 102) return char - (97 - 10);
}
function reslice(input, inputBits, outputBits, useRemainder) {
  const output = [];
  let accumulator = 0;
  let bitsInAccumulator = 0;
  const mask = (1 << outputBits) - 1;
  for (const value of input) {
    accumulator = accumulator << inputBits | value;
    bitsInAccumulator += inputBits;
    while (bitsInAccumulator >= outputBits) {
      bitsInAccumulator -= outputBits;
      output.push(accumulator >> bitsInAccumulator & mask);
    }
  }
  if (useRemainder && bitsInAccumulator > 0) {
    output.push(accumulator << outputBits - bitsInAccumulator & mask);
  }
  return output;
}
var getBaseXEncoder, getBaseXDecoder, getBaseXCodec, alphabet3, getBase10Encoder, getBase10Decoder, getBase10Codec, INVALID_STRING_ERROR_BASE_CONFIG, getBase16Encoder, getBase16Decoder, getBase16Codec, alphabet22, getBase58Encoder, getBase58Decoder, getBase58Codec, getBaseXResliceEncoder, getBaseXResliceDecoder, getBaseXResliceCodec, alphabet32, getBase64Encoder, getBase64Decoder, getBase64Codec, removeNullCharacters, padNullCharacters, e, o, getUtf8Encoder, getUtf8Decoder, getUtf8Codec;
var init_index_node3 = __esm({
  "node_modules/@solana/codecs-strings/dist/index.node.mjs"() {
    "use strict";
    init_index_node();
    init_index_node2();
    getBaseXEncoder = (alphabet4) => {
      return createEncoder({
        getSizeFromValue: (value) => {
          const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);
          if (!tailChars) return value.length;
          const base10Number = getBigIntFromBaseX(tailChars, alphabet4);
          return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);
        },
        write(value, bytes, offset) {
          assertValidBaseString(alphabet4, value);
          if (value === "") return offset;
          const [leadingZeroes, tailChars] = partitionLeadingZeroes(value, alphabet4[0]);
          if (!tailChars) {
            bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);
            return offset + leadingZeroes.length;
          }
          let base10Number = getBigIntFromBaseX(tailChars, alphabet4);
          const tailBytes = [];
          while (base10Number > 0n) {
            tailBytes.unshift(Number(base10Number % 256n));
            base10Number /= 256n;
          }
          const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];
          bytes.set(bytesToAdd, offset);
          return offset + bytesToAdd.length;
        }
      });
    };
    getBaseXDecoder = (alphabet4) => {
      return createDecoder({
        read(rawBytes, offset) {
          const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);
          if (bytes.length === 0) return ["", 0];
          let trailIndex = bytes.findIndex((n) => n !== 0);
          trailIndex = trailIndex === -1 ? bytes.length : trailIndex;
          const leadingZeroes = alphabet4[0].repeat(trailIndex);
          if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];
          const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);
          const tailChars = getBaseXFromBigInt(base10Number, alphabet4);
          return [leadingZeroes + tailChars, rawBytes.length];
        }
      });
    };
    getBaseXCodec = (alphabet4) => combineCodec(getBaseXEncoder(alphabet4), getBaseXDecoder(alphabet4));
    alphabet3 = "0123456789";
    getBase10Encoder = () => getBaseXEncoder(alphabet3);
    getBase10Decoder = () => getBaseXDecoder(alphabet3);
    getBase10Codec = () => getBaseXCodec(alphabet3);
    INVALID_STRING_ERROR_BASE_CONFIG = {
      alphabet: "0123456789abcdef",
      base: 16
    };
    getBase16Encoder = () => createEncoder({
      getSizeFromValue: (value) => Math.ceil(value.length / 2),
      write(value, bytes, offset) {
        const len = value.length;
        const al = len / 2;
        if (len === 1) {
          const c = value.charCodeAt(0);
          const n = charCodeToBase163(c);
          if (n === void 0) {
            throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {
              ...INVALID_STRING_ERROR_BASE_CONFIG,
              value
            });
          }
          bytes.set([n], offset);
          return 1 + offset;
        }
        const hexBytes2 = new Uint8Array(al);
        for (let i = 0, j = 0; i < al; i++) {
          const c1 = value.charCodeAt(j++);
          const c2 = value.charCodeAt(j++);
          const n1 = charCodeToBase163(c1);
          const n2 = charCodeToBase163(c2);
          if (n1 === void 0 || n2 === void 0 && !Number.isNaN(c2)) {
            throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {
              ...INVALID_STRING_ERROR_BASE_CONFIG,
              value
            });
          }
          hexBytes2[i] = !Number.isNaN(c2) ? n1 << 4 | (n2 ?? 0) : n1;
        }
        bytes.set(hexBytes2, offset);
        return hexBytes2.length + offset;
      }
    });
    getBase16Decoder = () => createDecoder({
      read(bytes, offset) {
        const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
        return [value, bytes.length];
      }
    });
    getBase16Codec = () => combineCodec(getBase16Encoder(), getBase16Decoder());
    alphabet22 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
    getBase58Encoder = () => getBaseXEncoder(alphabet22);
    getBase58Decoder = () => getBaseXDecoder(alphabet22);
    getBase58Codec = () => getBaseXCodec(alphabet22);
    getBaseXResliceEncoder = (alphabet4, bits) => createEncoder({
      getSizeFromValue: (value) => Math.floor(value.length * bits / 8),
      write(value, bytes, offset) {
        assertValidBaseString(alphabet4, value);
        if (value === "") return offset;
        const charIndices = [...value].map((c) => alphabet4.indexOf(c));
        const reslicedBytes = reslice(charIndices, bits, 8, false);
        bytes.set(reslicedBytes, offset);
        return reslicedBytes.length + offset;
      }
    });
    getBaseXResliceDecoder = (alphabet4, bits) => createDecoder({
      read(rawBytes, offset = 0) {
        const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);
        if (bytes.length === 0) return ["", rawBytes.length];
        const charIndices = reslice([...bytes], 8, bits, true);
        return [charIndices.map((i) => alphabet4[i]).join(""), rawBytes.length];
      }
    });
    getBaseXResliceCodec = (alphabet4, bits) => combineCodec(getBaseXResliceEncoder(alphabet4, bits), getBaseXResliceDecoder(alphabet4, bits));
    alphabet32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    getBase64Encoder = () => {
      {
        return createEncoder({
          getSizeFromValue: (value) => Buffer.from(value, "base64").length,
          write(value, bytes, offset) {
            assertValidBaseString(alphabet32, value.replace(/=/g, ""));
            const buffer2 = Buffer.from(value, "base64");
            bytes.set(buffer2, offset);
            return buffer2.length + offset;
          }
        });
      }
    };
    getBase64Decoder = () => {
      {
        return createDecoder({
          read: (bytes, offset = 0) => [Buffer.from(toArrayBuffer(bytes), offset).toString("base64"), bytes.length]
        });
      }
    };
    getBase64Codec = () => combineCodec(getBase64Encoder(), getBase64Decoder());
    removeNullCharacters = (value) => (
      // eslint-disable-next-line no-control-regex
      value.replace(/\u0000/g, "")
    );
    padNullCharacters = (value, chars) => value.padEnd(chars, "\0");
    e = globalThis.TextDecoder;
    o = globalThis.TextEncoder;
    getUtf8Encoder = () => {
      let textEncoder;
      return createEncoder({
        getSizeFromValue: (value) => (textEncoder ||= new o()).encode(value).length,
        write: (value, bytes, offset) => {
          const bytesToAdd = (textEncoder ||= new o()).encode(value);
          bytes.set(bytesToAdd, offset);
          return offset + bytesToAdd.length;
        }
      });
    };
    getUtf8Decoder = () => {
      let textDecoder;
      return createDecoder({
        read(bytes, offset) {
          const value = (textDecoder ||= new e()).decode(bytes.slice(offset));
          return [removeNullCharacters(value), bytes.length];
        }
      });
    };
    getUtf8Codec = () => combineCodec(getUtf8Encoder(), getUtf8Decoder());
  }
});

// node_modules/@solana/accounts/dist/index.node.mjs
function decodeAccount(encodedAccount, decoder2) {
  try {
    if ("exists" in encodedAccount && !encodedAccount.exists) {
      return encodedAccount;
    }
    return Object.freeze({ ...encodedAccount, data: decoder2.decode(encodedAccount.data) });
  } catch {
    throw new SolanaError(SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT, {
      address: encodedAccount.address
    });
  }
}
function accountExists(account) {
  return !("exists" in account) || "exists" in account && account.exists;
}
function assertAccountDecoded(account) {
  if (accountExists(account) && account.data instanceof Uint8Array) {
    throw new SolanaError(SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT, {
      address: account.address
    });
  }
}
function assertAccountsDecoded(accounts) {
  const encoded = accounts.filter((a) => accountExists(a) && a.data instanceof Uint8Array);
  if (encoded.length > 0) {
    const encodedAddresses = encoded.map((a) => a.address);
    throw new SolanaError(SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED, {
      addresses: encodedAddresses
    });
  }
}
function parseBase64RpcAccount(address2, rpcAccount) {
  if (!rpcAccount) return Object.freeze({ address: address2, exists: false });
  const data = getBase64Encoder().encode(rpcAccount.data[0]);
  return Object.freeze({ ...parseBaseAccount(rpcAccount), address: address2, data, exists: true });
}
function parseBase58RpcAccount(address2, rpcAccount) {
  if (!rpcAccount) return Object.freeze({ address: address2, exists: false });
  const data = getBase58Encoder().encode(typeof rpcAccount.data === "string" ? rpcAccount.data : rpcAccount.data[0]);
  return Object.freeze({ ...parseBaseAccount(rpcAccount), address: address2, data, exists: true });
}
function parseJsonRpcAccount(address2, rpcAccount) {
  if (!rpcAccount) return Object.freeze({ address: address2, exists: false });
  const data = rpcAccount.data.parsed.info || {};
  if (rpcAccount.data.program || rpcAccount.data.parsed.type) {
    data.parsedAccountMeta = {
      program: rpcAccount.data.program,
      type: rpcAccount.data.parsed.type
    };
  }
  return Object.freeze({ ...parseBaseAccount(rpcAccount), address: address2, data, exists: true });
}
function parseBaseAccount(rpcAccount) {
  return Object.freeze({
    executable: rpcAccount.executable,
    lamports: rpcAccount.lamports,
    programAddress: rpcAccount.owner,
    space: rpcAccount.space
  });
}
async function fetchEncodedAccount(rpc, address2, config = {}) {
  const { abortSignal, ...rpcConfig } = config;
  const response = await rpc.getAccountInfo(address2, { ...rpcConfig, encoding: "base64" }).send({ abortSignal });
  return parseBase64RpcAccount(address2, response.value);
}
async function fetchJsonParsedAccount(rpc, address2, config = {}) {
  const { abortSignal, ...rpcConfig } = config;
  const { value: account } = await rpc.getAccountInfo(address2, { ...rpcConfig, encoding: "jsonParsed" }).send({ abortSignal });
  return !!account && typeof account === "object" && "parsed" in account.data ? parseJsonRpcAccount(address2, account) : parseBase64RpcAccount(address2, account);
}
async function fetchEncodedAccounts(rpc, addresses, config = {}) {
  const { abortSignal, ...rpcConfig } = config;
  const response = await rpc.getMultipleAccounts(addresses, { ...rpcConfig, encoding: "base64" }).send({ abortSignal });
  return response.value.map((account, index2) => parseBase64RpcAccount(addresses[index2], account));
}
async function fetchJsonParsedAccounts(rpc, addresses, config = {}) {
  const { abortSignal, ...rpcConfig } = config;
  const response = await rpc.getMultipleAccounts(addresses, { ...rpcConfig, encoding: "jsonParsed" }).send({ abortSignal });
  return response.value.map((account, index2) => {
    return !!account && typeof account === "object" && "parsed" in account.data ? parseJsonRpcAccount(addresses[index2], account) : parseBase64RpcAccount(addresses[index2], account);
  });
}
function assertAccountExists(account) {
  if (!account.exists) {
    throw new SolanaError(SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND, { address: account.address });
  }
}
function assertAccountsExist(accounts) {
  const missingAccounts = accounts.filter((a) => !a.exists);
  if (missingAccounts.length > 0) {
    const missingAddresses = missingAccounts.map((a) => a.address);
    throw new SolanaError(SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND, { addresses: missingAddresses });
  }
}
var BASE_ACCOUNT_SIZE;
var init_index_node4 = __esm({
  "node_modules/@solana/accounts/dist/index.node.mjs"() {
    "use strict";
    init_index_node();
    init_index_node3();
    BASE_ACCOUNT_SIZE = 128;
  }
});

// node_modules/@solana/assertions/dist/index.node.mjs
function assertPRNGIsAvailable() {
  if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.getRandomValues !== "function") {
    throw new SolanaError(SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED);
  }
}
async function isEd25519CurveSupported(subtle) {
  if (cachedEd25519Decision === void 0) {
    cachedEd25519Decision = new Promise((resolve) => {
      subtle.generateKey(
        "Ed25519",
        /* extractable */
        false,
        ["sign", "verify"]
      ).then(() => {
        resolve(cachedEd25519Decision = true);
      }).catch(() => {
        resolve(cachedEd25519Decision = false);
      });
    });
  }
  if (typeof cachedEd25519Decision === "boolean") {
    return cachedEd25519Decision;
  } else {
    return await cachedEd25519Decision;
  }
}
function assertDigestCapabilityIsAvailable() {
  if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.digest !== "function") {
    throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED);
  }
}
async function assertKeyGenerationIsAvailable() {
  if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.generateKey !== "function") {
    throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED);
  }
  if (!await isEd25519CurveSupported(globalThis.crypto.subtle)) {
    throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED);
  }
}
function assertKeyExporterIsAvailable() {
  if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.exportKey !== "function") {
    throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED);
  }
}
function assertSigningCapabilityIsAvailable() {
  if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.sign !== "function") {
    throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED);
  }
}
function assertVerificationCapabilityIsAvailable() {
  if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.subtle?.verify !== "function") {
    throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED);
  }
}
var cachedEd25519Decision;
var init_index_node5 = __esm({
  "node_modules/@solana/assertions/dist/index.node.mjs"() {
    "use strict";
    init_index_node();
  }
});

// node_modules/@solana/addresses/dist/index.node.mjs
function getMemoizedBase58Encoder() {
  if (!memoizedBase58Encoder) memoizedBase58Encoder = getBase58Encoder();
  return memoizedBase58Encoder;
}
function getMemoizedBase58Decoder() {
  if (!memoizedBase58Decoder) memoizedBase58Decoder = getBase58Decoder();
  return memoizedBase58Decoder;
}
function isAddress2(putativeAddress) {
  if (
    // Lowest address (32 bytes of zeroes)
    putativeAddress.length < 32 || // Highest address (32 bytes of 255)
    putativeAddress.length > 44
  ) {
    return false;
  }
  const base58Encoder2 = getMemoizedBase58Encoder();
  try {
    return base58Encoder2.encode(putativeAddress).byteLength === 32;
  } catch {
    return false;
  }
}
function assertIsAddress(putativeAddress) {
  if (
    // Lowest address (32 bytes of zeroes)
    putativeAddress.length < 32 || // Highest address (32 bytes of 255)
    putativeAddress.length > 44
  ) {
    throw new SolanaError(SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE, {
      actualLength: putativeAddress.length
    });
  }
  const base58Encoder2 = getMemoizedBase58Encoder();
  const bytes = base58Encoder2.encode(putativeAddress);
  const numBytes = bytes.byteLength;
  if (numBytes !== 32) {
    throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH, {
      actualLength: numBytes
    });
  }
}
function address(putativeAddress) {
  assertIsAddress(putativeAddress);
  return putativeAddress;
}
function getAddressEncoder() {
  return transformEncoder(
    fixEncoderSize(getMemoizedBase58Encoder(), 32),
    (putativeAddress) => address(putativeAddress)
  );
}
function getAddressDecoder() {
  return fixDecoderSize(getMemoizedBase58Decoder(), 32);
}
function getAddressCodec() {
  return combineCodec(getAddressEncoder(), getAddressDecoder());
}
function getAddressComparator() {
  return new Intl.Collator("en", {
    caseFirst: "lower",
    ignorePunctuation: false,
    localeMatcher: "best fit",
    numeric: false,
    sensitivity: "variant",
    usage: "sort"
  }).compare;
}
function mod4(a) {
  const r = a % P;
  return r >= 0n ? r : P + r;
}
function pow24(x, power) {
  let r = x;
  while (power-- > 0n) {
    r *= r;
    r %= P;
  }
  return r;
}
function pow_2_252_3(x) {
  const x2 = x * x % P;
  const b2 = x2 * x % P;
  const b4 = pow24(b2, 2n) * b2 % P;
  const b5 = pow24(b4, 1n) * x % P;
  const b10 = pow24(b5, 5n) * b5 % P;
  const b20 = pow24(b10, 10n) * b10 % P;
  const b40 = pow24(b20, 20n) * b20 % P;
  const b80 = pow24(b40, 40n) * b40 % P;
  const b160 = pow24(b80, 80n) * b80 % P;
  const b240 = pow24(b160, 80n) * b80 % P;
  const b250 = pow24(b240, 10n) * b10 % P;
  const pow_p_5_8 = pow24(b250, 2n) * x % P;
  return pow_p_5_8;
}
function uvRatio(u, v) {
  const v3 = mod4(v * v * v);
  const v7 = mod4(v3 * v3 * v);
  const pow = pow_2_252_3(u * v7);
  let x = mod4(u * v3 * pow);
  const vx2 = mod4(v * x * x);
  const root1 = x;
  const root2 = mod4(x * RM1);
  const useRoot1 = vx2 === u;
  const useRoot2 = vx2 === mod4(-u);
  const noRoot = vx2 === mod4(-u * RM1);
  if (useRoot1) x = root1;
  if (useRoot2 || noRoot) x = root2;
  if ((mod4(x) & 1n) === 1n) x = mod4(-x);
  if (!useRoot1 && !useRoot2) {
    return null;
  }
  return x;
}
function pointIsOnCurve(y, lastByte) {
  const y2 = mod4(y * y);
  const u = mod4(y2 - 1n);
  const v = mod4(D * y2 + 1n);
  const x = uvRatio(u, v);
  if (x === null) {
    return false;
  }
  const isLastByteOdd = (lastByte & 128) !== 0;
  if (x === 0n && isLastByteOdd) {
    return false;
  }
  return true;
}
function byteToHex(byte) {
  const hexString = byte.toString(16);
  if (hexString.length === 1) {
    return `0${hexString}`;
  } else {
    return hexString;
  }
}
function decompressPointBytes(bytes) {
  const hexString = bytes.reduce((acc, byte, ii) => `${byteToHex(ii === 31 ? byte & -129 : byte)}${acc}`, "");
  const integerLiteralString = `0x${hexString}`;
  return BigInt(integerLiteralString);
}
function compressedPointBytesAreOnCurve(bytes) {
  if (bytes.byteLength !== 32) {
    return false;
  }
  const y = decompressPointBytes(bytes);
  return pointIsOnCurve(y, bytes[31]);
}
function isOffCurveAddress(putativeOffCurveAddress) {
  const addressBytes = getAddressCodec().encode(putativeOffCurveAddress);
  return compressedPointBytesAreOnCurve(addressBytes) === false;
}
function assertIsOffCurveAddress(putativeOffCurveAddress) {
  if (!isOffCurveAddress(putativeOffCurveAddress)) {
    throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS);
  }
}
function offCurveAddress(putativeOffCurveAddress) {
  assertIsOffCurveAddress(putativeOffCurveAddress);
  return putativeOffCurveAddress;
}
function isProgramDerivedAddress(value) {
  return Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number" && value[1] >= 0 && value[1] <= 255 && isAddress2(value[0]);
}
function assertIsProgramDerivedAddress(value) {
  const validFormat = Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && typeof value[1] === "number";
  if (!validFormat) {
    throw new SolanaError(SOLANA_ERROR__ADDRESSES__MALFORMED_PDA);
  }
  if (value[1] < 0 || value[1] > 255) {
    throw new SolanaError(SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE, {
      bump: value[1]
    });
  }
  assertIsAddress(value[0]);
}
async function createProgramDerivedAddress({ programAddress, seeds }) {
  assertDigestCapabilityIsAvailable();
  if (seeds.length > MAX_SEEDS) {
    throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED, {
      actual: seeds.length,
      maxSeeds: MAX_SEEDS
    });
  }
  let textEncoder;
  const seedBytes = seeds.reduce((acc, seed, ii) => {
    const bytes = typeof seed === "string" ? (textEncoder ||= new TextEncoder()).encode(seed) : seed;
    if (bytes.byteLength > MAX_SEED_LENGTH) {
      throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {
        actual: bytes.byteLength,
        index: ii,
        maxSeedLength: MAX_SEED_LENGTH
      });
    }
    acc.push(...bytes);
    return acc;
  }, []);
  const base58EncodedAddressCodec = getAddressCodec();
  const programAddressBytes = base58EncodedAddressCodec.encode(programAddress);
  const addressBytesBuffer = await crypto.subtle.digest(
    "SHA-256",
    new Uint8Array([...seedBytes, ...programAddressBytes, ...PDA_MARKER_BYTES])
  );
  const addressBytes = new Uint8Array(addressBytesBuffer);
  if (compressedPointBytesAreOnCurve(addressBytes)) {
    throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE);
  }
  return base58EncodedAddressCodec.decode(addressBytes);
}
async function getProgramDerivedAddress({
  programAddress,
  seeds
}) {
  let bumpSeed = 255;
  while (bumpSeed > 0) {
    try {
      const address2 = await createProgramDerivedAddress({
        programAddress,
        seeds: [...seeds, new Uint8Array([bumpSeed])]
      });
      return [address2, bumpSeed];
    } catch (e7) {
      if (isSolanaError(e7, SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE)) {
        bumpSeed--;
      } else {
        throw e7;
      }
    }
  }
  throw new SolanaError(SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED);
}
async function createAddressWithSeed({ baseAddress, programAddress, seed }) {
  const { encode: encode4, decode: decode2 } = getAddressCodec();
  const seedBytes = typeof seed === "string" ? new TextEncoder().encode(seed) : seed;
  if (seedBytes.byteLength > MAX_SEED_LENGTH) {
    throw new SolanaError(SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED, {
      actual: seedBytes.byteLength,
      index: 0,
      maxSeedLength: MAX_SEED_LENGTH
    });
  }
  const programAddressBytes = encode4(programAddress);
  if (programAddressBytes.length >= PDA_MARKER_BYTES.length && bytesEqual(programAddressBytes.slice(-PDA_MARKER_BYTES.length), new Uint8Array(PDA_MARKER_BYTES))) {
    throw new SolanaError(SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER);
  }
  const addressBytesBuffer = await crypto.subtle.digest(
    "SHA-256",
    new Uint8Array([...encode4(baseAddress), ...seedBytes, ...programAddressBytes])
  );
  const addressBytes = new Uint8Array(addressBytesBuffer);
  return decode2(addressBytes);
}
async function getAddressFromPublicKey(publicKey) {
  assertKeyExporterIsAvailable();
  if (publicKey.type !== "public" || publicKey.algorithm.name !== "Ed25519") {
    throw new SolanaError(SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY);
  }
  const publicKeyBytes = await crypto.subtle.exportKey("raw", publicKey);
  return getAddressDecoder().decode(new Uint8Array(publicKeyBytes));
}
async function getPublicKeyFromAddress(address2) {
  const addressBytes = getAddressEncoder().encode(address2);
  return await crypto.subtle.importKey("raw", addressBytes, { name: "Ed25519" }, true, ["verify"]);
}
var memoizedBase58Encoder, memoizedBase58Decoder, D, P, RM1, MAX_SEED_LENGTH, MAX_SEEDS, PDA_MARKER_BYTES;
var init_index_node6 = __esm({
  "node_modules/@solana/addresses/dist/index.node.mjs"() {
    "use strict";
    init_index_node2();
    init_index_node3();
    init_index_node();
    init_index_node5();
    D = 37095705934669439343138083508754565189542113879843219016388785533085940283555n;
    P = 57896044618658097711785492504343953926634992332820282019728792003956564819949n;
    RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n;
    MAX_SEED_LENGTH = 32;
    MAX_SEEDS = 16;
    PDA_MARKER_BYTES = [
      // The string 'ProgramDerivedAddress'
      80,
      114,
      111,
      103,
      114,
      97,
      109,
      68,
      101,
      114,
      105,
      118,
      101,
      100,
      65,
      100,
      100,
      114,
      101,
      115,
      115
    ];
  }
});

// node_modules/@solana/codecs-numbers/dist/index.node.mjs
function assertNumberIsBetweenForCodec(codecDescription, min, max, value) {
  if (value < min || value > max) {
    throw new SolanaError(SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE, {
      codecDescription,
      max,
      min,
      value
    });
  }
}
function isLittleEndian(config) {
  return config?.endian === 1 ? false : true;
}
function numberEncoderFactory(input) {
  return createEncoder({
    fixedSize: input.size,
    write(value, bytes, offset) {
      if (input.range) {
        assertNumberIsBetweenForCodec(input.name, input.range[0], input.range[1], value);
      }
      const arrayBuffer = new ArrayBuffer(input.size);
      input.set(new DataView(arrayBuffer), value, isLittleEndian(input.config));
      bytes.set(new Uint8Array(arrayBuffer), offset);
      return offset + input.size;
    }
  });
}
function numberDecoderFactory(input) {
  return createDecoder({
    fixedSize: input.size,
    read(bytes, offset = 0) {
      assertByteArrayIsNotEmptyForCodec(input.name, bytes, offset);
      assertByteArrayHasEnoughBytesForCodec(input.name, input.size, bytes, offset);
      const view = new DataView(toArrayBuffer(bytes, offset, input.size));
      return [input.get(view, isLittleEndian(input.config)), offset + input.size];
    }
  });
}
var Endian, getF32Encoder, getF32Decoder, getF32Codec, getF64Encoder, getF64Decoder, getF64Codec, getI128Encoder, getI128Decoder, getI128Codec, getI16Encoder, getI16Decoder, getI16Codec, getI32Encoder, getI32Decoder, getI32Codec, getI64Encoder, getI64Decoder, getI64Codec, getI8Encoder, getI8Decoder, getI8Codec, getShortU16Encoder, getShortU16Decoder, getShortU16Codec, getU128Encoder, getU128Decoder, getU128Codec, getU16Encoder, getU16Decoder, getU16Codec, getU32Encoder, getU32Decoder, getU32Codec, getU64Encoder, getU64Decoder, getU64Codec, getU8Encoder, getU8Decoder, getU8Codec;
var init_index_node7 = __esm({
  "node_modules/@solana/codecs-numbers/dist/index.node.mjs"() {
    "use strict";
    init_index_node();
    init_index_node2();
    Endian = /* @__PURE__ */ ((Endian2) => {
      Endian2[Endian2["Little"] = 0] = "Little";
      Endian2[Endian2["Big"] = 1] = "Big";
      return Endian2;
    })(Endian || {});
    getF32Encoder = (config = {}) => numberEncoderFactory({
      config,
      name: "f32",
      set: (view, value, le) => view.setFloat32(0, Number(value), le),
      size: 4
    });
    getF32Decoder = (config = {}) => numberDecoderFactory({
      config,
      get: (view, le) => view.getFloat32(0, le),
      name: "f32",
      size: 4
    });
    getF32Codec = (config = {}) => combineCodec(getF32Encoder(config), getF32Decoder(config));
    getF64Encoder = (config = {}) => numberEncoderFactory({
      config,
      name: "f64",
      set: (view, value, le) => view.setFloat64(0, Number(value), le),
      size: 8
    });
    getF64Decoder = (config = {}) => numberDecoderFactory({
      config,
      get: (view, le) => view.getFloat64(0, le),
      name: "f64",
      size: 8
    });
    getF64Codec = (config = {}) => combineCodec(getF64Encoder(config), getF64Decoder(config));
    getI128Encoder = (config = {}) => numberEncoderFactory({
      config,
      name: "i128",
      range: [-BigInt("0x7fffffffffffffffffffffffffffffff") - 1n, BigInt("0x7fffffffffffffffffffffffffffffff")],
      set: (view, value, le) => {
        const leftOffset = le ? 8 : 0;
        const rightOffset = le ? 0 : 8;
        const rightMask = 0xffffffffffffffffn;
        view.setBigInt64(leftOffset, BigInt(value) >> 64n, le);
        view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);
      },
      size: 16
    });
    getI128Decoder = (config = {}) => numberDecoderFactory({
      config,
      get: (view, le) => {
        const leftOffset = le ? 8 : 0;
        const rightOffset = le ? 0 : 8;
        const left = view.getBigInt64(leftOffset, le);
        const right = view.getBigUint64(rightOffset, le);
        return (left << 64n) + right;
      },
      name: "i128",
      size: 16
    });
    getI128Codec = (config = {}) => combineCodec(getI128Encoder(config), getI128Decoder(config));
    getI16Encoder = (config = {}) => numberEncoderFactory({
      config,
      name: "i16",
      range: [-Number("0x7fff") - 1, Number("0x7fff")],
      set: (view, value, le) => view.setInt16(0, Number(value), le),
      size: 2
    });
    getI16Decoder = (config = {}) => numberDecoderFactory({
      config,
      get: (view, le) => view.getInt16(0, le),
      name: "i16",
      size: 2
    });
    getI16Codec = (config = {}) => combineCodec(getI16Encoder(config), getI16Decoder(config));
    getI32Encoder = (config = {}) => numberEncoderFactory({
      config,
      name: "i32",
      range: [-Number("0x7fffffff") - 1, Number("0x7fffffff")],
      set: (view, value, le) => view.setInt32(0, Number(value), le),
      size: 4
    });
    getI32Decoder = (config = {}) => numberDecoderFactory({
      config,
      get: (view, le) => view.getInt32(0, le),
      name: "i32",
      size: 4
    });
    getI32Codec = (config = {}) => combineCodec(getI32Encoder(config), getI32Decoder(config));
    getI64Encoder = (config = {}) => numberEncoderFactory({
      config,
      name: "i64",
      range: [-BigInt("0x7fffffffffffffff") - 1n, BigInt("0x7fffffffffffffff")],
      set: (view, value, le) => view.setBigInt64(0, BigInt(value), le),
      size: 8
    });
    getI64Decoder = (config = {}) => numberDecoderFactory({
      config,
      get: (view, le) => view.getBigInt64(0, le),
      name: "i64",
      size: 8
    });
    getI64Codec = (config = {}) => combineCodec(getI64Encoder(config), getI64Decoder(config));
    getI8Encoder = () => numberEncoderFactory({
      name: "i8",
      range: [-Number("0x7f") - 1, Number("0x7f")],
      set: (view, value) => view.setInt8(0, Number(value)),
      size: 1
    });
    getI8Decoder = () => numberDecoderFactory({
      get: (view) => view.getInt8(0),
      name: "i8",
      size: 1
    });
    getI8Codec = () => combineCodec(getI8Encoder(), getI8Decoder());
    getShortU16Encoder = () => createEncoder({
      getSizeFromValue: (value) => {
        if (value <= 127) return 1;
        if (value <= 16383) return 2;
        return 3;
      },
      maxSize: 3,
      write: (value, bytes, offset) => {
        assertNumberIsBetweenForCodec("shortU16", 0, 65535, value);
        const shortU16Bytes = [0];
        for (let ii = 0; ; ii += 1) {
          const alignedValue = Number(value) >> ii * 7;
          if (alignedValue === 0) {
            break;
          }
          const nextSevenBits = 127 & alignedValue;
          shortU16Bytes[ii] = nextSevenBits;
          if (ii > 0) {
            shortU16Bytes[ii - 1] |= 128;
          }
        }
        bytes.set(shortU16Bytes, offset);
        return offset + shortU16Bytes.length;
      }
    });
    getShortU16Decoder = () => createDecoder({
      maxSize: 3,
      read: (bytes, offset) => {
        let value = 0;
        let byteCount = 0;
        while (++byteCount) {
          const byteIndex = byteCount - 1;
          const currentByte = bytes[offset + byteIndex];
          const nextSevenBits = 127 & currentByte;
          value |= nextSevenBits << byteIndex * 7;
          if ((currentByte & 128) === 0) {
            break;
          }
        }
        return [value, offset + byteCount];
      }
    });
    getShortU16Codec = () => combineCodec(getShortU16Encoder(), getShortU16Decoder());
    getU128Encoder = (config = {}) => numberEncoderFactory({
      config,
      name: "u128",
      range: [0n, BigInt("0xffffffffffffffffffffffffffffffff")],
      set: (view, value, le) => {
        const leftOffset = le ? 8 : 0;
        const rightOffset = le ? 0 : 8;
        const rightMask = 0xffffffffffffffffn;
        view.setBigUint64(leftOffset, BigInt(value) >> 64n, le);
        view.setBigUint64(rightOffset, BigInt(value) & rightMask, le);
      },
      size: 16
    });
    getU128Decoder = (config = {}) => numberDecoderFactory({
      config,
      get: (view, le) => {
        const leftOffset = le ? 8 : 0;
        const rightOffset = le ? 0 : 8;
        const left = view.getBigUint64(leftOffset, le);
        const right = view.getBigUint64(rightOffset, le);
        return (left << 64n) + right;
      },
      name: "u128",
      size: 16
    });
    getU128Codec = (config = {}) => combineCodec(getU128Encoder(config), getU128Decoder(config));
    getU16Encoder = (config = {}) => numberEncoderFactory({
      config,
      name: "u16",
      range: [0, Number("0xffff")],
      set: (view, value, le) => view.setUint16(0, Number(value), le),
      size: 2
    });
    getU16Decoder = (config = {}) => numberDecoderFactory({
      config,
      get: (view, le) => view.getUint16(0, le),
      name: "u16",
      size: 2
    });
    getU16Codec = (config = {}) => combineCodec(getU16Encoder(config), getU16Decoder(config));
    getU32Encoder = (config = {}) => numberEncoderFactory({
      config,
      name: "u32",
      range: [0, Number("0xffffffff")],
      set: (view, value, le) => view.setUint32(0, Number(value), le),
      size: 4
    });
    getU32Decoder = (config = {}) => numberDecoderFactory({
      config,
      get: (view, le) => view.getUint32(0, le),
      name: "u32",
      size: 4
    });
    getU32Codec = (config = {}) => combineCodec(getU32Encoder(config), getU32Decoder(config));
    getU64Encoder = (config = {}) => numberEncoderFactory({
      config,
      name: "u64",
      range: [0n, BigInt("0xffffffffffffffff")],
      set: (view, value, le) => view.setBigUint64(0, BigInt(value), le),
      size: 8
    });
    getU64Decoder = (config = {}) => numberDecoderFactory({
      config,
      get: (view, le) => view.getBigUint64(0, le),
      name: "u64",
      size: 8
    });
    getU64Codec = (config = {}) => combineCodec(getU64Encoder(config), getU64Decoder(config));
    getU8Encoder = () => numberEncoderFactory({
      name: "u8",
      range: [0, Number("0xff")],
      set: (view, value) => view.setUint8(0, Number(value)),
      size: 1
    });
    getU8Decoder = () => numberDecoderFactory({
      get: (view) => view.getUint8(0),
      name: "u8",
      size: 1
    });
    getU8Codec = () => combineCodec(getU8Encoder(), getU8Decoder());
  }
});

// node_modules/@solana/codecs-data-structures/dist/index.node.mjs
function assertValidNumberOfItemsForCodec(codecDescription, expected, actual) {
  if (expected !== actual) {
    throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS, {
      actual,
      codecDescription,
      expected
    });
  }
}
function maxCodecSizes(sizes) {
  return sizes.reduce(
    (all, size5) => all === null || size5 === null ? null : Math.max(all, size5),
    0
  );
}
function sumCodecSizes(sizes) {
  return sizes.reduce((all, size5) => all === null || size5 === null ? null : all + size5, 0);
}
function getFixedSize(codec) {
  return isFixedSize(codec) ? codec.fixedSize : null;
}
function getMaxSize(codec) {
  return isFixedSize(codec) ? codec.fixedSize : codec.maxSize ?? null;
}
function getArrayEncoder(item, config = {}) {
  const size5 = config.size ?? getU32Encoder();
  const fixedSize = computeArrayLikeCodecSize(size5, getFixedSize(item));
  const maxSize = computeArrayLikeCodecSize(size5, getMaxSize(item)) ?? void 0;
  return createEncoder({
    ...fixedSize !== null ? { fixedSize } : {
      getSizeFromValue: (array) => {
        const prefixSize = typeof size5 === "object" ? getEncodedSize(array.length, size5) : 0;
        return prefixSize + [...array].reduce((all, value) => all + getEncodedSize(value, item), 0);
      },
      maxSize
    },
    write: (array, bytes, offset) => {
      if (typeof size5 === "number") {
        assertValidNumberOfItemsForCodec("array", size5, array.length);
      }
      if (typeof size5 === "object") {
        offset = size5.write(array.length, bytes, offset);
      }
      array.forEach((value) => {
        offset = item.write(value, bytes, offset);
      });
      return offset;
    }
  });
}
function getArrayDecoder(item, config = {}) {
  const size5 = config.size ?? getU32Decoder();
  const itemSize = getFixedSize(item);
  const fixedSize = computeArrayLikeCodecSize(size5, itemSize);
  const maxSize = computeArrayLikeCodecSize(size5, getMaxSize(item)) ?? void 0;
  return createDecoder({
    ...fixedSize !== null ? { fixedSize } : { maxSize },
    read: (bytes, offset) => {
      const array = [];
      if (typeof size5 === "object" && bytes.slice(offset).length === 0) {
        return [array, offset];
      }
      if (size5 === "remainder") {
        while (offset < bytes.length) {
          const [value, newOffset2] = item.read(bytes, offset);
          offset = newOffset2;
          array.push(value);
        }
        return [array, offset];
      }
      const [resolvedSize, newOffset] = typeof size5 === "number" ? [size5, offset] : size5.read(bytes, offset);
      offset = newOffset;
      for (let i = 0; i < resolvedSize; i += 1) {
        const [value, newOffset2] = item.read(bytes, offset);
        offset = newOffset2;
        array.push(value);
      }
      return [array, offset];
    }
  });
}
function getArrayCodec(item, config = {}) {
  return combineCodec(getArrayEncoder(item, config), getArrayDecoder(item, config));
}
function computeArrayLikeCodecSize(size5, itemSize) {
  if (typeof size5 !== "number") return null;
  if (size5 === 0) return 0;
  return itemSize === null ? null : itemSize * size5;
}
function getBitArrayEncoder(size5, config = {}) {
  const parsedConfig = typeof config === "boolean" ? { backward: config } : config;
  const backward = parsedConfig.backward ?? false;
  return createEncoder({
    fixedSize: size5,
    write(value, bytes, offset) {
      const bytesToAdd = [];
      for (let i = 0; i < size5; i += 1) {
        let byte = 0;
        for (let j = 0; j < 8; j += 1) {
          const feature = Number(value[i * 8 + j] ?? 0);
          byte |= feature << (backward ? j : 7 - j);
        }
        if (backward) {
          bytesToAdd.unshift(byte);
        } else {
          bytesToAdd.push(byte);
        }
      }
      bytes.set(bytesToAdd, offset);
      return size5;
    }
  });
}
function getBitArrayDecoder(size5, config = {}) {
  const parsedConfig = typeof config === "boolean" ? { backward: config } : config;
  const backward = parsedConfig.backward ?? false;
  return createDecoder({
    fixedSize: size5,
    read(bytes, offset) {
      assertByteArrayHasEnoughBytesForCodec("bitArray", size5, bytes, offset);
      const booleans = [];
      let slice4 = bytes.slice(offset, offset + size5);
      slice4 = backward ? slice4.reverse() : slice4;
      slice4.forEach((byte) => {
        for (let i = 0; i < 8; i += 1) {
          if (backward) {
            booleans.push(Boolean(byte & 1));
            byte >>= 1;
          } else {
            booleans.push(Boolean(byte & 128));
            byte <<= 1;
          }
        }
      });
      return [booleans, offset + size5];
    }
  });
}
function getBitArrayCodec(size5, config = {}) {
  return combineCodec(getBitArrayEncoder(size5, config), getBitArrayDecoder(size5, config));
}
function getBooleanEncoder(config = {}) {
  return transformEncoder(config.size ?? getU8Encoder(), (value) => value ? 1 : 0);
}
function getBooleanDecoder(config = {}) {
  return transformDecoder(config.size ?? getU8Decoder(), (value) => Number(value) === 1);
}
function getBooleanCodec(config = {}) {
  return combineCodec(getBooleanEncoder(config), getBooleanDecoder(config));
}
function getBytesEncoder() {
  return createEncoder({
    getSizeFromValue: (value) => value.length,
    write: (value, bytes, offset) => {
      bytes.set(value, offset);
      return offset + value.length;
    }
  });
}
function getBytesDecoder() {
  return createDecoder({
    read: (bytes, offset) => {
      const slice4 = bytes.slice(offset);
      return [slice4, offset + slice4.length];
    }
  });
}
function getBytesCodec() {
  return combineCodec(getBytesEncoder(), getBytesDecoder());
}
function getConstantEncoder(constant) {
  return createEncoder({
    fixedSize: constant.length,
    write: (_, bytes, offset) => {
      bytes.set(constant, offset);
      return offset + constant.length;
    }
  });
}
function getConstantDecoder(constant) {
  return createDecoder({
    fixedSize: constant.length,
    read: (bytes, offset) => {
      const base16 = getBase16Decoder2();
      if (!containsBytes(bytes, constant, offset)) {
        throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_CONSTANT, {
          constant,
          data: bytes,
          hexConstant: base16.decode(constant),
          hexData: base16.decode(bytes),
          offset
        });
      }
      return [void 0, offset + constant.length];
    }
  });
}
function getConstantCodec(constant) {
  return combineCodec(getConstantEncoder(constant), getConstantDecoder(constant));
}
function getTupleEncoder(items) {
  const fixedSize = sumCodecSizes(items.map(getFixedSize));
  const maxSize = sumCodecSizes(items.map(getMaxSize)) ?? void 0;
  return createEncoder({
    ...fixedSize === null ? {
      getSizeFromValue: (value) => items.map((item, index2) => getEncodedSize(value[index2], item)).reduce((all, one) => all + one, 0),
      maxSize
    } : { fixedSize },
    write: (value, bytes, offset) => {
      assertValidNumberOfItemsForCodec("tuple", items.length, value.length);
      items.forEach((item, index2) => {
        offset = item.write(value[index2], bytes, offset);
      });
      return offset;
    }
  });
}
function getTupleDecoder(items) {
  const fixedSize = sumCodecSizes(items.map(getFixedSize));
  const maxSize = sumCodecSizes(items.map(getMaxSize)) ?? void 0;
  return createDecoder({
    ...fixedSize === null ? { maxSize } : { fixedSize },
    read: (bytes, offset) => {
      const values = [];
      items.forEach((item) => {
        const [newValue, newOffset] = item.read(bytes, offset);
        values.push(newValue);
        offset = newOffset;
      });
      return [values, offset];
    }
  });
}
function getTupleCodec(items) {
  return combineCodec(
    getTupleEncoder(items),
    getTupleDecoder(items)
  );
}
function getUnionEncoder(variants, getIndexFromValue) {
  const fixedSize = getUnionFixedSize(variants);
  const write = (variant, bytes, offset) => {
    const index2 = getIndexFromValue(variant);
    assertValidVariantIndex(variants, index2);
    return variants[index2].write(variant, bytes, offset);
  };
  if (fixedSize !== null) {
    return createEncoder({ fixedSize, write });
  }
  const maxSize = getUnionMaxSize(variants);
  return createEncoder({
    ...maxSize !== null ? { maxSize } : {},
    getSizeFromValue: (variant) => {
      const index2 = getIndexFromValue(variant);
      assertValidVariantIndex(variants, index2);
      return getEncodedSize(variant, variants[index2]);
    },
    write
  });
}
function getUnionDecoder(variants, getIndexFromBytes) {
  const fixedSize = getUnionFixedSize(variants);
  const read = (bytes, offset) => {
    const index2 = getIndexFromBytes(bytes, offset);
    assertValidVariantIndex(variants, index2);
    return variants[index2].read(bytes, offset);
  };
  if (fixedSize !== null) {
    return createDecoder({ fixedSize, read });
  }
  const maxSize = getUnionMaxSize(variants);
  return createDecoder({ ...maxSize !== null ? { maxSize } : {}, read });
}
function getUnionCodec(variants, getIndexFromValue, getIndexFromBytes) {
  return combineCodec(
    getUnionEncoder(variants, getIndexFromValue),
    getUnionDecoder(variants, getIndexFromBytes)
  );
}
function assertValidVariantIndex(variants, index2) {
  if (typeof variants[index2] === "undefined") {
    throw new SolanaError(SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE, {
      maxRange: variants.length - 1,
      minRange: 0,
      variant: index2
    });
  }
}
function getUnionFixedSize(variants) {
  if (variants.length === 0) return 0;
  if (!isFixedSize(variants[0])) return null;
  const variantSize = variants[0].fixedSize;
  const sameSizedVariants = variants.every((variant) => isFixedSize(variant) && variant.fixedSize === variantSize);
  return sameSizedVariants ? variantSize : null;
}
function getUnionMaxSize(variants) {
  return maxCodecSizes(variants.map((variant) => getMaxSize(variant)));
}
function getDiscriminatedUnionEncoder(variants, config = {}) {
  const discriminatorProperty = config.discriminator ?? "__kind";
  const prefix = config.size ?? getU8Encoder();
  return getUnionEncoder(
    variants.map(
      ([, variant], index2) => transformEncoder(getTupleEncoder([prefix, variant]), (value) => [index2, value])
    ),
    (value) => getVariantDiscriminator(variants, value[discriminatorProperty])
  );
}
function getDiscriminatedUnionDecoder(variants, config = {}) {
  const discriminatorProperty = config.discriminator ?? "__kind";
  const prefix = config.size ?? getU8Decoder();
  return getUnionDecoder(
    variants.map(
      ([discriminator, variant]) => transformDecoder(getTupleDecoder([prefix, variant]), ([, value]) => ({
        [discriminatorProperty]: discriminator,
        ...value
      }))
    ),
    (bytes, offset) => Number(prefix.read(bytes, offset)[0])
  );
}
function getDiscriminatedUnionCodec(variants, config = {}) {
  return combineCodec(
    getDiscriminatedUnionEncoder(variants, config),
    getDiscriminatedUnionDecoder(variants, config)
  );
}
function getVariantDiscriminator(variants, discriminatorValue) {
  const discriminator = variants.findIndex(([key]) => discriminatorValue === key);
  if (discriminator < 0) {
    throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT, {
      value: discriminatorValue,
      variants: variants.map(([key]) => key)
    });
  }
  return discriminator;
}
function getEnumStats(constructor) {
  const numericalValues = [...new Set(Object.values(constructor).filter((v) => typeof v === "number"))].sort();
  const enumRecord = Object.fromEntries(Object.entries(constructor).slice(numericalValues.length));
  const enumKeys = Object.keys(enumRecord);
  const enumValues = Object.values(enumRecord);
  const stringValues = [
    .../* @__PURE__ */ new Set([...enumKeys, ...enumValues.filter((v) => typeof v === "string")])
  ];
  return { enumKeys, enumRecord, enumValues, numericalValues, stringValues };
}
function getEnumIndexFromVariant({
  enumKeys,
  enumValues,
  variant
}) {
  const valueIndex = findLastIndex(enumValues, (value) => value === variant);
  if (valueIndex >= 0) return valueIndex;
  return enumKeys.findIndex((key) => key === variant);
}
function getEnumIndexFromDiscriminator({
  discriminator,
  enumKeys,
  enumValues,
  useValuesAsDiscriminators
}) {
  if (!useValuesAsDiscriminators) {
    return discriminator >= 0 && discriminator < enumKeys.length ? discriminator : -1;
  }
  return findLastIndex(enumValues, (value) => value === discriminator);
}
function findLastIndex(array, predicate) {
  let l2 = array.length;
  while (l2--) {
    if (predicate(array[l2], l2, array)) return l2;
  }
  return -1;
}
function formatNumericalValues(values) {
  if (values.length === 0) return "";
  let range = [values[0], values[0]];
  const ranges = [];
  for (let index2 = 1; index2 < values.length; index2++) {
    const value = values[index2];
    if (range[1] + 1 === value) {
      range[1] = value;
    } else {
      ranges.push(range[0] === range[1] ? `${range[0]}` : `${range[0]}-${range[1]}`);
      range = [value, value];
    }
  }
  ranges.push(range[0] === range[1] ? `${range[0]}` : `${range[0]}-${range[1]}`);
  return ranges.join(", ");
}
function getEnumEncoder(constructor, config = {}) {
  const prefix = config.size ?? getU8Encoder();
  const useValuesAsDiscriminators = config.useValuesAsDiscriminators ?? false;
  const { enumKeys, enumValues, numericalValues, stringValues } = getEnumStats(constructor);
  if (useValuesAsDiscriminators && enumValues.some((value) => typeof value === "string")) {
    throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS, {
      stringValues: enumValues.filter((v) => typeof v === "string")
    });
  }
  return transformEncoder(prefix, (variant) => {
    const index2 = getEnumIndexFromVariant({ enumKeys, enumValues, variant });
    if (index2 < 0) {
      throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT, {
        formattedNumericalValues: formatNumericalValues(numericalValues),
        numericalValues,
        stringValues,
        variant
      });
    }
    return useValuesAsDiscriminators ? enumValues[index2] : index2;
  });
}
function getEnumDecoder(constructor, config = {}) {
  const prefix = config.size ?? getU8Decoder();
  const useValuesAsDiscriminators = config.useValuesAsDiscriminators ?? false;
  const { enumKeys, enumValues, numericalValues } = getEnumStats(constructor);
  if (useValuesAsDiscriminators && enumValues.some((value) => typeof value === "string")) {
    throw new SolanaError(SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS, {
      stringValues: enumValues.filter((v) => typeof v === "string")
    });
  }
  return transformDecoder(prefix, (value) => {
    const discriminator = Number(value);
    const index2 = getEnumIndexFromDiscriminator({
      discriminator,
      enumKeys,
      enumValues,
      useValuesAsDiscriminators
    });
    if (index2 < 0) {
      const validDiscriminators = useValuesAsDiscriminators ? numericalValues : [...Array(enumKeys.length).keys()];
      throw new SolanaError(SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE, {
        discriminator,
        formattedValidDiscriminators: formatNumericalValues(validDiscriminators),
        validDiscriminators
      });
    }
    return enumValues[index2];
  });
}
function getEnumCodec(constructor, config = {}) {
  return combineCodec(getEnumEncoder(constructor, config), getEnumDecoder(constructor, config));
}
function getHiddenPrefixEncoder(encoder5, prefixedEncoders) {
  return transformEncoder(
    getTupleEncoder([...prefixedEncoders, encoder5]),
    (value) => [...prefixedEncoders.map(() => void 0), value]
  );
}
function getHiddenPrefixDecoder(decoder2, prefixedDecoders) {
  return transformDecoder(
    getTupleDecoder([...prefixedDecoders, decoder2]),
    (tuple) => tuple[tuple.length - 1]
  );
}
function getHiddenPrefixCodec(codec, prefixedCodecs) {
  return combineCodec(getHiddenPrefixEncoder(codec, prefixedCodecs), getHiddenPrefixDecoder(codec, prefixedCodecs));
}
function getHiddenSuffixEncoder(encoder5, suffixedEncoders) {
  return transformEncoder(
    getTupleEncoder([encoder5, ...suffixedEncoders]),
    (value) => [value, ...suffixedEncoders.map(() => void 0)]
  );
}
function getHiddenSuffixDecoder(decoder2, suffixedDecoders) {
  return transformDecoder(
    getTupleDecoder([decoder2, ...suffixedDecoders]),
    (tuple) => tuple[0]
  );
}
function getHiddenSuffixCodec(codec, suffixedCodecs) {
  return combineCodec(getHiddenSuffixEncoder(codec, suffixedCodecs), getHiddenSuffixDecoder(codec, suffixedCodecs));
}
function getLiteralUnionEncoder(variants, config = {}) {
  const discriminator = config.size ?? getU8Encoder();
  return transformEncoder(discriminator, (variant) => {
    const index2 = variants.indexOf(variant);
    if (index2 < 0) {
      throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT, {
        value: variant,
        variants
      });
    }
    return index2;
  });
}
function getLiteralUnionDecoder(variants, config = {}) {
  const discriminator = config.size ?? getU8Decoder();
  return transformDecoder(discriminator, (index2) => {
    if (index2 < 0 || index2 >= variants.length) {
      throw new SolanaError(SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE, {
        discriminator: index2,
        maxRange: variants.length - 1,
        minRange: 0
      });
    }
    return variants[Number(index2)];
  });
}
function getLiteralUnionCodec(variants, config = {}) {
  return combineCodec(getLiteralUnionEncoder(variants, config), getLiteralUnionDecoder(variants, config));
}
function getMapEncoder(key, value, config = {}) {
  return transformEncoder(
    getArrayEncoder(getTupleEncoder([key, value]), config),
    (map) => [...map.entries()]
  );
}
function getMapDecoder(key, value, config = {}) {
  return transformDecoder(
    getArrayDecoder(getTupleDecoder([key, value]), config),
    (entries) => new Map(entries)
  );
}
function getMapCodec(key, value, config = {}) {
  return combineCodec(getMapEncoder(key, value, config), getMapDecoder(key, value, config));
}
function getUnitEncoder() {
  return createEncoder({
    fixedSize: 0,
    write: (_value, _bytes, offset) => offset
  });
}
function getUnitDecoder() {
  return createDecoder({
    fixedSize: 0,
    read: (_bytes, offset) => [void 0, offset]
  });
}
function getUnitCodec() {
  return combineCodec(getUnitEncoder(), getUnitDecoder());
}
function getNullableEncoder(item, config = {}) {
  const prefix = (() => {
    if (config.prefix === null) {
      return transformEncoder(getUnitEncoder(), (_boolean) => void 0);
    }
    return getBooleanEncoder({ size: config.prefix ?? getU8Encoder() });
  })();
  const noneValue = (() => {
    if (config.noneValue === "zeroes") {
      assertIsFixedSize(item);
      return fixEncoderSize(getUnitEncoder(), item.fixedSize);
    }
    if (!config.noneValue) {
      return getUnitEncoder();
    }
    return getConstantEncoder(config.noneValue);
  })();
  return getUnionEncoder(
    [
      transformEncoder(getTupleEncoder([prefix, noneValue]), (_value) => [
        false,
        void 0
      ]),
      transformEncoder(getTupleEncoder([prefix, item]), (value) => [true, value])
    ],
    (variant) => Number(variant !== null)
  );
}
function getNullableDecoder(item, config = {}) {
  const prefix = (() => {
    if (config.prefix === null) {
      return transformDecoder(getUnitDecoder(), () => false);
    }
    return getBooleanDecoder({ size: config.prefix ?? getU8Decoder() });
  })();
  const noneValue = (() => {
    if (config.noneValue === "zeroes") {
      assertIsFixedSize(item);
      return fixDecoderSize(getUnitDecoder(), item.fixedSize);
    }
    if (!config.noneValue) {
      return getUnitDecoder();
    }
    return getConstantDecoder(config.noneValue);
  })();
  return getUnionDecoder(
    [
      transformDecoder(getTupleDecoder([prefix, noneValue]), () => null),
      transformDecoder(getTupleDecoder([prefix, item]), ([, value]) => value)
    ],
    (bytes, offset) => {
      if (config.prefix === null && !config.noneValue) {
        return Number(offset < bytes.length);
      }
      if (config.prefix === null && config.noneValue != null) {
        const zeroValue = config.noneValue === "zeroes" ? new Uint8Array(noneValue.fixedSize).fill(0) : config.noneValue;
        return containsBytes(bytes, zeroValue, offset) ? 0 : 1;
      }
      return Number(prefix.read(bytes, offset)[0]);
    }
  );
}
function getNullableCodec(item, config = {}) {
  return combineCodec(
    getNullableEncoder(item, config),
    getNullableDecoder(item, config)
  );
}
function getSetEncoder(item, config = {}) {
  return transformEncoder(getArrayEncoder(item, config), (set) => [...set]);
}
function getSetDecoder(item, config = {}) {
  return transformDecoder(getArrayDecoder(item, config), (entries) => new Set(entries));
}
function getSetCodec(item, config = {}) {
  return combineCodec(getSetEncoder(item, config), getSetDecoder(item, config));
}
function getStructEncoder(fields) {
  const fieldCodecs = fields.map(([, codec]) => codec);
  const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));
  const maxSize = sumCodecSizes(fieldCodecs.map(getMaxSize)) ?? void 0;
  return createEncoder({
    ...fixedSize === null ? {
      getSizeFromValue: (value) => fields.map(([key, codec]) => getEncodedSize(value[key], codec)).reduce((all, one) => all + one, 0),
      maxSize
    } : { fixedSize },
    write: (struct, bytes, offset) => {
      fields.forEach(([key, codec]) => {
        offset = codec.write(struct[key], bytes, offset);
      });
      return offset;
    }
  });
}
function getStructDecoder(fields) {
  const fieldCodecs = fields.map(([, codec]) => codec);
  const fixedSize = sumCodecSizes(fieldCodecs.map(getFixedSize));
  const maxSize = sumCodecSizes(fieldCodecs.map(getMaxSize)) ?? void 0;
  return createDecoder({
    ...fixedSize === null ? { maxSize } : { fixedSize },
    read: (bytes, offset) => {
      const struct = {};
      fields.forEach(([key, codec]) => {
        const [value, newOffset] = codec.read(bytes, offset);
        offset = newOffset;
        struct[key] = value;
      });
      return [struct, offset];
    }
  });
}
function getStructCodec(fields) {
  return combineCodec(
    getStructEncoder(fields),
    getStructDecoder(fields)
  );
}
var getBase16Decoder2;
var init_index_node8 = __esm({
  "node_modules/@solana/codecs-data-structures/dist/index.node.mjs"() {
    "use strict";
    init_index_node2();
    init_index_node7();
    init_index_node();
    getBase16Decoder2 = () => createDecoder({
      read(bytes, offset) {
        const value = bytes.slice(offset).reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
        return [value, bytes.length];
      }
    });
  }
});

// node_modules/@solana/options/dist/index.node.mjs
function unwrapOption(option, fallback) {
  if (isSome(option)) return option.value;
  return fallback ? fallback() : null;
}
function getOptionEncoder(item, config = {}) {
  const prefix = (() => {
    if (config.prefix === null) {
      return transformEncoder(getUnitEncoder(), (_boolean) => void 0);
    }
    return getBooleanEncoder({ size: config.prefix ?? getU8Encoder() });
  })();
  const noneValue = (() => {
    if (config.noneValue === "zeroes") {
      assertIsFixedSize(item);
      return fixEncoderSize(getUnitEncoder(), item.fixedSize);
    }
    if (!config.noneValue) {
      return getUnitEncoder();
    }
    return getConstantEncoder(config.noneValue);
  })();
  return getUnionEncoder(
    [
      transformEncoder(getTupleEncoder([prefix, noneValue]), (_value) => [
        false,
        void 0
      ]),
      transformEncoder(getTupleEncoder([prefix, item]), (value) => [
        true,
        isOption(value) && isSome(value) ? value.value : value
      ])
    ],
    (variant) => {
      const option = isOption(variant) ? variant : wrapNullable(variant);
      return Number(isSome(option));
    }
  );
}
function getOptionDecoder(item, config = {}) {
  const prefix = (() => {
    if (config.prefix === null) {
      return transformDecoder(getUnitDecoder(), () => false);
    }
    return getBooleanDecoder({ size: config.prefix ?? getU8Decoder() });
  })();
  const noneValue = (() => {
    if (config.noneValue === "zeroes") {
      assertIsFixedSize(item);
      return fixDecoderSize(getUnitDecoder(), item.fixedSize);
    }
    if (!config.noneValue) {
      return getUnitDecoder();
    }
    return getConstantDecoder(config.noneValue);
  })();
  return getUnionDecoder(
    [
      transformDecoder(getTupleDecoder([prefix, noneValue]), () => none()),
      transformDecoder(getTupleDecoder([prefix, item]), ([, value]) => some(value))
    ],
    (bytes, offset) => {
      if (config.prefix === null && !config.noneValue) {
        return Number(offset < bytes.length);
      }
      if (config.prefix === null && config.noneValue != null) {
        const zeroValue = config.noneValue === "zeroes" ? new Uint8Array(noneValue.fixedSize).fill(0) : config.noneValue;
        return containsBytes(bytes, zeroValue, offset) ? 0 : 1;
      }
      return Number(prefix.read(bytes, offset)[0]);
    }
  );
}
function getOptionCodec(item, config = {}) {
  return combineCodec(
    getOptionEncoder(item, config),
    getOptionDecoder(item, config)
  );
}
function unwrapOptionRecursively(input, fallback) {
  if (!input || ArrayBuffer.isView(input)) {
    return input;
  }
  const next = (x) => fallback ? unwrapOptionRecursively(x, fallback) : unwrapOptionRecursively(x);
  if (isOption(input)) {
    if (isSome(input)) return next(input.value);
    return fallback ? fallback() : null;
  }
  if (Array.isArray(input)) {
    return input.map(next);
  }
  if (typeof input === "object") {
    return Object.fromEntries(Object.entries(input).map(([k, v]) => [k, next(v)]));
  }
  return input;
}
var some, none, isOption, isSome, isNone, wrapNullable;
var init_index_node9 = __esm({
  "node_modules/@solana/options/dist/index.node.mjs"() {
    "use strict";
    init_index_node2();
    init_index_node8();
    init_index_node7();
    some = (value) => ({ __option: "Some", value });
    none = () => ({ __option: "None" });
    isOption = (input) => !!(input && typeof input === "object" && "__option" in input && (input.__option === "Some" && "value" in input || input.__option === "None"));
    isSome = (option) => option.__option === "Some";
    isNone = (option) => option.__option === "None";
    wrapNullable = (nullable) => nullable !== null ? some(nullable) : none();
  }
});

// node_modules/@solana/codecs/dist/index.node.mjs
var init_index_node10 = __esm({
  "node_modules/@solana/codecs/dist/index.node.mjs"() {
    "use strict";
    init_index_node2();
    init_index_node8();
    init_index_node7();
    init_index_node3();
    init_index_node9();
  }
});

// node_modules/@solana/functional/dist/index.node.mjs
function pipe(init, ...fns) {
  return fns.reduce((acc, fn) => fn(acc), init);
}
var init_index_node11 = __esm({
  "node_modules/@solana/functional/dist/index.node.mjs"() {
    "use strict";
  }
});

// node_modules/@solana/instructions/dist/index.node.mjs
function isInstructionForProgram(instruction, programAddress) {
  return instruction.programAddress === programAddress;
}
function assertIsInstructionForProgram(instruction, programAddress) {
  if (instruction.programAddress !== programAddress) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH, {
      actualProgramAddress: instruction.programAddress,
      expectedProgramAddress: programAddress
    });
  }
}
function isInstructionWithAccounts(instruction) {
  return instruction.accounts !== void 0;
}
function assertIsInstructionWithAccounts(instruction) {
  if (instruction.accounts === void 0) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS, {
      data: instruction.data,
      programAddress: instruction.programAddress
    });
  }
}
function isInstructionWithData(instruction) {
  return instruction.data !== void 0;
}
function assertIsInstructionWithData(instruction) {
  if (instruction.data === void 0) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA, {
      accountAddresses: instruction.accounts?.map((a) => a.address),
      programAddress: instruction.programAddress
    });
  }
}
function downgradeRoleToNonSigner(role) {
  return role & ~IS_SIGNER_BITMASK;
}
function downgradeRoleToReadonly(role) {
  return role & ~IS_WRITABLE_BITMASK;
}
function isSignerRole(role) {
  return role >= 2;
}
function isWritableRole(role) {
  return (role & IS_WRITABLE_BITMASK) !== 0;
}
function mergeRoles(roleA, roleB) {
  return roleA | roleB;
}
function upgradeRoleToSigner(role) {
  return role | IS_SIGNER_BITMASK;
}
function upgradeRoleToWritable(role) {
  return role | IS_WRITABLE_BITMASK;
}
var AccountRole, IS_SIGNER_BITMASK, IS_WRITABLE_BITMASK;
var init_index_node12 = __esm({
  "node_modules/@solana/instructions/dist/index.node.mjs"() {
    "use strict";
    init_index_node();
    AccountRole = /* @__PURE__ */ ((AccountRole2) => {
      AccountRole2[AccountRole2["WRITABLE_SIGNER"] = /* 3 */
      3] = "WRITABLE_SIGNER";
      AccountRole2[AccountRole2["READONLY_SIGNER"] = /* 2 */
      2] = "READONLY_SIGNER";
      AccountRole2[AccountRole2["WRITABLE"] = /* 1 */
      1] = "WRITABLE";
      AccountRole2[AccountRole2["READONLY"] = /* 0 */
      0] = "READONLY";
      return AccountRole2;
    })(AccountRole || {});
    IS_SIGNER_BITMASK = 2;
    IS_WRITABLE_BITMASK = 1;
  }
});

// node_modules/@solana/rpc-types/dist/index.node.mjs
function isBlockhash(putativeBlockhash) {
  return isAddress2(putativeBlockhash);
}
function assertIsBlockhash(putativeBlockhash) {
  try {
    assertIsAddress(putativeBlockhash);
  } catch (error) {
    if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE)) {
      throw new SolanaError(SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE, error.context);
    }
    if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH)) {
      throw new SolanaError(SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH, error.context);
    }
    throw error;
  }
}
function blockhash(putativeBlockhash) {
  assertIsBlockhash(putativeBlockhash);
  return putativeBlockhash;
}
function getBlockhashEncoder() {
  const addressEncoder = getAddressEncoder();
  return createEncoder({
    fixedSize: 32,
    write: (value, bytes, offset) => {
      assertIsBlockhash(value);
      return addressEncoder.write(value, bytes, offset);
    }
  });
}
function getBlockhashDecoder() {
  return getAddressDecoder();
}
function getBlockhashCodec() {
  return combineCodec(getBlockhashEncoder(), getBlockhashDecoder());
}
function getBlockhashComparator() {
  return new Intl.Collator("en", {
    caseFirst: "lower",
    ignorePunctuation: false,
    localeMatcher: "best fit",
    numeric: false,
    sensitivity: "variant",
    usage: "sort"
  }).compare;
}
function mainnet(putativeString) {
  return putativeString;
}
function devnet(putativeString) {
  return putativeString;
}
function testnet(putativeString) {
  return putativeString;
}
function getCommitmentScore(commitment) {
  switch (commitment) {
    case "finalized":
      return 2;
    case "confirmed":
      return 1;
    case "processed":
      return 0;
    default:
      throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {
        unexpectedValue: commitment
      });
  }
}
function commitmentComparator(a, b) {
  if (a === b) {
    return 0;
  }
  return getCommitmentScore(a) < getCommitmentScore(b) ? -1 : 1;
}
function getMemoizedU64Encoder() {
  if (!memoizedU64Encoder) memoizedU64Encoder = getU64Encoder();
  return memoizedU64Encoder;
}
function getMemoizedU64Decoder() {
  if (!memoizedU64Decoder) memoizedU64Decoder = getU64Decoder();
  return memoizedU64Decoder;
}
function isLamports(putativeLamports) {
  return putativeLamports >= 0 && putativeLamports <= maxU64Value;
}
function assertIsLamports(putativeLamports) {
  if (putativeLamports < 0 || putativeLamports > maxU64Value) {
    throw new SolanaError(SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE);
  }
}
function lamports(putativeLamports) {
  assertIsLamports(putativeLamports);
  return putativeLamports;
}
function getDefaultLamportsEncoder() {
  return getLamportsEncoder(getMemoizedU64Encoder());
}
function getLamportsEncoder(innerEncoder) {
  return innerEncoder;
}
function getDefaultLamportsDecoder() {
  return getLamportsDecoder(getMemoizedU64Decoder());
}
function getLamportsDecoder(innerDecoder) {
  return transformDecoder(
    innerDecoder,
    (value) => lamports(typeof value === "bigint" ? value : BigInt(value))
  );
}
function getDefaultLamportsCodec() {
  return combineCodec(getDefaultLamportsEncoder(), getDefaultLamportsDecoder());
}
function getLamportsCodec(innerCodec) {
  return combineCodec(getLamportsEncoder(innerCodec), getLamportsDecoder(innerCodec));
}
function isStringifiedBigInt(putativeBigInt) {
  try {
    BigInt(putativeBigInt);
    return true;
  } catch {
    return false;
  }
}
function assertIsStringifiedBigInt(putativeBigInt) {
  try {
    BigInt(putativeBigInt);
  } catch {
    throw new SolanaError(SOLANA_ERROR__MALFORMED_BIGINT_STRING, {
      value: putativeBigInt
    });
  }
}
function stringifiedBigInt(putativeBigInt) {
  assertIsStringifiedBigInt(putativeBigInt);
  return putativeBigInt;
}
function isStringifiedNumber(putativeNumber) {
  return !Number.isNaN(Number(putativeNumber));
}
function assertIsStringifiedNumber(putativeNumber) {
  if (Number.isNaN(Number(putativeNumber))) {
    throw new SolanaError(SOLANA_ERROR__MALFORMED_NUMBER_STRING, {
      value: putativeNumber
    });
  }
}
function stringifiedNumber(putativeNumber) {
  assertIsStringifiedNumber(putativeNumber);
  return putativeNumber;
}
function isUnixTimestamp(putativeTimestamp) {
  return putativeTimestamp >= minI64Value && putativeTimestamp <= maxI64Value;
}
function assertIsUnixTimestamp(putativeTimestamp) {
  if (putativeTimestamp < minI64Value || putativeTimestamp > maxI64Value) {
    throw new SolanaError(SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE, {
      value: putativeTimestamp
    });
  }
}
function unixTimestamp(putativeTimestamp) {
  assertIsUnixTimestamp(putativeTimestamp);
  return putativeTimestamp;
}
var maxU64Value, memoizedU64Encoder, memoizedU64Decoder, maxI64Value, minI64Value;
var init_index_node13 = __esm({
  "node_modules/@solana/rpc-types/dist/index.node.mjs"() {
    "use strict";
    init_index_node6();
    init_index_node2();
    init_index_node();
    init_index_node7();
    maxU64Value = 18446744073709551615n;
    maxI64Value = 9223372036854775807n;
    minI64Value = -9223372036854775808n;
  }
});

// node_modules/@solana/transaction-messages/dist/index.node.mjs
function isTransactionMessageWithBlockhashLifetime(transactionMessage) {
  return "lifetimeConstraint" in transactionMessage && typeof transactionMessage.lifetimeConstraint.blockhash === "string" && typeof transactionMessage.lifetimeConstraint.lastValidBlockHeight === "bigint" && isBlockhash(transactionMessage.lifetimeConstraint.blockhash);
}
function assertIsTransactionMessageWithBlockhashLifetime(transactionMessage) {
  if (!isTransactionMessageWithBlockhashLifetime(transactionMessage)) {
    throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME);
  }
}
function setTransactionMessageLifetimeUsingBlockhash(blockhashLifetimeConstraint, transactionMessage) {
  if ("lifetimeConstraint" in transactionMessage && transactionMessage.lifetimeConstraint && "blockhash" in transactionMessage.lifetimeConstraint && transactionMessage.lifetimeConstraint.blockhash === blockhashLifetimeConstraint.blockhash && transactionMessage.lifetimeConstraint.lastValidBlockHeight === blockhashLifetimeConstraint.lastValidBlockHeight) {
    return transactionMessage;
  }
  return Object.freeze({
    ...transactionMessage,
    lifetimeConstraint: Object.freeze(blockhashLifetimeConstraint)
  });
}
function assertValidBaseString2(alphabet4, testValue, givenValue = testValue) {
  if (!testValue.match(new RegExp(`^[${alphabet4}]*$`))) {
    throw new SolanaError(SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE, {
      alphabet: alphabet4,
      base: alphabet4.length,
      value: givenValue
    });
  }
}
function partitionLeadingZeroes2(value, zeroCharacter) {
  const [leadingZeros, tailChars] = value.split(new RegExp(`((?!${zeroCharacter}).*)`));
  return [leadingZeros, tailChars];
}
function getBigIntFromBaseX2(value, alphabet4) {
  const base2 = BigInt(alphabet4.length);
  let sum = 0n;
  for (const char of value) {
    sum *= base2;
    sum += BigInt(alphabet4.indexOf(char));
  }
  return sum;
}
function getBaseXFromBigInt2(value, alphabet4) {
  const base2 = BigInt(alphabet4.length);
  const tailChars = [];
  while (value > 0n) {
    tailChars.unshift(alphabet4[Number(value % base2)]);
    value /= base2;
  }
  return tailChars.join("");
}
function getAddressTableLookupEncoder() {
  if (!memoizedAddressTableLookupEncoder) {
    const indexEncoder = getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() });
    memoizedAddressTableLookupEncoder = getStructEncoder([
      ["lookupTableAddress", getAddressEncoder()],
      ["writableIndexes", indexEncoder],
      ["readonlyIndexes", indexEncoder]
    ]);
  }
  return memoizedAddressTableLookupEncoder;
}
function getAddressTableLookupDecoder() {
  if (!memoizedAddressTableLookupDecoder) {
    const indexEncoder = getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() });
    memoizedAddressTableLookupDecoder = getStructDecoder([
      ["lookupTableAddress", getAddressDecoder()],
      ["writableIndexes", indexEncoder],
      ["readonlyIndexes", indexEncoder]
    ]);
  }
  return memoizedAddressTableLookupDecoder;
}
function getMemoizedU8Encoder() {
  if (!memoizedU8Encoder) memoizedU8Encoder = getU8Encoder();
  return memoizedU8Encoder;
}
function getMemoizedU8Decoder() {
  if (!memoizedU8Decoder) memoizedU8Decoder = getU8Decoder();
  return memoizedU8Decoder;
}
function getMessageHeaderEncoder() {
  return getStructEncoder([
    ["numSignerAccounts", getMemoizedU8Encoder()],
    ["numReadonlySignerAccounts", getMemoizedU8Encoder()],
    ["numReadonlyNonSignerAccounts", getMemoizedU8Encoder()]
  ]);
}
function getMessageHeaderDecoder() {
  return getStructDecoder([
    ["numSignerAccounts", getMemoizedU8Decoder()],
    ["numReadonlySignerAccounts", getMemoizedU8Decoder()],
    ["numReadonlyNonSignerAccounts", getMemoizedU8Decoder()]
  ]);
}
function getInstructionEncoder() {
  if (!memoizedGetInstructionEncoder) {
    memoizedGetInstructionEncoder = transformEncoder(
      getStructEncoder([
        ["programAddressIndex", getU8Encoder()],
        ["accountIndices", getArrayEncoder(getU8Encoder(), { size: getShortU16Encoder() })],
        ["data", addEncoderSizePrefix(getBytesEncoder(), getShortU16Encoder())]
      ]),
      // Convert an instruction to have all fields defined
      (instruction) => {
        if (instruction.accountIndices !== void 0 && instruction.data !== void 0) {
          return instruction;
        }
        return {
          ...instruction,
          accountIndices: instruction.accountIndices ?? [],
          data: instruction.data ?? new Uint8Array(0)
        };
      }
    );
  }
  return memoizedGetInstructionEncoder;
}
function getInstructionDecoder() {
  if (!memoizedGetInstructionDecoder) {
    memoizedGetInstructionDecoder = transformDecoder(
      getStructDecoder([
        ["programAddressIndex", getU8Decoder()],
        ["accountIndices", getArrayDecoder(getU8Decoder(), { size: getShortU16Decoder() })],
        [
          "data",
          addDecoderSizePrefix(getBytesDecoder(), getShortU16Decoder())
        ]
      ]),
      // Convert an instruction to exclude optional fields if they are empty
      (instruction) => {
        if (instruction.accountIndices.length && instruction.data.byteLength) {
          return instruction;
        }
        const { accountIndices, data, ...rest } = instruction;
        return {
          ...rest,
          ...accountIndices.length ? { accountIndices } : null,
          ...data.byteLength ? { data } : null
        };
      }
    );
  }
  return memoizedGetInstructionDecoder;
}
function getTransactionVersionEncoder() {
  return createEncoder({
    getSizeFromValue: (value) => value === "legacy" ? 0 : 1,
    maxSize: 1,
    write: (value, bytes, offset) => {
      if (value === "legacy") {
        return offset;
      }
      if (value < 0 || value > 127) {
        throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE, {
          actualVersion: value
        });
      }
      if (value > MAX_SUPPORTED_TRANSACTION_VERSION) {
        throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, {
          unsupportedVersion: value
        });
      }
      bytes.set([value | VERSION_FLAG_MASK], offset);
      return offset + 1;
    }
  });
}
function getTransactionVersionDecoder() {
  return createDecoder({
    maxSize: 1,
    read: (bytes, offset) => {
      const firstByte = bytes[offset];
      if ((firstByte & VERSION_FLAG_MASK) === 0) {
        return ["legacy", offset];
      } else {
        const version4 = firstByte ^ VERSION_FLAG_MASK;
        if (version4 > MAX_SUPPORTED_TRANSACTION_VERSION) {
          throw new SolanaError(SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED, {
            unsupportedVersion: version4
          });
        }
        return [version4, offset + 1];
      }
    }
  });
}
function getTransactionVersionCodec() {
  return combineCodec(getTransactionVersionEncoder(), getTransactionVersionDecoder());
}
function getCompiledMessageLegacyEncoder() {
  return getStructEncoder(getPreludeStructEncoderTuple());
}
function getCompiledMessageVersionedEncoder() {
  return transformEncoder(
    getStructEncoder([
      ...getPreludeStructEncoderTuple(),
      ["addressTableLookups", getAddressTableLookupArrayEncoder()]
    ]),
    (value) => {
      if (value.version === "legacy") {
        return value;
      }
      return {
        ...value,
        addressTableLookups: value.addressTableLookups ?? []
      };
    }
  );
}
function getPreludeStructEncoderTuple() {
  const lifetimeTokenEncoder = getUnionEncoder(
    [
      // Use a 32-byte constant encoder for a missing lifetime token (index 0).
      getConstantEncoder(new Uint8Array(32)),
      // Use a 32-byte base58 encoder for a valid lifetime token (index 1).
      fixEncoderSize(getBase58Encoder2(), 32)
    ],
    (value) => value === void 0 ? 0 : 1
  );
  return [
    ["version", getTransactionVersionEncoder()],
    ["header", getMessageHeaderEncoder()],
    ["staticAccounts", getArrayEncoder(getAddressEncoder(), { size: getShortU16Encoder() })],
    ["lifetimeToken", lifetimeTokenEncoder],
    ["instructions", getArrayEncoder(getInstructionEncoder(), { size: getShortU16Encoder() })]
  ];
}
function getPreludeStructDecoderTuple() {
  return [
    ["version", getTransactionVersionDecoder()],
    ["header", getMessageHeaderDecoder()],
    ["staticAccounts", getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() })],
    ["lifetimeToken", fixDecoderSize(getBase58Decoder2(), 32)],
    ["instructions", getArrayDecoder(getInstructionDecoder(), { size: getShortU16Decoder() })],
    ["addressTableLookups", getAddressTableLookupArrayDecoder()]
  ];
}
function getAddressTableLookupArrayEncoder() {
  return getArrayEncoder(getAddressTableLookupEncoder(), { size: getShortU16Encoder() });
}
function getAddressTableLookupArrayDecoder() {
  return getArrayDecoder(getAddressTableLookupDecoder(), { size: getShortU16Decoder() });
}
function getCompiledTransactionMessageEncoder() {
  return createEncoder({
    getSizeFromValue: (compiledMessage) => {
      if (compiledMessage.version === "legacy") {
        return getCompiledMessageLegacyEncoder().getSizeFromValue(compiledMessage);
      } else {
        return getCompiledMessageVersionedEncoder().getSizeFromValue(compiledMessage);
      }
    },
    write: (compiledMessage, bytes, offset) => {
      if (compiledMessage.version === "legacy") {
        return getCompiledMessageLegacyEncoder().write(compiledMessage, bytes, offset);
      } else {
        return getCompiledMessageVersionedEncoder().write(compiledMessage, bytes, offset);
      }
    }
  });
}
function getCompiledTransactionMessageDecoder() {
  return transformDecoder(
    getStructDecoder(getPreludeStructDecoderTuple()),
    ({ addressTableLookups, ...restOfMessage }) => {
      if (restOfMessage.version === "legacy" || !addressTableLookups?.length) {
        return restOfMessage;
      }
      return { ...restOfMessage, addressTableLookups };
    }
  );
}
function getCompiledTransactionMessageCodec() {
  return combineCodec(getCompiledTransactionMessageEncoder(), getCompiledTransactionMessageDecoder());
}
function upsert(addressMap, address2, update) {
  addressMap[address2] = update(addressMap[address2] ?? { role: AccountRole.READONLY });
}
function getAddressMapFromInstructions(feePayer, instructions) {
  const addressMap = {
    [feePayer]: { [TYPE2]: 0, role: AccountRole.WRITABLE_SIGNER }
  };
  const addressesOfInvokedPrograms = /* @__PURE__ */ new Set();
  for (const instruction of instructions) {
    upsert(addressMap, instruction.programAddress, (entry) => {
      addressesOfInvokedPrograms.add(instruction.programAddress);
      if (TYPE2 in entry) {
        if (isWritableRole(entry.role)) {
          switch (entry[TYPE2]) {
            case 0:
              throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES, {
                programAddress: instruction.programAddress
              });
            default:
              throw new SolanaError(SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE, {
                programAddress: instruction.programAddress
              });
          }
        }
        if (entry[TYPE2] === 2) {
          return entry;
        }
      }
      return { [TYPE2]: 2, role: AccountRole.READONLY };
    });
    let addressComparator;
    if (!instruction.accounts) {
      continue;
    }
    for (const account of instruction.accounts) {
      upsert(addressMap, account.address, (entry) => {
        const {
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          address: _,
          ...accountMeta
        } = account;
        if (TYPE2 in entry) {
          switch (entry[TYPE2]) {
            case 0:
              return entry;
            case 1: {
              const nextRole = mergeRoles(entry.role, accountMeta.role);
              if ("lookupTableAddress" in accountMeta) {
                const shouldReplaceEntry = (
                  // Consider using the new LOOKUP_TABLE if its address is different...
                  entry.lookupTableAddress !== accountMeta.lookupTableAddress && // ...and sorts before the existing one.
                  (addressComparator ||= getAddressComparator())(
                    accountMeta.lookupTableAddress,
                    entry.lookupTableAddress
                  ) < 0
                );
                if (shouldReplaceEntry) {
                  return {
                    [TYPE2]: 1,
                    ...accountMeta,
                    role: nextRole
                  };
                }
              } else if (isSignerRole(accountMeta.role)) {
                return {
                  [TYPE2]: 2,
                  role: nextRole
                };
              }
              if (entry.role !== nextRole) {
                return {
                  ...entry,
                  role: nextRole
                };
              } else {
                return entry;
              }
            }
            case 2: {
              const nextRole = mergeRoles(entry.role, accountMeta.role);
              if (
                // Check to see if this address represents a program that is invoked
                // in this transaction.
                addressesOfInvokedPrograms.has(account.address)
              ) {
                if (isWritableRole(accountMeta.role)) {
                  throw new SolanaError(
                    SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,
                    {
                      programAddress: account.address
                    }
                  );
                }
                if (entry.role !== nextRole) {
                  return {
                    ...entry,
                    role: nextRole
                  };
                } else {
                  return entry;
                }
              } else if ("lookupTableAddress" in accountMeta && // Static accounts can be 'upgraded' to lookup table accounts as
              // long as they are not require to sign the transaction.
              !isSignerRole(entry.role)) {
                return {
                  ...accountMeta,
                  [TYPE2]: 1,
                  role: nextRole
                };
              } else {
                if (entry.role !== nextRole) {
                  return {
                    ...entry,
                    role: nextRole
                  };
                } else {
                  return entry;
                }
              }
            }
          }
        }
        if ("lookupTableAddress" in accountMeta) {
          return {
            ...accountMeta,
            [TYPE2]: 1
            /* LOOKUP_TABLE */
          };
        } else {
          return {
            ...accountMeta,
            [TYPE2]: 2
            /* STATIC */
          };
        }
      });
    }
  }
  return addressMap;
}
function getOrderedAccountsFromAddressMap(addressMap) {
  let addressComparator;
  const orderedAccounts = Object.entries(addressMap).sort(([leftAddress, leftEntry], [rightAddress, rightEntry]) => {
    if (leftEntry[TYPE2] !== rightEntry[TYPE2]) {
      if (leftEntry[TYPE2] === 0) {
        return -1;
      } else if (rightEntry[TYPE2] === 0) {
        return 1;
      } else if (leftEntry[TYPE2] === 2) {
        return -1;
      } else if (rightEntry[TYPE2] === 2) {
        return 1;
      }
    }
    const leftIsSigner = isSignerRole(leftEntry.role);
    if (leftIsSigner !== isSignerRole(rightEntry.role)) {
      return leftIsSigner ? -1 : 1;
    }
    const leftIsWritable = isWritableRole(leftEntry.role);
    if (leftIsWritable !== isWritableRole(rightEntry.role)) {
      return leftIsWritable ? -1 : 1;
    }
    addressComparator ||= getAddressComparator();
    if (leftEntry[TYPE2] === 1 && rightEntry[TYPE2] === 1 && leftEntry.lookupTableAddress !== rightEntry.lookupTableAddress) {
      return addressComparator(leftEntry.lookupTableAddress, rightEntry.lookupTableAddress);
    } else {
      return addressComparator(leftAddress, rightAddress);
    }
  }).map(([address2, addressMeta]) => ({
    address: address2,
    ...addressMeta
  }));
  return orderedAccounts;
}
function getCompiledAddressTableLookups(orderedAccounts) {
  const index2 = {};
  for (const account of orderedAccounts) {
    if (!("lookupTableAddress" in account)) {
      continue;
    }
    const entry = index2[account.lookupTableAddress] ||= {
      readonlyIndexes: [],
      writableIndexes: []
    };
    if (account.role === AccountRole.WRITABLE) {
      entry.writableIndexes.push(account.addressIndex);
    } else {
      entry.readonlyIndexes.push(account.addressIndex);
    }
  }
  return Object.keys(index2).sort(getAddressComparator()).map((lookupTableAddress) => ({
    lookupTableAddress,
    ...index2[lookupTableAddress]
  }));
}
function getCompiledMessageHeader(orderedAccounts) {
  let numReadonlyNonSignerAccounts = 0;
  let numReadonlySignerAccounts = 0;
  let numSignerAccounts = 0;
  for (const account of orderedAccounts) {
    if ("lookupTableAddress" in account) {
      break;
    }
    const accountIsWritable = isWritableRole(account.role);
    if (isSignerRole(account.role)) {
      numSignerAccounts++;
      if (!accountIsWritable) {
        numReadonlySignerAccounts++;
      }
    } else if (!accountIsWritable) {
      numReadonlyNonSignerAccounts++;
    }
  }
  return {
    numReadonlyNonSignerAccounts,
    numReadonlySignerAccounts,
    numSignerAccounts
  };
}
function getAccountIndex(orderedAccounts) {
  const out = {};
  for (const [index2, account] of orderedAccounts.entries()) {
    out[account.address] = index2;
  }
  return out;
}
function getCompiledInstructions(instructions, orderedAccounts) {
  const accountIndex = getAccountIndex(orderedAccounts);
  return instructions.map(({ accounts, data, programAddress }) => {
    return {
      programAddressIndex: accountIndex[programAddress],
      ...accounts ? { accountIndices: accounts.map(({ address: address2 }) => accountIndex[address2]) } : null,
      ...data ? { data } : null
    };
  });
}
function getCompiledLifetimeToken(lifetimeConstraint) {
  if ("nonce" in lifetimeConstraint) {
    return lifetimeConstraint.nonce;
  }
  return lifetimeConstraint.blockhash;
}
function getCompiledStaticAccounts(orderedAccounts) {
  const firstLookupTableAccountIndex = orderedAccounts.findIndex((account) => "lookupTableAddress" in account);
  const orderedStaticAccounts = firstLookupTableAccountIndex === -1 ? orderedAccounts : orderedAccounts.slice(0, firstLookupTableAccountIndex);
  return orderedStaticAccounts.map(({ address: address2 }) => address2);
}
function compileTransactionMessage(transactionMessage) {
  const addressMap = getAddressMapFromInstructions(
    transactionMessage.feePayer.address,
    transactionMessage.instructions
  );
  const orderedAccounts = getOrderedAccountsFromAddressMap(addressMap);
  const lifetimeConstraint = transactionMessage.lifetimeConstraint;
  return {
    ...transactionMessage.version !== "legacy" ? { addressTableLookups: getCompiledAddressTableLookups(orderedAccounts) } : null,
    ...lifetimeConstraint ? { lifetimeToken: getCompiledLifetimeToken(lifetimeConstraint) } : null,
    header: getCompiledMessageHeader(orderedAccounts),
    instructions: getCompiledInstructions(transactionMessage.instructions, orderedAccounts),
    staticAccounts: getCompiledStaticAccounts(orderedAccounts),
    version: transactionMessage.version
  };
}
function findAddressInLookupTables(address2, role, addressesByLookupTableAddress) {
  for (const [lookupTableAddress, addresses] of Object.entries(addressesByLookupTableAddress)) {
    for (let i = 0; i < addresses.length; i++) {
      if (address2 === addresses[i]) {
        return {
          address: address2,
          addressIndex: i,
          lookupTableAddress,
          role
        };
      }
    }
  }
}
function compressTransactionMessageUsingAddressLookupTables(transactionMessage, addressesByLookupTableAddress) {
  const programAddresses = new Set(transactionMessage.instructions.map((ix) => ix.programAddress));
  const eligibleLookupAddresses = new Set(
    Object.values(addressesByLookupTableAddress).flatMap((a) => a).filter((address2) => !programAddresses.has(address2))
  );
  const newInstructions = [];
  let updatedAnyInstructions = false;
  for (const instruction of transactionMessage.instructions) {
    if (!instruction.accounts) {
      newInstructions.push(instruction);
      continue;
    }
    const newAccounts = [];
    let updatedAnyAccounts = false;
    for (const account of instruction.accounts) {
      if ("lookupTableAddress" in account || !eligibleLookupAddresses.has(account.address) || isSignerRole(account.role)) {
        newAccounts.push(account);
        continue;
      }
      const lookupMetaAccount = findAddressInLookupTables(
        account.address,
        account.role,
        addressesByLookupTableAddress
      );
      newAccounts.push(Object.freeze(lookupMetaAccount));
      updatedAnyAccounts = true;
      updatedAnyInstructions = true;
    }
    newInstructions.push(
      Object.freeze(updatedAnyAccounts ? { ...instruction, accounts: newAccounts } : instruction)
    );
  }
  return Object.freeze(
    updatedAnyInstructions ? { ...transactionMessage, instructions: newInstructions } : transactionMessage
  );
}
function createTransactionMessage(config) {
  return Object.freeze({
    instructions: Object.freeze([]),
    version: config.version
  });
}
function createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress) {
  return {
    accounts: [
      { address: nonceAccountAddress, role: AccountRole.WRITABLE },
      {
        address: RECENT_BLOCKHASHES_SYSVAR_ADDRESS,
        role: AccountRole.READONLY
      },
      { address: nonceAuthorityAddress, role: AccountRole.READONLY_SIGNER }
    ],
    data: new Uint8Array([4, 0, 0, 0]),
    programAddress: SYSTEM_PROGRAM_ADDRESS
  };
}
function isAdvanceNonceAccountInstruction(instruction) {
  return instruction.programAddress === SYSTEM_PROGRAM_ADDRESS && // Test for `AdvanceNonceAccount` instruction data
  instruction.data != null && isAdvanceNonceAccountInstructionData(instruction.data) && // Test for exactly 3 accounts
  instruction.accounts?.length === 3 && // First account is nonce account address
  instruction.accounts[0].address != null && instruction.accounts[0].role === AccountRole.WRITABLE && // Second account is recent blockhashes sysvar
  instruction.accounts[1].address === RECENT_BLOCKHASHES_SYSVAR_ADDRESS && instruction.accounts[1].role === AccountRole.READONLY && // Third account is nonce authority account
  instruction.accounts[2].address != null && isSignerRole(instruction.accounts[2].role);
}
function isAdvanceNonceAccountInstructionData(data) {
  return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;
}
function isTransactionMessageWithDurableNonceLifetime(transactionMessage) {
  return "lifetimeConstraint" in transactionMessage && typeof transactionMessage.lifetimeConstraint.nonce === "string" && transactionMessage.instructions[0] != null && isAdvanceNonceAccountInstruction(transactionMessage.instructions[0]);
}
function assertIsTransactionMessageWithDurableNonceLifetime(transactionMessage) {
  if (!isTransactionMessageWithDurableNonceLifetime(transactionMessage)) {
    throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME);
  }
}
function isAdvanceNonceAccountInstructionForNonce(instruction, nonceAccountAddress, nonceAuthorityAddress) {
  return instruction.accounts[0].address === nonceAccountAddress && instruction.accounts[2].address === nonceAuthorityAddress;
}
function setTransactionMessageLifetimeUsingDurableNonce({
  nonce,
  nonceAccountAddress,
  nonceAuthorityAddress
}, transactionMessage) {
  let newInstructions;
  const firstInstruction = transactionMessage.instructions[0];
  if (firstInstruction && isAdvanceNonceAccountInstruction(firstInstruction)) {
    if (isAdvanceNonceAccountInstructionForNonce(firstInstruction, nonceAccountAddress, nonceAuthorityAddress)) {
      if (isTransactionMessageWithDurableNonceLifetime(transactionMessage) && transactionMessage.lifetimeConstraint.nonce === nonce) {
        return transactionMessage;
      } else {
        newInstructions = [firstInstruction, ...transactionMessage.instructions.slice(1)];
      }
    } else {
      newInstructions = [
        Object.freeze(createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress)),
        ...transactionMessage.instructions.slice(1)
      ];
    }
  } else {
    newInstructions = [
      Object.freeze(createAdvanceNonceAccountInstruction(nonceAccountAddress, nonceAuthorityAddress)),
      ...transactionMessage.instructions
    ];
  }
  return Object.freeze({
    ...transactionMessage,
    instructions: Object.freeze(newInstructions),
    lifetimeConstraint: Object.freeze({ nonce })
  });
}
function setTransactionMessageFeePayer(feePayer, transactionMessage) {
  if ("feePayer" in transactionMessage && feePayer === transactionMessage.feePayer?.address && isAddressOnlyFeePayer(transactionMessage.feePayer)) {
    return transactionMessage;
  }
  const out = {
    ...transactionMessage,
    feePayer: Object.freeze({ address: feePayer })
  };
  Object.freeze(out);
  return out;
}
function isAddressOnlyFeePayer(feePayer) {
  return !!feePayer && "address" in feePayer && typeof feePayer.address === "string" && Object.keys(feePayer).length === 1;
}
function appendTransactionMessageInstruction(instruction, transactionMessage) {
  return appendTransactionMessageInstructions([instruction], transactionMessage);
}
function appendTransactionMessageInstructions(instructions, transactionMessage) {
  return Object.freeze({
    ...transactionMessage,
    instructions: Object.freeze([
      ...transactionMessage.instructions,
      ...instructions
    ])
  });
}
function prependTransactionMessageInstruction(instruction, transactionMessage) {
  return prependTransactionMessageInstructions([instruction], transactionMessage);
}
function prependTransactionMessageInstructions(instructions, transactionMessage) {
  return Object.freeze({
    ...transactionMessage,
    instructions: Object.freeze([
      ...instructions,
      ...transactionMessage.instructions
    ])
  });
}
function getAccountMetas(message) {
  const { header } = message;
  const numWritableSignerAccounts = header.numSignerAccounts - header.numReadonlySignerAccounts;
  const numWritableNonSignerAccounts = message.staticAccounts.length - header.numSignerAccounts - header.numReadonlyNonSignerAccounts;
  const accountMetas = [];
  let accountIndex = 0;
  for (let i = 0; i < numWritableSignerAccounts; i++) {
    accountMetas.push({
      address: message.staticAccounts[accountIndex],
      role: AccountRole.WRITABLE_SIGNER
    });
    accountIndex++;
  }
  for (let i = 0; i < header.numReadonlySignerAccounts; i++) {
    accountMetas.push({
      address: message.staticAccounts[accountIndex],
      role: AccountRole.READONLY_SIGNER
    });
    accountIndex++;
  }
  for (let i = 0; i < numWritableNonSignerAccounts; i++) {
    accountMetas.push({
      address: message.staticAccounts[accountIndex],
      role: AccountRole.WRITABLE
    });
    accountIndex++;
  }
  for (let i = 0; i < header.numReadonlyNonSignerAccounts; i++) {
    accountMetas.push({
      address: message.staticAccounts[accountIndex],
      role: AccountRole.READONLY
    });
    accountIndex++;
  }
  return accountMetas;
}
function getAddressLookupMetas(compiledAddressTableLookups, addressesByLookupTableAddress) {
  const compiledAddressTableLookupAddresses = compiledAddressTableLookups.map((l2) => l2.lookupTableAddress);
  const missing = compiledAddressTableLookupAddresses.filter((a) => addressesByLookupTableAddress[a] === void 0);
  if (missing.length > 0) {
    throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING, {
      lookupTableAddresses: missing
    });
  }
  const readOnlyMetas = [];
  const writableMetas = [];
  for (const lookup of compiledAddressTableLookups) {
    const addresses = addressesByLookupTableAddress[lookup.lookupTableAddress];
    const readonlyIndexes = lookup.readonlyIndexes;
    const writableIndexes = lookup.writableIndexes;
    const highestIndex = Math.max(...readonlyIndexes, ...writableIndexes);
    if (highestIndex >= addresses.length) {
      throw new SolanaError(
        SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,
        {
          highestKnownIndex: addresses.length - 1,
          highestRequestedIndex: highestIndex,
          lookupTableAddress: lookup.lookupTableAddress
        }
      );
    }
    const readOnlyForLookup = readonlyIndexes.map((r) => ({
      address: addresses[r],
      addressIndex: r,
      lookupTableAddress: lookup.lookupTableAddress,
      role: AccountRole.READONLY
    }));
    readOnlyMetas.push(...readOnlyForLookup);
    const writableForLookup = writableIndexes.map((w) => ({
      address: addresses[w],
      addressIndex: w,
      lookupTableAddress: lookup.lookupTableAddress,
      role: AccountRole.WRITABLE
    }));
    writableMetas.push(...writableForLookup);
  }
  return [...writableMetas, ...readOnlyMetas];
}
function convertInstruction(instruction, accountMetas) {
  const programAddress = accountMetas[instruction.programAddressIndex]?.address;
  if (!programAddress) {
    throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND, {
      index: instruction.programAddressIndex
    });
  }
  const accounts = instruction.accountIndices?.map((accountIndex) => accountMetas[accountIndex]);
  const { data } = instruction;
  return Object.freeze({
    programAddress,
    ...accounts && accounts.length ? { accounts: Object.freeze(accounts) } : {},
    ...data && data.length ? { data } : {}
  });
}
function getLifetimeConstraint(messageLifetimeToken, firstInstruction, lastValidBlockHeight) {
  if (!firstInstruction || !isAdvanceNonceAccountInstruction(firstInstruction)) {
    return {
      blockhash: messageLifetimeToken,
      lastValidBlockHeight: lastValidBlockHeight ?? 2n ** 64n - 1n
      // U64 MAX
    };
  } else {
    const nonceAccountAddress = firstInstruction.accounts[0].address;
    assertIsAddress(nonceAccountAddress);
    const nonceAuthorityAddress = firstInstruction.accounts[2].address;
    assertIsAddress(nonceAuthorityAddress);
    return {
      nonce: messageLifetimeToken,
      nonceAccountAddress,
      nonceAuthorityAddress
    };
  }
}
function decompileTransactionMessage(compiledTransactionMessage, config) {
  const feePayer = compiledTransactionMessage.staticAccounts[0];
  if (!feePayer) {
    throw new SolanaError(SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING);
  }
  const accountMetas = getAccountMetas(compiledTransactionMessage);
  const accountLookupMetas = "addressTableLookups" in compiledTransactionMessage && compiledTransactionMessage.addressTableLookups !== void 0 && compiledTransactionMessage.addressTableLookups.length > 0 ? getAddressLookupMetas(
    compiledTransactionMessage.addressTableLookups,
    config?.addressesByLookupTableAddress ?? {}
  ) : [];
  const transactionMetas = [...accountMetas, ...accountLookupMetas];
  const instructions = compiledTransactionMessage.instructions.map(
    (compiledInstruction) => convertInstruction(compiledInstruction, transactionMetas)
  );
  const firstInstruction = instructions[0];
  const lifetimeConstraint = getLifetimeConstraint(
    compiledTransactionMessage.lifetimeToken,
    firstInstruction,
    config?.lastValidBlockHeight
  );
  return pipe(
    createTransactionMessage({ version: compiledTransactionMessage.version }),
    (m) => setTransactionMessageFeePayer(feePayer, m),
    (m) => instructions.reduce(
      (acc, instruction) => appendTransactionMessageInstruction(instruction, acc),
      m
    ),
    (m) => "blockhash" in lifetimeConstraint ? setTransactionMessageLifetimeUsingBlockhash(lifetimeConstraint, m) : setTransactionMessageLifetimeUsingDurableNonce(lifetimeConstraint, m)
  );
}
var getBaseXEncoder2, getBaseXDecoder2, alphabet23, getBase58Encoder2, getBase58Decoder2, memoizedAddressTableLookupEncoder, memoizedAddressTableLookupDecoder, memoizedU8Encoder, memoizedU8Decoder, memoizedGetInstructionEncoder, memoizedGetInstructionDecoder, MAX_SUPPORTED_TRANSACTION_VERSION, VERSION_FLAG_MASK, TYPE2, RECENT_BLOCKHASHES_SYSVAR_ADDRESS, SYSTEM_PROGRAM_ADDRESS;
var init_index_node14 = __esm({
  "node_modules/@solana/transaction-messages/dist/index.node.mjs"() {
    "use strict";
    init_index_node();
    init_index_node13();
    init_index_node6();
    init_index_node2();
    init_index_node8();
    init_index_node7();
    init_index_node12();
    init_index_node11();
    getBaseXEncoder2 = (alphabet4) => {
      return createEncoder({
        getSizeFromValue: (value) => {
          const [leadingZeroes, tailChars] = partitionLeadingZeroes2(value, alphabet4[0]);
          if (!tailChars) return value.length;
          const base10Number = getBigIntFromBaseX2(tailChars, alphabet4);
          return leadingZeroes.length + Math.ceil(base10Number.toString(16).length / 2);
        },
        write(value, bytes, offset) {
          assertValidBaseString2(alphabet4, value);
          if (value === "") return offset;
          const [leadingZeroes, tailChars] = partitionLeadingZeroes2(value, alphabet4[0]);
          if (!tailChars) {
            bytes.set(new Uint8Array(leadingZeroes.length).fill(0), offset);
            return offset + leadingZeroes.length;
          }
          let base10Number = getBigIntFromBaseX2(tailChars, alphabet4);
          const tailBytes = [];
          while (base10Number > 0n) {
            tailBytes.unshift(Number(base10Number % 256n));
            base10Number /= 256n;
          }
          const bytesToAdd = [...Array(leadingZeroes.length).fill(0), ...tailBytes];
          bytes.set(bytesToAdd, offset);
          return offset + bytesToAdd.length;
        }
      });
    };
    getBaseXDecoder2 = (alphabet4) => {
      return createDecoder({
        read(rawBytes, offset) {
          const bytes = offset === 0 ? rawBytes : rawBytes.slice(offset);
          if (bytes.length === 0) return ["", 0];
          let trailIndex = bytes.findIndex((n) => n !== 0);
          trailIndex = trailIndex === -1 ? bytes.length : trailIndex;
          const leadingZeroes = alphabet4[0].repeat(trailIndex);
          if (trailIndex === bytes.length) return [leadingZeroes, rawBytes.length];
          const base10Number = bytes.slice(trailIndex).reduce((sum, byte) => sum * 256n + BigInt(byte), 0n);
          const tailChars = getBaseXFromBigInt2(base10Number, alphabet4);
          return [leadingZeroes + tailChars, rawBytes.length];
        }
      });
    };
    alphabet23 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
    getBase58Encoder2 = () => getBaseXEncoder2(alphabet23);
    getBase58Decoder2 = () => getBaseXDecoder2(alphabet23);
    MAX_SUPPORTED_TRANSACTION_VERSION = 0;
    VERSION_FLAG_MASK = 128;
    TYPE2 = /* @__PURE__ */ Symbol("AddressMapTypeProperty");
    RECENT_BLOCKHASHES_SYSVAR_ADDRESS = "SysvarRecentB1ockHashes11111111111111111111";
    SYSTEM_PROGRAM_ADDRESS = "11111111111111111111111111111111";
  }
});

// node_modules/@solana/keys/dist/index.node.mjs
function addPkcs8Header(bytes) {
  return new Uint8Array([
    /**
     * PKCS#8 header
     */
    48,
    // ASN.1 sequence tag
    46,
    // Length of sequence (46 more bytes)
    2,
    // ASN.1 integer tag
    1,
    // Length of integer
    0,
    // Version number
    48,
    // ASN.1 sequence tag
    5,
    // Length of sequence
    6,
    // ASN.1 object identifier tag
    3,
    // Length of object identifier
    // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112
    43,
    // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)
    101,
    // thawte(101)
    // Ed25519 identifier
    112,
    // id-Ed25519(112)
    /**
     * Private key payload
     */
    4,
    // ASN.1 octet string tag
    34,
    // String length (34 more bytes)
    // Private key bytes as octet string
    4,
    // ASN.1 octet string tag
    32,
    // String length (32 bytes)
    ...bytes
  ]);
}
async function createPrivateKeyFromBytes(bytes, extractable = false) {
  const actualLength = bytes.byteLength;
  if (actualLength !== 32) {
    throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH, {
      actualLength
    });
  }
  const privateKeyBytesPkcs8 = addPkcs8Header(bytes);
  return await crypto.subtle.importKey("pkcs8", privateKeyBytesPkcs8, ED25519_ALGORITHM_IDENTIFIER, extractable, [
    "sign"
  ]);
}
async function getPublicKeyFromPrivateKey(privateKey, extractable = false) {
  assertKeyExporterIsAvailable();
  if (privateKey.extractable === false) {
    throw new SolanaError(SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY, { key: privateKey });
  }
  const jwk = await crypto.subtle.exportKey("jwk", privateKey);
  return await crypto.subtle.importKey(
    "jwk",
    {
      crv: "Ed25519",
      ext: extractable,
      key_ops: ["verify"],
      kty: "OKP",
      x: jwk.x
    },
    "Ed25519",
    extractable,
    ["verify"]
  );
}
function assertIsSignature(putativeSignature) {
  if (!base58Encoder) base58Encoder = getBase58Encoder();
  if (
    // Lowest value (64 bytes of zeroes)
    putativeSignature.length < 64 || // Highest value (64 bytes of 255)
    putativeSignature.length > 88
  ) {
    throw new SolanaError(SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE, {
      actualLength: putativeSignature.length
    });
  }
  const bytes = base58Encoder.encode(putativeSignature);
  assertIsSignatureBytes(bytes);
}
function assertIsSignatureBytes(putativeSignatureBytes) {
  const numBytes = putativeSignatureBytes.byteLength;
  if (numBytes !== 64) {
    throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH, {
      actualLength: numBytes
    });
  }
}
function isSignature(putativeSignature) {
  if (!base58Encoder) base58Encoder = getBase58Encoder();
  if (
    // Lowest value (64 bytes of zeroes)
    putativeSignature.length < 64 || // Highest value (64 bytes of 255)
    putativeSignature.length > 88
  ) {
    return false;
  }
  const bytes = base58Encoder.encode(putativeSignature);
  return isSignatureBytes(bytes);
}
function isSignatureBytes(putativeSignatureBytes) {
  return putativeSignatureBytes.byteLength === 64;
}
async function signBytes(key, data) {
  assertSigningCapabilityIsAvailable();
  const signedData = await crypto.subtle.sign(ED25519_ALGORITHM_IDENTIFIER, key, toArrayBuffer(data));
  return new Uint8Array(signedData);
}
function signature(putativeSignature) {
  assertIsSignature(putativeSignature);
  return putativeSignature;
}
function signatureBytes(putativeSignatureBytes) {
  assertIsSignatureBytes(putativeSignatureBytes);
  return putativeSignatureBytes;
}
async function verifySignature(key, signature2, data) {
  assertVerificationCapabilityIsAvailable();
  return await crypto.subtle.verify(ED25519_ALGORITHM_IDENTIFIER, key, toArrayBuffer(signature2), toArrayBuffer(data));
}
async function generateKeyPair() {
  await assertKeyGenerationIsAvailable();
  const keyPair = await crypto.subtle.generateKey(
    /* algorithm */
    ED25519_ALGORITHM_IDENTIFIER,
    // Native implementation status: https://github.com/WICG/webcrypto-secure-curves/issues/20
    /* extractable */
    false,
    // Prevents the bytes of the private key from being visible to JS.
    /* allowed uses */
    ["sign", "verify"]
  );
  return keyPair;
}
async function createKeyPairFromBytes(bytes, extractable = false) {
  assertPRNGIsAvailable();
  if (bytes.byteLength !== 64) {
    throw new SolanaError(SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH, { byteLength: bytes.byteLength });
  }
  const [publicKey, privateKey] = await Promise.all([
    crypto.subtle.importKey(
      "raw",
      bytes.slice(32),
      ED25519_ALGORITHM_IDENTIFIER,
      /* extractable */
      true,
      [
        "verify"
      ]
    ),
    createPrivateKeyFromBytes(bytes.slice(0, 32), extractable)
  ]);
  const randomBytes8 = new Uint8Array(32);
  crypto.getRandomValues(randomBytes8);
  const signedData = await signBytes(privateKey, randomBytes8);
  const isValid2 = await verifySignature(publicKey, signedData, randomBytes8);
  if (!isValid2) {
    throw new SolanaError(SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY);
  }
  return { privateKey, publicKey };
}
async function createKeyPairFromPrivateKeyBytes(bytes, extractable = false) {
  const privateKeyPromise = createPrivateKeyFromBytes(bytes, extractable);
  const [publicKey, privateKey] = await Promise.all([
    // This nested promise makes things efficient by
    // creating the public key in parallel with the
    // second private key creation, if it is needed.
    (extractable ? privateKeyPromise : createPrivateKeyFromBytes(
      bytes,
      true
      /* extractable */
    )).then(
      async (privateKey2) => await getPublicKeyFromPrivateKey(
        privateKey2,
        true
        /* extractable */
      )
    ),
    privateKeyPromise
  ]);
  return { privateKey, publicKey };
}
var ED25519_ALGORITHM_IDENTIFIER, base58Encoder;
var init_index_node15 = __esm({
  "node_modules/@solana/keys/dist/index.node.mjs"() {
    "use strict";
    init_index_node5();
    init_index_node();
    init_index_node2();
    init_index_node3();
    ED25519_ALGORITHM_IDENTIFIER = // Resist the temptation to convert this to a simple string; As of version 133.0.3, Firefox
    // requires the object form of `AlgorithmIdentifier` and will throw a `DOMException` otherwise.
    Object.freeze({ name: "Ed25519" });
  }
});

// node_modules/@solana/transactions/dist/index.node.mjs
function getSignaturesToEncode(signaturesMap) {
  const signatures = Object.values(signaturesMap);
  if (signatures.length === 0) {
    throw new SolanaError(SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES);
  }
  return signatures.map((signature2) => {
    if (!signature2) {
      return new Uint8Array(64).fill(0);
    }
    return signature2;
  });
}
function getSignaturesEncoder() {
  return transformEncoder(
    getArrayEncoder(fixEncoderSize(getBytesEncoder(), 64), { size: getShortU16Encoder() }),
    getSignaturesToEncode
  );
}
function getTransactionEncoder() {
  return getStructEncoder([
    ["signatures", getSignaturesEncoder()],
    ["messageBytes", getBytesEncoder()]
  ]);
}
function getTransactionDecoder() {
  return transformDecoder(
    getStructDecoder([
      ["signatures", getArrayDecoder(fixDecoderSize(getBytesDecoder(), 64), { size: getShortU16Decoder() })],
      ["messageBytes", getBytesDecoder()]
    ]),
    decodePartiallyDecodedTransaction
  );
}
function getTransactionCodec() {
  return combineCodec(getTransactionEncoder(), getTransactionDecoder());
}
function decodePartiallyDecodedTransaction(transaction) {
  const { messageBytes, signatures } = transaction;
  const signerAddressesDecoder = getTupleDecoder([
    // read transaction version
    getTransactionVersionDecoder(),
    // read first byte of header, `numSignerAccounts`
    // padRight to skip the next 2 bytes, `numReadOnlySignedAccounts` and `numReadOnlyUnsignedAccounts` which we don't need
    padRightDecoder(getU8Decoder(), 2),
    // read static addresses
    getArrayDecoder(getAddressDecoder(), { size: getShortU16Decoder() })
  ]);
  const [_txVersion, numRequiredSignatures, staticAddresses] = signerAddressesDecoder.decode(messageBytes);
  const signerAddresses = staticAddresses.slice(0, numRequiredSignatures);
  if (signerAddresses.length !== signatures.length) {
    throw new SolanaError(SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH, {
      numRequiredSignatures,
      signaturesLength: signatures.length,
      signerAddresses
    });
  }
  const signaturesMap = {};
  signerAddresses.forEach((address2, index2) => {
    const signatureForAddress = signatures[index2];
    if (signatureForAddress.every((b) => b === 0)) {
      signaturesMap[address2] = null;
    } else {
      signaturesMap[address2] = signatureForAddress;
    }
  });
  return {
    messageBytes,
    signatures: Object.freeze(signaturesMap)
  };
}
function compiledInstructionIsAdvanceNonceInstruction(instruction, staticAddresses) {
  return staticAddresses[instruction.programAddressIndex] === SYSTEM_PROGRAM_ADDRESS2 && // Test for `AdvanceNonceAccount` instruction data
  instruction.data != null && isAdvanceNonceAccountInstructionData2(instruction.data) && // Test for exactly 3 accounts
  instruction.accountIndices?.length === 3;
}
function isAdvanceNonceAccountInstructionData2(data) {
  return data.byteLength === 4 && data[0] === 4 && data[1] === 0 && data[2] === 0 && data[3] === 0;
}
async function getTransactionLifetimeConstraintFromCompiledTransactionMessage(compiledTransactionMessage) {
  const firstInstruction = compiledTransactionMessage.instructions[0];
  const { staticAccounts } = compiledTransactionMessage;
  if (firstInstruction && compiledInstructionIsAdvanceNonceInstruction(firstInstruction, staticAccounts)) {
    const nonceAccountAddress = staticAccounts[firstInstruction.accountIndices[0]];
    if (!nonceAccountAddress) {
      throw new SolanaError(SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE, {
        nonce: compiledTransactionMessage.lifetimeToken
      });
    }
    return {
      nonce: compiledTransactionMessage.lifetimeToken,
      nonceAccountAddress
    };
  } else {
    return {
      blockhash: compiledTransactionMessage.lifetimeToken,
      // This is not known from the compiled message, so we set it to the maximum possible value
      lastValidBlockHeight: 0xffffffffffffffffn
    };
  }
}
function isTransactionWithBlockhashLifetime(transaction) {
  return "lifetimeConstraint" in transaction && "blockhash" in transaction.lifetimeConstraint && typeof transaction.lifetimeConstraint.blockhash === "string" && typeof transaction.lifetimeConstraint.lastValidBlockHeight === "bigint" && isBlockhash(transaction.lifetimeConstraint.blockhash);
}
function assertIsTransactionWithBlockhashLifetime(transaction) {
  if (!isTransactionWithBlockhashLifetime(transaction)) {
    throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME);
  }
}
function isTransactionWithDurableNonceLifetime(transaction) {
  return "lifetimeConstraint" in transaction && "nonce" in transaction.lifetimeConstraint && typeof transaction.lifetimeConstraint.nonce === "string" && typeof transaction.lifetimeConstraint.nonceAccountAddress === "string" && isAddress2(transaction.lifetimeConstraint.nonceAccountAddress);
}
function assertIsTransactionWithDurableNonceLifetime(transaction) {
  if (!isTransactionWithDurableNonceLifetime(transaction)) {
    throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME);
  }
}
function compileTransaction(transactionMessage) {
  const compiledMessage = compileTransactionMessage(transactionMessage);
  const messageBytes = getCompiledTransactionMessageEncoder().encode(compiledMessage);
  const transactionSigners = compiledMessage.staticAccounts.slice(0, compiledMessage.header.numSignerAccounts);
  const signatures = {};
  for (const signerAddress of transactionSigners) {
    signatures[signerAddress] = null;
  }
  let lifetimeConstraint;
  if (isTransactionMessageWithBlockhashLifetime(transactionMessage)) {
    lifetimeConstraint = {
      blockhash: transactionMessage.lifetimeConstraint.blockhash,
      lastValidBlockHeight: transactionMessage.lifetimeConstraint.lastValidBlockHeight
    };
  } else if (isTransactionMessageWithDurableNonceLifetime(transactionMessage)) {
    lifetimeConstraint = {
      nonce: transactionMessage.lifetimeConstraint.nonce,
      nonceAccountAddress: transactionMessage.instructions[0].accounts[0].address
    };
  }
  return Object.freeze({
    ...lifetimeConstraint ? { lifetimeConstraint } : void 0,
    messageBytes,
    signatures: Object.freeze(signatures)
  });
}
function getSignatureFromTransaction(transaction) {
  if (!base58Decoder) base58Decoder = getBase58Decoder();
  const signatureBytes2 = Object.values(transaction.signatures)[0];
  if (!signatureBytes2) {
    throw new SolanaError(SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING);
  }
  const transactionSignature = base58Decoder.decode(signatureBytes2);
  return transactionSignature;
}
async function partiallySignTransaction(keyPairs, transaction) {
  let newSignatures;
  let unexpectedSigners;
  await Promise.all(
    keyPairs.map(async (keyPair) => {
      const address2 = await getAddressFromPublicKey(keyPair.publicKey);
      const existingSignature = transaction.signatures[address2];
      if (existingSignature === void 0) {
        unexpectedSigners ||= /* @__PURE__ */ new Set();
        unexpectedSigners.add(address2);
        return;
      }
      if (unexpectedSigners) {
        return;
      }
      const newSignature = await signBytes(keyPair.privateKey, transaction.messageBytes);
      if (existingSignature !== null && bytesEqual(newSignature, existingSignature)) {
        return;
      }
      newSignatures ||= {};
      newSignatures[address2] = newSignature;
    })
  );
  if (unexpectedSigners && unexpectedSigners.size > 0) {
    const expectedSigners = Object.keys(transaction.signatures);
    throw new SolanaError(SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION, {
      expectedAddresses: expectedSigners,
      unexpectedAddresses: [...unexpectedSigners]
    });
  }
  if (!newSignatures) {
    return transaction;
  }
  return Object.freeze({
    ...transaction,
    signatures: Object.freeze({
      ...transaction.signatures,
      ...newSignatures
    })
  });
}
async function signTransaction2(keyPairs, transaction) {
  const out = await partiallySignTransaction(keyPairs, transaction);
  assertIsFullySignedTransaction(out);
  Object.freeze(out);
  return out;
}
function isFullySignedTransaction(transaction) {
  return Object.entries(transaction.signatures).every(([_, signatureBytes2]) => !!signatureBytes2);
}
function assertIsFullySignedTransaction(transaction) {
  const missingSigs = [];
  Object.entries(transaction.signatures).forEach(([address2, signatureBytes2]) => {
    if (!signatureBytes2) {
      missingSigs.push(address2);
    }
  });
  if (missingSigs.length > 0) {
    throw new SolanaError(SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING, {
      addresses: missingSigs
    });
  }
}
function getBase64EncodedWireTransaction(transaction) {
  const wireTransactionBytes = getTransactionEncoder().encode(transaction);
  return getBase64Decoder().decode(wireTransactionBytes);
}
function getTransactionSize(transaction) {
  return getTransactionEncoder().getSizeFromValue(transaction);
}
function isTransactionWithinSizeLimit(transaction) {
  return getTransactionSize(transaction) <= TRANSACTION_SIZE_LIMIT;
}
function assertIsTransactionWithinSizeLimit(transaction) {
  const transactionSize = getTransactionSize(transaction);
  if (transactionSize > TRANSACTION_SIZE_LIMIT) {
    throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, {
      transactionSize,
      transactionSizeLimit: TRANSACTION_SIZE_LIMIT
    });
  }
}
function isSendableTransaction(transaction) {
  return isFullySignedTransaction(transaction) && isTransactionWithinSizeLimit(transaction);
}
function assertIsSendableTransaction(transaction) {
  assertIsFullySignedTransaction(transaction);
  assertIsTransactionWithinSizeLimit(transaction);
}
function getTransactionMessageSize(transactionMessage) {
  return getTransactionSize(compileTransaction(transactionMessage));
}
function isTransactionMessageWithinSizeLimit(transactionMessage) {
  return getTransactionMessageSize(transactionMessage) <= TRANSACTION_SIZE_LIMIT;
}
function assertIsTransactionMessageWithinSizeLimit(transactionMessage) {
  const transactionSize = getTransactionMessageSize(transactionMessage);
  if (transactionSize > TRANSACTION_SIZE_LIMIT) {
    throw new SolanaError(SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT, {
      transactionSize,
      transactionSizeLimit: TRANSACTION_SIZE_LIMIT
    });
  }
}
var SYSTEM_PROGRAM_ADDRESS2, base58Decoder, TRANSACTION_PACKET_SIZE, TRANSACTION_PACKET_HEADER, TRANSACTION_SIZE_LIMIT;
var init_index_node16 = __esm({
  "node_modules/@solana/transactions/dist/index.node.mjs"() {
    "use strict";
    init_index_node6();
    init_index_node2();
    init_index_node8();
    init_index_node7();
    init_index_node();
    init_index_node14();
    init_index_node13();
    init_index_node3();
    init_index_node15();
    SYSTEM_PROGRAM_ADDRESS2 = "11111111111111111111111111111111";
    TRANSACTION_PACKET_SIZE = 1280;
    TRANSACTION_PACKET_HEADER = 40 + 8;
    TRANSACTION_SIZE_LIMIT = TRANSACTION_PACKET_SIZE - TRANSACTION_PACKET_HEADER;
  }
});

// node_modules/@solana/promises/dist/index.node.mjs
function isObject(value) {
  return value !== null && (typeof value === "object" || typeof value === "function");
}
function addRaceContender(contender) {
  const deferreds = /* @__PURE__ */ new Set();
  const record = { deferreds, settled: false };
  Promise.resolve(contender).then(
    (value) => {
      for (const { resolve } of deferreds) {
        resolve(value);
      }
      deferreds.clear();
      record.settled = true;
    },
    (err) => {
      for (const { reject } of deferreds) {
        reject(err);
      }
      deferreds.clear();
      record.settled = true;
    }
  );
  return record;
}
async function safeRace(contenders) {
  let deferred;
  const result = new Promise((resolve, reject) => {
    deferred = { reject, resolve };
    for (const contender of contenders) {
      if (!isObject(contender)) {
        Promise.resolve(contender).then(resolve, reject);
        continue;
      }
      let record = wm.get(contender);
      if (record === void 0) {
        record = addRaceContender(contender);
        record.deferreds.add(deferred);
        wm.set(contender, record);
      } else if (record.settled) {
        Promise.resolve(contender).then(resolve, reject);
      } else {
        record.deferreds.add(deferred);
      }
    }
  });
  return await result.finally(() => {
    for (const contender of contenders) {
      if (isObject(contender)) {
        const record = wm.get(contender);
        record.deferreds.delete(deferred);
      }
    }
  });
}
function getAbortablePromise(promise, abortSignal) {
  if (!abortSignal) {
    return promise;
  } else {
    return safeRace([
      // This promise only ever rejects if the signal is aborted. Otherwise it idles forever.
      // It's important that this come before the input promise; in the event of an abort, we
      // want to throw even if the input promise's result is ready
      new Promise((_, reject) => {
        if (abortSignal.aborted) {
          reject(abortSignal.reason);
        } else {
          abortSignal.addEventListener("abort", function() {
            reject(this.reason);
          });
        }
      }),
      promise
    ]);
  }
}
var wm;
var init_index_node17 = __esm({
  "node_modules/@solana/promises/dist/index.node.mjs"() {
    "use strict";
    wm = /* @__PURE__ */ new WeakMap();
  }
});

// node_modules/@solana/instruction-plans/dist/index.node.mjs
function parallelInstructionPlan(plans) {
  return Object.freeze({
    kind: "parallel",
    plans: parseSingleInstructionPlans(plans)
  });
}
function sequentialInstructionPlan(plans) {
  return Object.freeze({
    divisible: true,
    kind: "sequential",
    plans: parseSingleInstructionPlans(plans)
  });
}
function nonDivisibleSequentialInstructionPlan(plans) {
  return Object.freeze({
    divisible: false,
    kind: "sequential",
    plans: parseSingleInstructionPlans(plans)
  });
}
function singleInstructionPlan(instruction) {
  return Object.freeze({ instruction, kind: "single" });
}
function parseSingleInstructionPlans(plans) {
  return plans.map((plan) => "kind" in plan ? plan : singleInstructionPlan(plan));
}
function isSingleInstructionPlan(plan) {
  return plan.kind === "single";
}
function assertIsSingleInstructionPlan(plan) {
  if (!isSingleInstructionPlan(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {
      actualKind: plan.kind,
      expectedKind: "single",
      instructionPlan: plan
    });
  }
}
function isMessagePackerInstructionPlan(plan) {
  return plan.kind === "messagePacker";
}
function assertIsMessagePackerInstructionPlan(plan) {
  if (!isMessagePackerInstructionPlan(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {
      actualKind: plan.kind,
      expectedKind: "messagePacker",
      instructionPlan: plan
    });
  }
}
function isSequentialInstructionPlan(plan) {
  return plan.kind === "sequential";
}
function assertIsSequentialInstructionPlan(plan) {
  if (!isSequentialInstructionPlan(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {
      actualKind: plan.kind,
      expectedKind: "sequential",
      instructionPlan: plan
    });
  }
}
function isNonDivisibleSequentialInstructionPlan(plan) {
  return plan.kind === "sequential" && plan.divisible === false;
}
function assertIsNonDivisibleSequentialInstructionPlan(plan) {
  if (!isNonDivisibleSequentialInstructionPlan(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {
      actualKind: plan.kind === "sequential" ? "divisible sequential" : plan.kind,
      expectedKind: "non-divisible sequential",
      instructionPlan: plan
    });
  }
}
function isParallelInstructionPlan(plan) {
  return plan.kind === "parallel";
}
function assertIsParallelInstructionPlan(plan) {
  if (!isParallelInstructionPlan(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN, {
      actualKind: plan.kind,
      expectedKind: "parallel",
      instructionPlan: plan
    });
  }
}
function findInstructionPlan(instructionPlan, predicate) {
  if (predicate(instructionPlan)) {
    return instructionPlan;
  }
  if (instructionPlan.kind === "single" || instructionPlan.kind === "messagePacker") {
    return void 0;
  }
  for (const subPlan of instructionPlan.plans) {
    const foundPlan = findInstructionPlan(subPlan, predicate);
    if (foundPlan) {
      return foundPlan;
    }
  }
  return void 0;
}
function everyInstructionPlan(instructionPlan, predicate) {
  if (!predicate(instructionPlan)) {
    return false;
  }
  if (instructionPlan.kind === "single" || instructionPlan.kind === "messagePacker") {
    return true;
  }
  return instructionPlan.plans.every((p) => everyInstructionPlan(p, predicate));
}
function transformInstructionPlan(instructionPlan, fn) {
  if (instructionPlan.kind === "single" || instructionPlan.kind === "messagePacker") {
    return Object.freeze(fn(instructionPlan));
  }
  return Object.freeze(
    fn(
      Object.freeze({
        ...instructionPlan,
        plans: instructionPlan.plans.map((p) => transformInstructionPlan(p, fn))
      })
    )
  );
}
function flattenInstructionPlan(instructionPlan) {
  if (instructionPlan.kind === "single" || instructionPlan.kind === "messagePacker") {
    return [instructionPlan];
  }
  return instructionPlan.plans.flatMap(flattenInstructionPlan);
}
function getLinearMessagePackerInstructionPlan({
  getInstruction,
  totalLength: totalBytes
}) {
  return Object.freeze({
    getMessagePacker: () => {
      let offset = 0;
      return Object.freeze({
        done: () => offset >= totalBytes,
        packMessageToCapacity: (message) => {
          if (offset >= totalBytes) {
            throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE);
          }
          const messageSizeWithBaseInstruction = getTransactionMessageSize(
            appendTransactionMessageInstruction(getInstruction(offset, 0), message)
          );
          const freeSpace = TRANSACTION_SIZE_LIMIT - messageSizeWithBaseInstruction - 1;
          if (freeSpace <= 0) {
            const messageSize = getTransactionMessageSize(message);
            throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN, {
              // (+1) We need to pack at least one byte of data otherwise
              // there is no point packing the base instruction alone.
              numBytesRequired: messageSizeWithBaseInstruction - messageSize + 1,
              // (-1) Leeway for shortU16 numbers in transaction headers.
              numFreeBytes: TRANSACTION_SIZE_LIMIT - messageSize - 1
            });
          }
          const length = Math.min(totalBytes - offset, freeSpace);
          const instruction = getInstruction(offset, length);
          offset += length;
          return appendTransactionMessageInstruction(instruction, message);
        }
      });
    },
    kind: "messagePacker"
  });
}
function getMessagePackerInstructionPlanFromInstructions(instructions) {
  return Object.freeze({
    getMessagePacker: () => {
      let instructionIndex = 0;
      return Object.freeze({
        done: () => instructionIndex >= instructions.length,
        packMessageToCapacity: (message) => {
          if (instructionIndex >= instructions.length) {
            throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE);
          }
          const originalMessageSize = getTransactionMessageSize(message);
          for (let index2 = instructionIndex; index2 < instructions.length; index2++) {
            message = appendTransactionMessageInstruction(instructions[index2], message);
            const messageSize = getTransactionMessageSize(message);
            if (messageSize > TRANSACTION_SIZE_LIMIT) {
              if (index2 === instructionIndex) {
                throw new SolanaError(
                  SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,
                  {
                    numBytesRequired: messageSize - originalMessageSize,
                    numFreeBytes: TRANSACTION_SIZE_LIMIT - originalMessageSize
                  }
                );
              }
              instructionIndex = index2;
              return message;
            }
          }
          instructionIndex = instructions.length;
          return message;
        }
      });
    },
    kind: "messagePacker"
  });
}
function getReallocMessagePackerInstructionPlan({
  getInstruction,
  totalSize
}) {
  const numberOfInstructions = Math.ceil(totalSize / REALLOC_LIMIT);
  const lastInstructionSize = totalSize % REALLOC_LIMIT;
  const instructions = new Array(numberOfInstructions).fill(0).map((_, i) => getInstruction(i === numberOfInstructions - 1 ? lastInstructionSize : REALLOC_LIMIT));
  return getMessagePackerInstructionPlanFromInstructions(instructions);
}
function appendTransactionMessageInstructionPlan(instructionPlan, transactionMessage) {
  const leafInstructionPlans = flattenInstructionPlan(instructionPlan);
  return leafInstructionPlans.reduce(
    (messageSoFar, plan) => {
      const kind = plan.kind;
      if (kind === "single") {
        return appendTransactionMessageInstruction(plan.instruction, messageSoFar);
      }
      if (kind === "messagePacker") {
        const messagerPacker = plan.getMessagePacker();
        let nextMessage = messageSoFar;
        while (!messagerPacker.done()) {
          nextMessage = messagerPacker.packMessageToCapacity(nextMessage);
        }
        return nextMessage;
      }
      throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, {
        kind
      });
    },
    transactionMessage
  );
}
function parallelTransactionPlan(plans) {
  return Object.freeze({ kind: "parallel", plans: parseSingleTransactionPlans(plans) });
}
function sequentialTransactionPlan(plans) {
  return Object.freeze({ divisible: true, kind: "sequential", plans: parseSingleTransactionPlans(plans) });
}
function nonDivisibleSequentialTransactionPlan(plans) {
  return Object.freeze({ divisible: false, kind: "sequential", plans: parseSingleTransactionPlans(plans) });
}
function singleTransactionPlan(transactionMessage) {
  return Object.freeze({ kind: "single", message: transactionMessage });
}
function parseSingleTransactionPlans(plans) {
  return plans.map((plan) => "kind" in plan ? plan : singleTransactionPlan(plan));
}
function isSingleTransactionPlan(plan) {
  return plan.kind === "single";
}
function assertIsSingleTransactionPlan(plan) {
  if (!isSingleTransactionPlan(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {
      actualKind: plan.kind,
      expectedKind: "single",
      transactionPlan: plan
    });
  }
}
function isSequentialTransactionPlan(plan) {
  return plan.kind === "sequential";
}
function assertIsSequentialTransactionPlan(plan) {
  if (!isSequentialTransactionPlan(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {
      actualKind: plan.kind,
      expectedKind: "sequential",
      transactionPlan: plan
    });
  }
}
function isNonDivisibleSequentialTransactionPlan(plan) {
  return plan.kind === "sequential" && plan.divisible === false;
}
function assertIsNonDivisibleSequentialTransactionPlan(plan) {
  if (!isNonDivisibleSequentialTransactionPlan(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {
      actualKind: plan.kind === "sequential" ? "divisible sequential" : plan.kind,
      expectedKind: "non-divisible sequential",
      transactionPlan: plan
    });
  }
}
function isParallelTransactionPlan(plan) {
  return plan.kind === "parallel";
}
function assertIsParallelTransactionPlan(plan) {
  if (!isParallelTransactionPlan(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN, {
      actualKind: plan.kind,
      expectedKind: "parallel",
      transactionPlan: plan
    });
  }
}
function flattenTransactionPlan(transactionPlan) {
  if (transactionPlan.kind === "single") {
    return [transactionPlan];
  }
  return transactionPlan.plans.flatMap(flattenTransactionPlan);
}
function findTransactionPlan(transactionPlan, predicate) {
  if (predicate(transactionPlan)) {
    return transactionPlan;
  }
  if (transactionPlan.kind === "single") {
    return void 0;
  }
  for (const subPlan of transactionPlan.plans) {
    const foundPlan = findTransactionPlan(subPlan, predicate);
    if (foundPlan) {
      return foundPlan;
    }
  }
  return void 0;
}
function everyTransactionPlan(transactionPlan, predicate) {
  if (!predicate(transactionPlan)) {
    return false;
  }
  if (transactionPlan.kind === "single") {
    return true;
  }
  return transactionPlan.plans.every((p) => everyTransactionPlan(p, predicate));
}
function transformTransactionPlan(transactionPlan, fn) {
  if (transactionPlan.kind === "single") {
    return Object.freeze(fn(transactionPlan));
  }
  return Object.freeze(
    fn(
      Object.freeze({
        ...transactionPlan,
        plans: transactionPlan.plans.map((p) => transformTransactionPlan(p, fn))
      })
    )
  );
}
function sequentialTransactionPlanResult(plans) {
  return Object.freeze({ divisible: true, kind: "sequential", plans });
}
function nonDivisibleSequentialTransactionPlanResult(plans) {
  return Object.freeze({ divisible: false, kind: "sequential", plans });
}
function parallelTransactionPlanResult(plans) {
  return Object.freeze({ kind: "parallel", plans });
}
function successfulSingleTransactionPlanResult(transactionMessage, transaction, context) {
  return Object.freeze({
    kind: "single",
    message: transactionMessage,
    status: Object.freeze({
      context: context ?? {},
      kind: "successful",
      signature: getSignatureFromTransaction(transaction),
      transaction
    })
  });
}
function successfulSingleTransactionPlanResultFromSignature(transactionMessage, signature2, context) {
  return Object.freeze({
    kind: "single",
    message: transactionMessage,
    status: Object.freeze({ context: context ?? {}, kind: "successful", signature: signature2 })
  });
}
function failedSingleTransactionPlanResult(transactionMessage, error) {
  return Object.freeze({
    kind: "single",
    message: transactionMessage,
    status: Object.freeze({ error, kind: "failed" })
  });
}
function canceledSingleTransactionPlanResult(transactionMessage) {
  return Object.freeze({
    kind: "single",
    message: transactionMessage,
    status: Object.freeze({ kind: "canceled" })
  });
}
function isSingleTransactionPlanResult(plan) {
  return plan.kind === "single";
}
function assertIsSingleTransactionPlanResult(plan) {
  if (!isSingleTransactionPlanResult(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {
      actualKind: plan.kind,
      expectedKind: "single",
      transactionPlanResult: plan
    });
  }
}
function isSuccessfulSingleTransactionPlanResult(plan) {
  return plan.kind === "single" && plan.status.kind === "successful";
}
function assertIsSuccessfulSingleTransactionPlanResult(plan) {
  if (!isSuccessfulSingleTransactionPlanResult(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {
      actualKind: plan.kind === "single" ? `${plan.status.kind} single` : plan.kind,
      expectedKind: "successful single",
      transactionPlanResult: plan
    });
  }
}
function isFailedSingleTransactionPlanResult(plan) {
  return plan.kind === "single" && plan.status.kind === "failed";
}
function assertIsFailedSingleTransactionPlanResult(plan) {
  if (!isFailedSingleTransactionPlanResult(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {
      actualKind: plan.kind === "single" ? `${plan.status.kind} single` : plan.kind,
      expectedKind: "failed single",
      transactionPlanResult: plan
    });
  }
}
function isCanceledSingleTransactionPlanResult(plan) {
  return plan.kind === "single" && plan.status.kind === "canceled";
}
function assertIsCanceledSingleTransactionPlanResult(plan) {
  if (!isCanceledSingleTransactionPlanResult(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {
      actualKind: plan.kind === "single" ? `${plan.status.kind} single` : plan.kind,
      expectedKind: "canceled single",
      transactionPlanResult: plan
    });
  }
}
function isSequentialTransactionPlanResult(plan) {
  return plan.kind === "sequential";
}
function assertIsSequentialTransactionPlanResult(plan) {
  if (!isSequentialTransactionPlanResult(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {
      actualKind: plan.kind,
      expectedKind: "sequential",
      transactionPlanResult: plan
    });
  }
}
function isNonDivisibleSequentialTransactionPlanResult(plan) {
  return plan.kind === "sequential" && plan.divisible === false;
}
function assertIsNonDivisibleSequentialTransactionPlanResult(plan) {
  if (!isNonDivisibleSequentialTransactionPlanResult(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {
      actualKind: plan.kind === "sequential" ? "divisible sequential" : plan.kind,
      expectedKind: "non-divisible sequential",
      transactionPlanResult: plan
    });
  }
}
function isParallelTransactionPlanResult(plan) {
  return plan.kind === "parallel";
}
function assertIsParallelTransactionPlanResult(plan) {
  if (!isParallelTransactionPlanResult(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT, {
      actualKind: plan.kind,
      expectedKind: "parallel",
      transactionPlanResult: plan
    });
  }
}
function isSuccessfulTransactionPlanResult(plan) {
  return everyTransactionPlanResult(
    plan,
    (r) => !isSingleTransactionPlanResult(r) || isSuccessfulSingleTransactionPlanResult(r)
  );
}
function assertIsSuccessfulTransactionPlanResult(plan) {
  if (!isSuccessfulTransactionPlanResult(plan)) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT, {
      transactionPlanResult: plan
    });
  }
}
function findTransactionPlanResult(transactionPlanResult, predicate) {
  if (predicate(transactionPlanResult)) {
    return transactionPlanResult;
  }
  if (transactionPlanResult.kind === "single") {
    return void 0;
  }
  for (const subResult of transactionPlanResult.plans) {
    const foundResult = findTransactionPlanResult(subResult, predicate);
    if (foundResult) {
      return foundResult;
    }
  }
  return void 0;
}
function getFirstFailedSingleTransactionPlanResult(transactionPlanResult) {
  const result = findTransactionPlanResult(
    transactionPlanResult,
    (r) => r.kind === "single" && r.status.kind === "failed"
  );
  if (!result) {
    const context = {};
    Object.defineProperty(context, "transactionPlanResult", {
      configurable: false,
      enumerable: false,
      value: transactionPlanResult,
      writable: false
    });
    throw new SolanaError(
      SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,
      context
    );
  }
  return result;
}
function everyTransactionPlanResult(transactionPlanResult, predicate) {
  if (!predicate(transactionPlanResult)) {
    return false;
  }
  if (transactionPlanResult.kind === "single") {
    return true;
  }
  return transactionPlanResult.plans.every((p) => everyTransactionPlanResult(p, predicate));
}
function transformTransactionPlanResult(transactionPlanResult, fn) {
  if (transactionPlanResult.kind === "single") {
    return Object.freeze(fn(transactionPlanResult));
  }
  return Object.freeze(
    fn(
      Object.freeze({
        ...transactionPlanResult,
        plans: transactionPlanResult.plans.map((p) => transformTransactionPlanResult(p, fn))
      })
    )
  );
}
function flattenTransactionPlanResult(result) {
  if (result.kind === "single") {
    return [result];
  }
  return result.plans.flatMap(flattenTransactionPlanResult);
}
function summarizeTransactionPlanResult(result) {
  const successfulTransactions = [];
  const failedTransactions = [];
  const canceledTransactions = [];
  const flattenedResults = flattenTransactionPlanResult(result);
  for (const singleResult of flattenedResults) {
    switch (singleResult.status.kind) {
      case "successful": {
        successfulTransactions.push(singleResult);
        break;
      }
      case "failed": {
        failedTransactions.push(singleResult);
        break;
      }
      case "canceled": {
        canceledTransactions.push(singleResult);
        break;
      }
    }
  }
  return Object.freeze({
    canceledTransactions,
    failedTransactions,
    successful: failedTransactions.length === 0 && canceledTransactions.length === 0,
    successfulTransactions
  });
}
function createTransactionPlanExecutor(config) {
  return async (plan, { abortSignal } = {}) => {
    const context = {
      ...config,
      abortSignal,
      canceled: abortSignal?.aborted ?? false
    };
    assertDivisibleSequentialPlansOnly(plan);
    const cancelHandler = () => {
      context.canceled = true;
    };
    abortSignal?.addEventListener("abort", cancelHandler);
    const transactionPlanResult = await traverse(plan, context);
    abortSignal?.removeEventListener("abort", cancelHandler);
    if (context.canceled) {
      const abortReason = abortSignal?.aborted ? abortSignal.reason : void 0;
      const context2 = { cause: findErrorFromTransactionPlanResult(transactionPlanResult) ?? abortReason };
      Object.defineProperty(context2, "transactionPlanResult", {
        configurable: false,
        enumerable: false,
        value: transactionPlanResult,
        writable: false
      });
      throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN, context2);
    }
    return transactionPlanResult;
  };
}
async function traverse(transactionPlan, context) {
  const kind = transactionPlan.kind;
  switch (kind) {
    case "sequential":
      return await traverseSequential(transactionPlan, context);
    case "parallel":
      return await traverseParallel(transactionPlan, context);
    case "single":
      return await traverseSingle(transactionPlan, context);
    default:
      throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND, { kind });
  }
}
async function traverseSequential(transactionPlan, context) {
  if (!transactionPlan.divisible) {
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED);
  }
  const results = [];
  for (const subPlan of transactionPlan.plans) {
    const result = await traverse(subPlan, context);
    results.push(result);
  }
  return sequentialTransactionPlanResult(results);
}
async function traverseParallel(transactionPlan, context) {
  const results = await Promise.all(transactionPlan.plans.map((plan) => traverse(plan, context)));
  return parallelTransactionPlanResult(results);
}
async function traverseSingle(transactionPlan, context) {
  if (context.canceled) {
    return canceledSingleTransactionPlanResult(transactionPlan.message);
  }
  try {
    const result = await getAbortablePromise(
      context.executeTransactionMessage(transactionPlan.message, { abortSignal: context.abortSignal }),
      context.abortSignal
    );
    if ("transaction" in result) {
      return successfulSingleTransactionPlanResult(transactionPlan.message, result.transaction, result.context);
    } else {
      return successfulSingleTransactionPlanResultFromSignature(
        transactionPlan.message,
        result.signature,
        result.context
      );
    }
  } catch (error) {
    context.canceled = true;
    return failedSingleTransactionPlanResult(transactionPlan.message, error);
  }
}
function findErrorFromTransactionPlanResult(result) {
  if (result.kind === "single") {
    return result.status.kind === "failed" ? result.status.error : void 0;
  }
  for (const plan of result.plans) {
    const error = findErrorFromTransactionPlanResult(plan);
    if (error) {
      return error;
    }
  }
}
function assertDivisibleSequentialPlansOnly(transactionPlan) {
  const kind = transactionPlan.kind;
  switch (kind) {
    case "sequential":
      if (!transactionPlan.divisible) {
        throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED);
      }
      for (const subPlan of transactionPlan.plans) {
        assertDivisibleSequentialPlansOnly(subPlan);
      }
      return;
    case "parallel":
      for (const subPlan of transactionPlan.plans) {
        assertDivisibleSequentialPlansOnly(subPlan);
      }
      return;
    case "single":
    default:
      return;
  }
}
async function passthroughFailedTransactionPlanExecution(promise) {
  try {
    return await promise;
  } catch (error) {
    if (isSolanaError(error, SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN)) {
      return error.context.transactionPlanResult;
    }
    throw error;
  }
}
function createTransactionPlanner(config) {
  return async (instructionPlan, { abortSignal } = {}) => {
    const plan = await traverse2(instructionPlan, {
      abortSignal,
      createTransactionMessage: config.createTransactionMessage,
      onTransactionMessageUpdated: config.onTransactionMessageUpdated ?? ((msg) => msg),
      parent: null,
      parentCandidates: []
    });
    if (!plan) {
      throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN);
    }
    return freezeTransactionPlan(plan);
  };
}
async function traverse2(instructionPlan, context) {
  context.abortSignal?.throwIfAborted();
  const kind = instructionPlan.kind;
  switch (kind) {
    case "sequential":
      return await traverseSequential2(instructionPlan, context);
    case "parallel":
      return await traverseParallel2(instructionPlan, context);
    case "single":
      return await traverseSingle2(instructionPlan, context);
    case "messagePacker":
      return await traverseMessagePacker(instructionPlan, context);
    default:
      throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, { kind });
  }
}
async function traverseSequential2(instructionPlan, context) {
  let candidate = null;
  const mustEntirelyFitInParentCandidate = context.parent && (context.parent.kind === "parallel" || !instructionPlan.divisible);
  if (mustEntirelyFitInParentCandidate) {
    const candidate2 = await selectAndMutateCandidate(
      context,
      context.parentCandidates,
      (message) => fitEntirePlanInsideMessage(instructionPlan, message)
    );
    if (candidate2) {
      return null;
    }
  } else {
    candidate = context.parentCandidates.length > 0 ? context.parentCandidates[0] : null;
  }
  const transactionPlans = [];
  for (const plan of instructionPlan.plans) {
    const transactionPlan = await traverse2(plan, {
      ...context,
      parent: instructionPlan,
      parentCandidates: candidate ? [candidate] : []
    });
    if (transactionPlan) {
      candidate = getSequentialCandidate(transactionPlan);
      const newPlans = transactionPlan.kind === "sequential" && (transactionPlan.divisible || !instructionPlan.divisible) ? transactionPlan.plans : [transactionPlan];
      transactionPlans.push(...newPlans);
    }
  }
  if (transactionPlans.length === 1) {
    return transactionPlans[0];
  }
  if (transactionPlans.length === 0) {
    return null;
  }
  return {
    divisible: instructionPlan.divisible,
    kind: "sequential",
    plans: transactionPlans
  };
}
async function traverseParallel2(instructionPlan, context) {
  const candidates = [...context.parentCandidates];
  const transactionPlans = [];
  const sortedChildren = Array.from(instructionPlan.plans).sort(
    (a, b) => Number(a.kind === "messagePacker") - Number(b.kind === "messagePacker")
  );
  for (const plan of sortedChildren) {
    const transactionPlan = await traverse2(plan, {
      ...context,
      parent: instructionPlan,
      parentCandidates: candidates
    });
    if (transactionPlan) {
      candidates.push(...getParallelCandidates(transactionPlan));
      const newPlans = transactionPlan.kind === "parallel" ? transactionPlan.plans : [transactionPlan];
      transactionPlans.push(...newPlans);
    }
  }
  if (transactionPlans.length === 1) {
    return transactionPlans[0];
  }
  if (transactionPlans.length === 0) {
    return null;
  }
  return { kind: "parallel", plans: transactionPlans };
}
async function traverseSingle2(instructionPlan, context) {
  const predicate = (message2) => appendTransactionMessageInstructions([instructionPlan.instruction], message2);
  const candidate = await selectAndMutateCandidate(context, context.parentCandidates, predicate);
  if (candidate) {
    return null;
  }
  const message = await createNewMessage(context, predicate);
  return { kind: "single", message };
}
async function traverseMessagePacker(instructionPlan, context) {
  const messagePacker = instructionPlan.getMessagePacker();
  const transactionPlans = [];
  const candidates = [...context.parentCandidates];
  while (!messagePacker.done()) {
    const candidate = await selectAndMutateCandidate(context, candidates, messagePacker.packMessageToCapacity);
    if (!candidate) {
      const message = await createNewMessage(context, messagePacker.packMessageToCapacity);
      const newPlan = { kind: "single", message };
      transactionPlans.push(newPlan);
    }
  }
  if (transactionPlans.length === 1) {
    return transactionPlans[0];
  }
  if (transactionPlans.length === 0) {
    return null;
  }
  if (context.parent?.kind === "parallel") {
    return { kind: "parallel", plans: transactionPlans };
  }
  return {
    divisible: context.parent?.kind === "sequential" ? context.parent.divisible : true,
    kind: "sequential",
    plans: transactionPlans
  };
}
function getSequentialCandidate(latestPlan) {
  if (latestPlan.kind === "single") {
    return latestPlan;
  }
  if (latestPlan.kind === "sequential" && latestPlan.plans.length > 0) {
    return getSequentialCandidate(latestPlan.plans[latestPlan.plans.length - 1]);
  }
  return null;
}
function getParallelCandidates(latestPlan) {
  return flattenTransactionPlan(latestPlan);
}
async function selectAndMutateCandidate(context, candidates, predicate) {
  for (const candidate of candidates) {
    try {
      const message = await getAbortablePromise(
        Promise.resolve(
          context.onTransactionMessageUpdated(predicate(candidate.message), {
            abortSignal: context.abortSignal
          })
        ),
        context.abortSignal
      );
      if (getTransactionMessageSize(message) <= TRANSACTION_SIZE_LIMIT) {
        candidate.message = message;
        return candidate;
      }
    } catch (error) {
      if (isSolanaError(error, SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN)) ;
      else {
        throw error;
      }
    }
  }
  return null;
}
async function createNewMessage(context, predicate) {
  const newMessage = await getAbortablePromise(
    Promise.resolve(context.createTransactionMessage({ abortSignal: context.abortSignal })),
    context.abortSignal
  );
  const updatedMessage = await getAbortablePromise(
    Promise.resolve(
      context.onTransactionMessageUpdated(predicate(newMessage), { abortSignal: context.abortSignal })
    ),
    context.abortSignal
  );
  const updatedMessageSize = getTransactionMessageSize(updatedMessage);
  if (updatedMessageSize > TRANSACTION_SIZE_LIMIT) {
    const newMessageSize = getTransactionMessageSize(newMessage);
    throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN, {
      numBytesRequired: updatedMessageSize - newMessageSize,
      numFreeBytes: TRANSACTION_SIZE_LIMIT - newMessageSize
    });
  }
  return updatedMessage;
}
function freezeTransactionPlan(plan) {
  const kind = plan.kind;
  switch (kind) {
    case "single":
      return singleTransactionPlan(plan.message);
    case "sequential":
      return plan.divisible ? sequentialTransactionPlan(plan.plans.map(freezeTransactionPlan)) : nonDivisibleSequentialTransactionPlan(plan.plans.map(freezeTransactionPlan));
    case "parallel":
      return parallelTransactionPlan(plan.plans.map(freezeTransactionPlan));
    default:
      throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND, { kind });
  }
}
function fitEntirePlanInsideMessage(instructionPlan, message) {
  let newMessage = message;
  const kind = instructionPlan.kind;
  switch (kind) {
    case "sequential":
    case "parallel":
      for (const plan of instructionPlan.plans) {
        newMessage = fitEntirePlanInsideMessage(plan, newMessage);
      }
      return newMessage;
    case "single":
      newMessage = appendTransactionMessageInstructions([instructionPlan.instruction], message);
      const newMessageSize = getTransactionMessageSize(newMessage);
      if (newMessageSize > TRANSACTION_SIZE_LIMIT) {
        const baseMessageSize = getTransactionMessageSize(message);
        throw new SolanaError(SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN, {
          numBytesRequired: newMessageSize - baseMessageSize,
          numFreeBytes: TRANSACTION_SIZE_LIMIT - baseMessageSize
        });
      }
      return newMessage;
    case "messagePacker":
      const messagePacker = instructionPlan.getMessagePacker();
      while (!messagePacker.done()) {
        newMessage = messagePacker.packMessageToCapacity(newMessage);
      }
      return newMessage;
    default:
      throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND, { kind });
  }
}
var REALLOC_LIMIT, getAllSingleTransactionPlans;
var init_index_node18 = __esm({
  "node_modules/@solana/instruction-plans/dist/index.node.mjs"() {
    "use strict";
    init_index_node();
    init_index_node14();
    init_index_node16();
    init_index_node17();
    REALLOC_LIMIT = 10240;
    getAllSingleTransactionPlans = flattenTransactionPlan;
  }
});

// node_modules/@solana/offchain-messages/dist/index.node.mjs
function isOffchainMessageApplicationDomain(putativeApplicationDomain) {
  return isAddress2(putativeApplicationDomain);
}
function assertIsOffchainMessageApplicationDomain(putativeApplicationDomain) {
  try {
    assertIsAddress(putativeApplicationDomain);
  } catch (error) {
    if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE)) {
      throw new SolanaError(
        SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,
        error.context
      );
    }
    if (isSolanaError(error, SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH)) {
      throw new SolanaError(
        SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,
        error.context
      );
    }
    throw error;
  }
}
function offchainMessageApplicationDomain(putativeApplicationDomain) {
  assertIsOffchainMessageApplicationDomain(putativeApplicationDomain);
  return putativeApplicationDomain;
}
function getOffchainMessageApplicationDomainEncoder() {
  return transformEncoder(
    getAddressEncoder(),
    (putativeApplicationDomain) => offchainMessageApplicationDomain(putativeApplicationDomain)
  );
}
function getOffchainMessageApplicationDomainDecoder() {
  return getAddressDecoder();
}
function getOffchainMessageApplicationDomainCodec() {
  return combineCodec(getOffchainMessageApplicationDomainEncoder(), getOffchainMessageApplicationDomainDecoder());
}
function getOffchainMessageSigningDomainDecoder() {
  return getConstantDecoder(OFFCHAIN_MESSAGE_SIGNING_DOMAIN_BYTES);
}
function getOffchainMessageSigningDomainEncoder() {
  return getConstantEncoder(OFFCHAIN_MESSAGE_SIGNING_DOMAIN_BYTES);
}
function getSigningDomainPrefixedDecoder(...fields) {
  return getHiddenPrefixDecoder(getStructDecoder(fields), [getOffchainMessageSigningDomainDecoder()]);
}
function getSigningDomainPrefixedEncoder(...fields) {
  return getHiddenPrefixEncoder(getStructEncoder(fields), [getOffchainMessageSigningDomainEncoder()]);
}
function getVersionTransformer(fixedVersion) {
  return (version4) => {
    if (version4 > 1) {
      throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {
        unsupportedVersion: version4
      });
    }
    if (fixedVersion != null && version4 !== fixedVersion) {
      throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION, {
        actualVersion: version4,
        expectedVersion: fixedVersion
      });
    }
    return version4;
  };
}
function createOffchainMessagePreambleDecoder(version4, ...fields) {
  return getSigningDomainPrefixedDecoder(
    ["version", transformDecoder(getU8Decoder(), getVersionTransformer(version4))],
    ...fields
  );
}
function createOffchainMessagePreambleEncoder(version4, ...fields) {
  return getSigningDomainPrefixedEncoder(
    ["version", transformEncoder(getU8Encoder(), getVersionTransformer(version4))],
    ...fields
  );
}
function decodeRequiredSignatoryAddresses(bytes) {
  const { version: version4, bytesAfterVersion } = getSigningDomainPrefixedDecoder(
    ["version", transformDecoder(getU8Decoder(), getVersionTransformer())],
    ["bytesAfterVersion", getBytesDecoder()]
  ).decode(bytes);
  return offsetDecoder(
    transformDecoder(getArrayDecoder(getAddressDecoder(), { size: getU8Decoder() }), (signatoryAddresses) => {
      if (signatoryAddresses.length === 0) {
        throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);
      }
      return signatoryAddresses;
    }),
    {
      preOffset: ({ preOffset }) => preOffset + (version4 === 0 ? 32 + 1 : 0)
    }
  ).decode(bytesAfterVersion);
}
function getSignatoriesComparator() {
  return (x, y) => {
    if (x.length !== y.length) {
      return x.length < y.length ? -1 : 1;
    }
    for (let ii = 0; ii < x.length; ii++) {
      if (x[ii] === y[ii]) {
        continue;
      } else {
        return x[ii] < y[ii] ? -1 : 1;
      }
    }
    return 0;
  };
}
function getSignaturesToEncode2(signaturesMap) {
  const signatures = Object.values(signaturesMap);
  if (signatures.length === 0) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO);
  }
  return signatures.map((signature2) => {
    if (!signature2) {
      return new Uint8Array(64).fill(0);
    }
    return signature2;
  });
}
function getSignaturesEncoder2() {
  return transformEncoder(
    getArrayEncoder(fixEncoderSize(getBytesEncoder(), 64), { size: getU8Encoder() }),
    getSignaturesToEncode2
  );
}
function getOffchainMessageEnvelopeEncoder() {
  return transformEncoder(
    getStructEncoder([
      ["signatures", getSignaturesEncoder2()],
      ["content", getBytesEncoder()]
    ]),
    (envelope) => {
      const signaturesMapAddresses = Object.keys(envelope.signatures).map(address);
      if (signaturesMapAddresses.length === 0) {
        throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO);
      }
      const signatoryAddresses = decodeAndValidateRequiredSignatoryAddresses(envelope.content);
      const missingRequiredSigners = [];
      const unexpectedSigners = [];
      for (const address2 of signatoryAddresses) {
        if (!signaturesMapAddresses.includes(address2)) {
          missingRequiredSigners.push(address2);
        }
      }
      for (const address2 of signaturesMapAddresses) {
        if (!signatoryAddresses.includes(address2)) {
          unexpectedSigners.push(address2);
        }
      }
      if (missingRequiredSigners.length || unexpectedSigners.length) {
        throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH, {
          missingRequiredSigners,
          unexpectedSigners
        });
      }
      const orderedSignatureMap = {};
      for (const address2 of signatoryAddresses) {
        orderedSignatureMap[address2] = envelope.signatures[address2];
      }
      return {
        ...envelope,
        signatures: orderedSignatureMap
      };
    }
  );
}
function getOffchainMessageEnvelopeDecoder() {
  return transformDecoder(
    getStructDecoder([
      ["signatures", getArrayDecoder(fixDecoderSize(getBytesDecoder(), 64), { size: getU8Decoder() })],
      ["content", getBytesDecoder()]
    ]),
    decodePartiallyDecodedOffchainMessageEnvelope
  );
}
function getOffchainMessageEnvelopeCodec() {
  return combineCodec(getOffchainMessageEnvelopeEncoder(), getOffchainMessageEnvelopeDecoder());
}
function decodePartiallyDecodedOffchainMessageEnvelope(offchainMessageEnvelope) {
  const { content, signatures } = offchainMessageEnvelope;
  if (signatures.length === 0) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO);
  }
  const signatoryAddresses = decodeAndValidateRequiredSignatoryAddresses(content);
  if (signatoryAddresses.length !== signatures.length) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH, {
      numRequiredSignatures: signatoryAddresses.length,
      signatoryAddresses,
      signaturesLength: signatures.length
    });
  }
  const signaturesMap = {};
  signatoryAddresses.forEach((address2, index2) => {
    const signatureForAddress = signatures[index2];
    if (signatureForAddress.every((b) => b === 0)) {
      signaturesMap[address2] = null;
    } else {
      signaturesMap[address2] = signatureForAddress;
    }
  });
  return Object.freeze({
    content,
    signatures: Object.freeze(signaturesMap)
  });
}
function decodeAndValidateRequiredSignatoryAddresses(bytes) {
  const signatoryAddresses = decodeRequiredSignatoryAddresses(bytes);
  if (signatoryAddresses.length === 0) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);
  }
  return signatoryAddresses;
}
function assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeContent) {
  if (putativeContent.format !== 0) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH, {
      actualMessageFormat: putativeContent.format,
      expectedMessageFormat: 0
      /* RESTRICTED_ASCII_1232_BYTES_MAX */
    });
  }
  if (putativeContent.text.length === 0) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);
  }
  if (isTextRestrictedAscii(putativeContent.text) === false) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE);
  }
  const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);
  if (length > MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED, {
      actualBytes: length,
      maxBytes: MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE
    });
  }
}
function isOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeContent) {
  if (putativeContent.format !== 0 || putativeContent.text.length === 0 || isTextRestrictedAscii(putativeContent.text) === false) {
    return false;
  }
  const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);
  return length <= MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE;
}
function offchainMessageContentRestrictedAsciiOf1232BytesMax(text) {
  const putativeContent = Object.freeze({
    format: 0,
    text
  });
  assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeContent);
  return putativeContent;
}
function assertIsOffchainMessageContentUtf8Of1232BytesMax(putativeContent) {
  if (putativeContent.text.length === 0) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);
  }
  if (putativeContent.format !== 1) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH, {
      actualMessageFormat: putativeContent.format,
      expectedMessageFormat: 1
      /* UTF8_1232_BYTES_MAX */
    });
  }
  const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);
  if (length > MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED, {
      actualBytes: length,
      maxBytes: MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE
    });
  }
}
function isOffchainMessageContentUtf8Of1232BytesMax(putativeContent) {
  if (putativeContent.format !== 1 || putativeContent.text.length === 0) {
    return false;
  }
  const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);
  return length <= MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE;
}
function offchainMessageContentUtf8Of1232BytesMax(text) {
  const putativeContent = Object.freeze({
    format: 1,
    text
  });
  assertIsOffchainMessageContentUtf8Of1232BytesMax(putativeContent);
  return putativeContent;
}
function assertIsOffchainMessageContentUtf8Of65535BytesMax(putativeContent) {
  if (putativeContent.format !== 2) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH, {
      actualMessageFormat: putativeContent.format,
      expectedMessageFormat: 2
      /* UTF8_65535_BYTES_MAX */
    });
  }
  if (putativeContent.text.length === 0) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);
  }
  const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);
  if (length > MAX_BODY_BYTES) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED, {
      actualBytes: length,
      maxBytes: MAX_BODY_BYTES
    });
  }
}
function isOffchainMessageContentUtf8Of65535BytesMax(putativeContent) {
  if (putativeContent.format !== 2 || putativeContent.text.length === 0) {
    return false;
  }
  const length = getUtf8Encoder().getSizeFromValue(putativeContent.text);
  return length <= MAX_BODY_BYTES;
}
function offchainMessageContentUtf8Of65535BytesMax(text) {
  const putativeContent = Object.freeze({
    format: 2,
    text
  });
  assertIsOffchainMessageContentUtf8Of65535BytesMax(putativeContent);
  return putativeContent;
}
function isTextRestrictedAscii(putativeRestrictedAsciiString) {
  return /^[\x20-\x7e]+$/.test(putativeRestrictedAsciiString);
}
function assertIsOffchainMessageRestrictedAsciiOf1232BytesMax(putativeMessage) {
  assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax(putativeMessage.content);
}
function assertIsOffchainMessageUtf8Of1232BytesMax(putativeMessage) {
  assertIsOffchainMessageContentUtf8Of1232BytesMax(putativeMessage.content);
}
function assertIsOffchainMessageUtf8Of65535BytesMax(putativeMessage) {
  assertIsOffchainMessageContentUtf8Of65535BytesMax(putativeMessage.content);
}
function getOffchainMessageContentFormatDecoder() {
  return getEnumDecoder(OffchainMessageContentFormat, {
    useValuesAsDiscriminators: true
  });
}
function getOffchainMessageContentFormatEncoder() {
  return getEnumEncoder(OffchainMessageContentFormat, {
    useValuesAsDiscriminators: true
  });
}
function getOffchainMessageV0PreambleDecoder() {
  return createOffchainMessagePreambleDecoder(
    /* version */
    0,
    ["applicationDomain", getOffchainMessageApplicationDomainDecoder()],
    ["messageFormat", getOffchainMessageContentFormatDecoder()],
    [
      "requiredSignatories",
      transformDecoder(getArrayDecoder(getAddressDecoder(), { size: getU8Decoder() }), (signatoryAddresses) => {
        if (signatoryAddresses.length === 0) {
          throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);
        }
        return signatoryAddresses.map((address2) => Object.freeze({ address: address2 }));
      })
    ],
    ["messageLength", getU16Decoder()]
  );
}
function getOffchainMessageV0PreambleEncoder() {
  return createOffchainMessagePreambleEncoder(
    /* version */
    0,
    ["applicationDomain", getOffchainMessageApplicationDomainEncoder()],
    ["messageFormat", getOffchainMessageContentFormatEncoder()],
    [
      "requiredSignatories",
      transformEncoder(
        getArrayEncoder(getAddressEncoder(), { size: getU8Encoder() }),
        (signatoryAddresses) => {
          if (signatoryAddresses.length === 0) {
            throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);
          }
          return signatoryAddresses.map(({ address: address2 }) => address2);
        }
      )
    ],
    ["messageLength", getU16Encoder()]
  );
}
function getOffchainMessageV0Decoder() {
  return transformDecoder(
    getTupleDecoder([getOffchainMessageV0PreambleDecoder(), getUtf8Decoder()]),
    ([{ messageLength, messageFormat, requiredSignatories, ...preambleRest }, text]) => {
      const actualLength = getUtf8Encoder().getSizeFromValue(text);
      if (messageLength !== actualLength) {
        throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH, {
          actualLength,
          specifiedLength: messageLength
        });
      }
      const offchainMessage = Object.freeze({
        ...preambleRest,
        content: Object.freeze({
          format: messageFormat,
          text
        }),
        requiredSignatories: Object.freeze(requiredSignatories)
      });
      switch (messageFormat) {
        case 0: {
          assertIsOffchainMessageRestrictedAsciiOf1232BytesMax(offchainMessage);
          return offchainMessage;
        }
        case 1: {
          assertIsOffchainMessageUtf8Of1232BytesMax(offchainMessage);
          return offchainMessage;
        }
        case 2: {
          assertIsOffchainMessageUtf8Of65535BytesMax(offchainMessage);
          return offchainMessage;
        }
        default: {
          throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {
            unexpectedValue: messageFormat
          });
        }
      }
    }
  );
}
function getOffchainMessageV0Encoder() {
  return transformEncoder(
    getTupleEncoder([getOffchainMessageV0PreambleEncoder(), getUtf8Encoder()]),
    (offchainMessage) => {
      const { content, ...preamble } = offchainMessage;
      switch (offchainMessage.content.format) {
        case 0: {
          assertIsOffchainMessageRestrictedAsciiOf1232BytesMax(offchainMessage);
          break;
        }
        case 1: {
          assertIsOffchainMessageUtf8Of1232BytesMax(offchainMessage);
          break;
        }
        case 2: {
          assertIsOffchainMessageUtf8Of65535BytesMax(offchainMessage);
          break;
        }
        default: {
          throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {
            unexpectedValue: offchainMessage.content
          });
        }
      }
      const messageLength = getUtf8Encoder().getSizeFromValue(content.text);
      const compiledPreamble = {
        ...preamble,
        messageFormat: content.format,
        messageLength
      };
      return [compiledPreamble, content.text];
    }
  );
}
function getOffchainMessageV0Codec() {
  return combineCodec(getOffchainMessageV0Encoder(), getOffchainMessageV0Decoder());
}
function getOffchainMessageV1PreambleDecoder() {
  return createOffchainMessagePreambleDecoder(
    /* version */
    1,
    [
      "requiredSignatories",
      transformDecoder(
        getArrayDecoder(fixDecoderSize(getBytesDecoder(), 32), { size: getU8Decoder() }),
        (signatoryAddressesBytes) => {
          if (signatoryAddressesBytes.length === 0) {
            throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);
          }
          const comparator = getSignatoriesComparator();
          for (let ii = 0; ii < signatoryAddressesBytes.length - 1; ii++) {
            switch (comparator(signatoryAddressesBytes[ii], signatoryAddressesBytes[ii + 1])) {
              case 0:
                throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE);
              case 1:
                throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED);
            }
          }
          const addressDecoder = getAddressDecoder();
          return signatoryAddressesBytes.map(
            (addressBytes) => Object.freeze({
              address: addressDecoder.decode(addressBytes)
            })
          );
        }
      )
    ]
  );
}
function getOffchainMessageV1PreambleEncoder() {
  return createOffchainMessagePreambleEncoder(
    /* version */
    1,
    [
      "requiredSignatories",
      transformEncoder(
        transformEncoder(
          getArrayEncoder(getBytesEncoder(), { size: getU8Encoder() }),
          (signatoryAddressesBytes) => {
            return signatoryAddressesBytes.toSorted(getSignatoriesComparator());
          }
        ),
        (signatoryAddresses) => {
          if (signatoryAddresses.length === 0) {
            throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO);
          }
          const seenSignatories = /* @__PURE__ */ new Set();
          for (const { address: address2 } of signatoryAddresses) {
            if (seenSignatories.has(address2)) {
              throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE);
            }
            seenSignatories.add(address2);
          }
          const addressEncoder = getAddressEncoder();
          return signatoryAddresses.map(({ address: address2 }) => addressEncoder.encode(address2));
        }
      )
    ]
  );
}
function getOffchainMessageV1Decoder() {
  return transformDecoder(
    getTupleDecoder([getOffchainMessageV1PreambleDecoder(), getUtf8Decoder()]),
    ([{ requiredSignatories, ...preambleRest }, text]) => {
      if (text.length === 0) {
        throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);
      }
      return Object.freeze({
        ...preambleRest,
        content: text,
        requiredSignatories: Object.freeze(requiredSignatories)
      });
    }
  );
}
function getOffchainMessageV1Encoder() {
  return transformEncoder(
    getTupleEncoder([getOffchainMessageV1PreambleEncoder(), getUtf8Encoder()]),
    (offchainMessage) => {
      const { content, ...compiledPreamble } = offchainMessage;
      if (content.length === 0) {
        throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY);
      }
      return [compiledPreamble, content];
    }
  );
}
function getOffchainMessageV1Codec() {
  return combineCodec(getOffchainMessageV1Encoder(), getOffchainMessageV1Decoder());
}
function getOffchainMessageDecoder() {
  return createDecoder({
    read(bytes, offset) {
      const version4 = getHiddenPrefixDecoder(getU8Decoder(), [
        // Discard the signing domain
        getOffchainMessageSigningDomainDecoder()
      ]).decode(bytes, offset);
      switch (version4) {
        case 0:
          return getOffchainMessageV0Decoder().read(bytes, offset);
        case 1:
          return getOffchainMessageV1Decoder().read(bytes, offset);
        default:
          throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {
            unsupportedVersion: version4
          });
      }
    }
  });
}
function getOffchainMessageEncoder() {
  return createEncoder({
    getSizeFromValue: (offchainMessage) => {
      const { version: version4 } = offchainMessage;
      switch (version4) {
        case 0:
          return getOffchainMessageV0Encoder().getSizeFromValue(offchainMessage);
        case 1:
          return getOffchainMessageV1Encoder().getSizeFromValue(offchainMessage);
        default:
          throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {
            unsupportedVersion: version4
          });
      }
    },
    write: (offchainMessage, bytes, offset) => {
      const { version: version4 } = offchainMessage;
      switch (version4) {
        case 0:
          return getOffchainMessageV0Encoder().write(offchainMessage, bytes, offset);
        case 1:
          return getOffchainMessageV1Encoder().write(offchainMessage, bytes, offset);
        default:
          throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED, {
            unsupportedVersion: version4
          });
      }
    }
  });
}
function getOffchainMessageCodec() {
  return combineCodec(getOffchainMessageEncoder(), getOffchainMessageDecoder());
}
function compileOffchainMessageEnvelopeUsingEncoder(offchainMessage, encoder5) {
  const offchainMessageBytes = encoder5.encode(offchainMessage);
  const signatures = {};
  for (const { address: address2 } of offchainMessage.requiredSignatories) {
    signatures[address2] = null;
  }
  return Object.freeze({
    content: offchainMessageBytes,
    signatures: Object.freeze(signatures)
  });
}
function compileOffchainMessageV0Envelope(offchainMessage) {
  return compileOffchainMessageEnvelopeUsingEncoder(offchainMessage, getOffchainMessageV0Encoder());
}
function compileOffchainMessageV1Envelope(offchainMessage) {
  return compileOffchainMessageEnvelopeUsingEncoder(offchainMessage, getOffchainMessageV1Encoder());
}
function compileOffchainMessageEnvelope(offchainMessage) {
  const { version: version4 } = offchainMessage;
  switch (version4) {
    case 0:
      return compileOffchainMessageV0Envelope(offchainMessage);
    case 1:
      return compileOffchainMessageV1Envelope(offchainMessage);
    default:
      throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE, {
        unexpectedValue: version4
      });
  }
}
async function partiallySignOffchainMessageEnvelope(keyPairs, offchainMessageEnvelope) {
  let newSignatures;
  let unexpectedSigners;
  const requiredSignatoryAddresses = decodeRequiredSignatoryAddresses(offchainMessageEnvelope.content);
  await Promise.all(
    keyPairs.map(async (keyPair) => {
      const address2 = await getAddressFromPublicKey(keyPair.publicKey);
      if (!requiredSignatoryAddresses.includes(address2)) {
        unexpectedSigners ||= /* @__PURE__ */ new Set();
        unexpectedSigners.add(address2);
        return;
      }
      if (unexpectedSigners) {
        return;
      }
      const existingSignature = offchainMessageEnvelope.signatures[address2];
      const newSignature = await signBytes(keyPair.privateKey, offchainMessageEnvelope.content);
      if (existingSignature != null && bytesEqual(newSignature, existingSignature)) {
        return;
      }
      newSignatures ||= {};
      newSignatures[address2] = newSignature;
    })
  );
  if (unexpectedSigners && unexpectedSigners.size > 0) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE, {
      expectedAddresses: requiredSignatoryAddresses,
      unexpectedAddresses: [...unexpectedSigners]
    });
  }
  if (!newSignatures) {
    return offchainMessageEnvelope;
  }
  return Object.freeze({
    ...offchainMessageEnvelope,
    signatures: Object.freeze({
      ...offchainMessageEnvelope.signatures,
      ...newSignatures
    })
  });
}
async function signOffchainMessageEnvelope(keyPairs, offchainMessageEnvelope) {
  const out = await partiallySignOffchainMessageEnvelope(keyPairs, offchainMessageEnvelope);
  assertIsFullySignedOffchainMessageEnvelope(out);
  Object.freeze(out);
  return out;
}
function isFullySignedOffchainMessageEnvelope(offchainMessage) {
  return Object.entries(offchainMessage.signatures).every(([_, signatureBytes2]) => !!signatureBytes2);
}
function assertIsFullySignedOffchainMessageEnvelope(offchainMessage) {
  const missingSigs = [];
  Object.entries(offchainMessage.signatures).forEach(([address2, signatureBytes2]) => {
    if (!signatureBytes2) {
      missingSigs.push(address2);
    }
  });
  if (missingSigs.length > 0) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING, {
      addresses: missingSigs
    });
  }
}
async function verifyOffchainMessageEnvelope(offchainMessageEnvelope) {
  let errorContext;
  const requiredSignatories = decodeRequiredSignatoryAddresses(offchainMessageEnvelope.content);
  await Promise.all(
    requiredSignatories.map(async (address2) => {
      const signature2 = offchainMessageEnvelope.signatures[address2];
      if (signature2 == null) {
        errorContext ||= {};
        errorContext.signatoriesWithMissingSignatures ||= [];
        errorContext.signatoriesWithMissingSignatures.push(address2);
      } else {
        const publicKey = await getPublicKeyFromAddress(address2);
        if (await verifySignature(publicKey, signature2, offchainMessageEnvelope.content)) {
          return true;
        } else {
          errorContext ||= {};
          errorContext.signatoriesWithInvalidSignatures ||= [];
          errorContext.signatoriesWithInvalidSignatures.push(address2);
        }
      }
    })
  );
  if (errorContext) {
    throw new SolanaError(SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE, errorContext);
  }
}
var OFFCHAIN_MESSAGE_SIGNING_DOMAIN_BYTES, MAX_BODY_BYTES, MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE, OffchainMessageContentFormat;
var init_index_node19 = __esm({
  "node_modules/@solana/offchain-messages/dist/index.node.mjs"() {
    "use strict";
    init_index_node6();
    init_index_node();
    init_index_node2();
    init_index_node8();
    init_index_node7();
    init_index_node3();
    init_index_node15();
    OFFCHAIN_MESSAGE_SIGNING_DOMAIN_BYTES = new Uint8Array([
      255,
      115,
      111,
      108,
      97,
      110,
      97,
      32,
      111,
      102,
      102,
      99,
      104,
      97,
      105,
      110
    ]);
    MAX_BODY_BYTES = // Largest 16-bit unsigned integer
    65535;
    MAX_BODY_BYTES_HARDWARE_WALLET_SIGNABLE = // Space remaining in the mininum IPv6 MTU after network header overhead
    1232;
    OffchainMessageContentFormat = /* @__PURE__ */ ((OffchainMessageContentFormat3) => {
      OffchainMessageContentFormat3[OffchainMessageContentFormat3["RESTRICTED_ASCII_1232_BYTES_MAX"] = 0] = "RESTRICTED_ASCII_1232_BYTES_MAX";
      OffchainMessageContentFormat3[OffchainMessageContentFormat3["UTF8_1232_BYTES_MAX"] = 1] = "UTF8_1232_BYTES_MAX";
      OffchainMessageContentFormat3[OffchainMessageContentFormat3["UTF8_65535_BYTES_MAX"] = 2] = "UTF8_65535_BYTES_MAX";
      return OffchainMessageContentFormat3;
    })(OffchainMessageContentFormat || {});
  }
});

// node_modules/@solana/plugin-core/dist/index.node.mjs
function createEmptyClient() {
  return addUse({});
}
function addUse(value) {
  return Object.freeze({
    ...value,
    use(plugin2) {
      const result = plugin2(value);
      return result instanceof Promise ? createAsyncClient(result) : addUse(result);
    }
  });
}
function createAsyncClient(promise) {
  return Object.freeze({
    catch(onrejected) {
      return promise.then((v) => addUse(v)).catch(onrejected);
    },
    finally(onfinally) {
      return promise.then((v) => addUse(v)).finally(onfinally);
    },
    then(onfulfilled, onrejected) {
      return promise.then((v) => addUse(v)).then(onfulfilled, onrejected);
    },
    use(plugin2) {
      return createAsyncClient(promise.then(plugin2));
    }
  });
}
var init_index_node20 = __esm({
  "node_modules/@solana/plugin-core/dist/index.node.mjs"() {
    "use strict";
  }
});

// node_modules/@solana/programs/dist/index.node.mjs
function isProgramError(error, transactionMessage, programAddress, code) {
  if (!isSolanaError(error, SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM)) {
    return false;
  }
  const instructionProgramAddress = transactionMessage.instructions[error.context.index]?.programAddress;
  if (!instructionProgramAddress || instructionProgramAddress !== programAddress) {
    return false;
  }
  return typeof code === "undefined" || error.context.code === code;
}
var init_index_node21 = __esm({
  "node_modules/@solana/programs/dist/index.node.mjs"() {
    "use strict";
    init_index_node();
  }
});

// node_modules/@solana/rpc-spec-types/dist/index.node.mjs
function parseJsonWithBigInts(json) {
  return JSON.parse(wrapIntegersInBigIntValueObject(json), (_, value) => {
    return isBigIntValueObject(value) ? unwrapBigIntValueObject(value) : value;
  });
}
function wrapIntegersInBigIntValueObject(json) {
  const out = [];
  let inQuote = false;
  for (let ii = 0; ii < json.length; ii++) {
    let isEscaped = false;
    if (json[ii] === "\\") {
      out.push(json[ii++]);
      isEscaped = !isEscaped;
    }
    if (json[ii] === '"') {
      out.push(json[ii]);
      if (!isEscaped) {
        inQuote = !inQuote;
      }
      continue;
    }
    if (!inQuote) {
      const consumedNumber = consumeNumber(json, ii);
      if (consumedNumber?.length) {
        ii += consumedNumber.length - 1;
        if (consumedNumber.match(/\.|[eE]-/)) {
          out.push(consumedNumber);
        } else {
          out.push(wrapBigIntValueObject(consumedNumber));
        }
        continue;
      }
    }
    out.push(json[ii]);
  }
  return out.join("");
}
function consumeNumber(json, ii) {
  const JSON_NUMBER_REGEX = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/;
  if (!json[ii]?.match(/[-\d]/)) {
    return null;
  }
  const numberMatch = json.slice(ii).match(JSON_NUMBER_REGEX);
  return numberMatch ? numberMatch[0] : null;
}
function wrapBigIntValueObject(value) {
  return `{"$n":"${value}"}`;
}
function unwrapBigIntValueObject({ $n }) {
  if ($n.match(/[eE]/)) {
    const [units, exponent] = $n.split(/[eE]/);
    return BigInt(units) * BigInt(10) ** BigInt(exponent);
  }
  return BigInt($n);
}
function isBigIntValueObject(value) {
  return !!value && typeof value === "object" && "$n" in value && typeof value.$n === "string";
}
function getNextMessageId() {
  const id = _nextMessageId;
  _nextMessageId++;
  return id.toString();
}
function createRpcMessage(request) {
  return {
    id: getNextMessageId(),
    jsonrpc: "2.0",
    method: request.methodName,
    params: request.params
  };
}
function stringifyJsonWithBigInts(value, space) {
  return unwrapBigIntValueObject2(
    JSON.stringify(value, (_, v) => typeof v === "bigint" ? wrapBigIntValueObject2(v) : v, space)
  );
}
function wrapBigIntValueObject2(value) {
  return { $n: `${value}` };
}
function unwrapBigIntValueObject2(value) {
  return value.replace(/\{\s*"\$n"\s*:\s*"(-?\d+)"\s*\}/g, "$1");
}
var _nextMessageId;
var init_index_node22 = __esm({
  "node_modules/@solana/rpc-spec-types/dist/index.node.mjs"() {
    "use strict";
    _nextMessageId = 0n;
  }
});

// node_modules/@solana/rpc-spec/dist/index.node.mjs
function createRpc(rpcConfig) {
  return makeProxy(rpcConfig);
}
function makeProxy(rpcConfig) {
  return new Proxy(rpcConfig.api, {
    defineProperty() {
      return false;
    },
    deleteProperty() {
      return false;
    },
    get(target, p, receiver) {
      if (p === "then") {
        return void 0;
      }
      return function(...rawParams) {
        const methodName = p.toString();
        const getApiPlan = Reflect.get(target, methodName, receiver);
        if (!getApiPlan) {
          throw new SolanaError(SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD, {
            method: methodName,
            params: rawParams
          });
        }
        const apiPlan = getApiPlan(...rawParams);
        return createPendingRpcRequest(rpcConfig, apiPlan);
      };
    }
  });
}
function createPendingRpcRequest({ transport }, plan) {
  return {
    async send(options) {
      return await plan.execute({ signal: options?.abortSignal, transport });
    }
  };
}
function createJsonRpcApi(config) {
  return new Proxy({}, {
    defineProperty() {
      return false;
    },
    deleteProperty() {
      return false;
    },
    get(...args) {
      const [_, p] = args;
      const methodName = p.toString();
      return function(...rawParams) {
        const rawRequest = Object.freeze({ methodName, params: rawParams });
        const request = config?.requestTransformer ? config?.requestTransformer(rawRequest) : rawRequest;
        return Object.freeze({
          execute: async ({ signal, transport }) => {
            const payload = createRpcMessage(request);
            const response = await transport({ payload, signal });
            if (!config?.responseTransformer) {
              return response;
            }
            return config.responseTransformer(response, request);
          }
        });
      };
    }
  });
}
function isJsonRpcPayload(payload) {
  if (payload == null || typeof payload !== "object" || Array.isArray(payload)) {
    return false;
  }
  return "jsonrpc" in payload && payload.jsonrpc === "2.0" && "method" in payload && typeof payload.method === "string" && "params" in payload;
}
var init_index_node23 = __esm({
  "node_modules/@solana/rpc-spec/dist/index.node.mjs"() {
    "use strict";
    init_index_node();
    init_index_node22();
  }
});

// node_modules/@solana/rpc-transformers/dist/index.node.mjs
function downcastNodeToNumberIfBigint(value) {
  return typeof value === "bigint" ? (
    // FIXME(solana-labs/solana/issues/30341) Create a data type to represent u64 in the Solana
    // JSON RPC implementation so that we can throw away this entire patcher instead of unsafely
    // downcasting `bigints` to `numbers`.
    Number(value)
  ) : value;
}
function getTreeWalker(visitors) {
  return function traverse3(node, state) {
    if (Array.isArray(node)) {
      return node.map((element, ii) => {
        const nextState = {
          ...state,
          keyPath: [...state.keyPath, ii]
        };
        return traverse3(element, nextState);
      });
    } else if (typeof node === "object" && node !== null) {
      const out = {};
      for (const propName in node) {
        if (!Object.prototype.hasOwnProperty.call(node, propName)) {
          continue;
        }
        const nextState = {
          ...state,
          keyPath: [...state.keyPath, propName]
        };
        out[propName] = traverse3(node[propName], nextState);
      }
      return out;
    } else {
      return visitors.reduce((acc, visitNode) => visitNode(acc, state), node);
    }
  };
}
function getTreeWalkerRequestTransformer(visitors, initialState) {
  return (request) => {
    const traverse3 = getTreeWalker(visitors);
    return Object.freeze({
      ...request,
      params: traverse3(request.params, initialState)
    });
  };
}
function getTreeWalkerResponseTransformer(visitors, initialState) {
  return (json) => getTreeWalker(visitors)(json, initialState);
}
function getBigIntDowncastRequestTransformer() {
  return getTreeWalkerRequestTransformer([downcastNodeToNumberIfBigint], { keyPath: [] });
}
function applyDefaultCommitment({
  commitmentPropertyName,
  params,
  optionsObjectPositionInParams,
  overrideCommitment
}) {
  const paramInTargetPosition = params[optionsObjectPositionInParams];
  if (
    // There's no config.
    paramInTargetPosition === void 0 || // There is a config object.
    paramInTargetPosition && typeof paramInTargetPosition === "object" && !Array.isArray(paramInTargetPosition)
  ) {
    if (
      // The config object already has a commitment set.
      paramInTargetPosition && commitmentPropertyName in paramInTargetPosition
    ) {
      if (!paramInTargetPosition[commitmentPropertyName] || paramInTargetPosition[commitmentPropertyName] === "finalized") {
        const nextParams = [...params];
        const {
          [commitmentPropertyName]: _,
          // eslint-disable-line @typescript-eslint/no-unused-vars
          ...rest
        } = paramInTargetPosition;
        if (Object.keys(rest).length > 0) {
          nextParams[optionsObjectPositionInParams] = rest;
        } else {
          if (optionsObjectPositionInParams === nextParams.length - 1) {
            nextParams.length--;
          } else {
            nextParams[optionsObjectPositionInParams] = void 0;
          }
        }
        return nextParams;
      }
    } else if (overrideCommitment !== "finalized") {
      const nextParams = [...params];
      nextParams[optionsObjectPositionInParams] = {
        ...paramInTargetPosition,
        [commitmentPropertyName]: overrideCommitment
      };
      return nextParams;
    }
  }
  return params;
}
function getDefaultCommitmentRequestTransformer({
  defaultCommitment,
  optionsObjectPositionByMethod
}) {
  return (request) => {
    const { params, methodName } = request;
    if (!Array.isArray(params)) {
      return request;
    }
    const optionsObjectPositionInParams = optionsObjectPositionByMethod[methodName];
    if (optionsObjectPositionInParams == null) {
      return request;
    }
    return Object.freeze({
      methodName,
      params: applyDefaultCommitment({
        commitmentPropertyName: methodName === "sendTransaction" ? "preflightCommitment" : "commitment",
        optionsObjectPositionInParams,
        overrideCommitment: defaultCommitment,
        params
      })
    });
  };
}
function getIntegerOverflowNodeVisitor(onIntegerOverflow) {
  return (value, { keyPath }) => {
    if (typeof value === "bigint") {
      if (onIntegerOverflow && (value > Number.MAX_SAFE_INTEGER || value < -Number.MAX_SAFE_INTEGER)) {
        onIntegerOverflow(keyPath, value);
      }
    }
    return value;
  };
}
function getIntegerOverflowRequestTransformer(onIntegerOverflow) {
  return (request) => {
    const transformer = getTreeWalkerRequestTransformer(
      [getIntegerOverflowNodeVisitor((...args) => onIntegerOverflow(request, ...args))],
      { keyPath: [] }
    );
    return transformer(request);
  };
}
function getDefaultRequestTransformerForSolanaRpc(config) {
  const handleIntegerOverflow = config?.onIntegerOverflow;
  return (request) => {
    return pipe(
      request,
      handleIntegerOverflow ? getIntegerOverflowRequestTransformer(handleIntegerOverflow) : (r) => r,
      getBigIntDowncastRequestTransformer(),
      getDefaultCommitmentRequestTransformer({
        defaultCommitment: config?.defaultCommitment,
        optionsObjectPositionByMethod: OPTIONS_OBJECT_POSITION_BY_METHOD
      })
    );
  };
}
function getBigIntUpcastVisitor(allowedNumericKeyPaths) {
  return function upcastNodeToBigIntIfNumber(value, { keyPath }) {
    const isInteger = typeof value === "number" && Number.isInteger(value) || typeof value === "bigint";
    if (!isInteger) return value;
    if (keyPathIsAllowedToBeNumeric(keyPath, allowedNumericKeyPaths)) {
      return Number(value);
    } else {
      return BigInt(value);
    }
  };
}
function keyPathIsAllowedToBeNumeric(keyPath, allowedNumericKeyPaths) {
  return allowedNumericKeyPaths.some((prohibitedKeyPath) => {
    if (prohibitedKeyPath.length !== keyPath.length) {
      return false;
    }
    for (let ii = keyPath.length - 1; ii >= 0; ii--) {
      const keyPathPart = keyPath[ii];
      const prohibitedKeyPathPart = prohibitedKeyPath[ii];
      if (prohibitedKeyPathPart !== keyPathPart && (prohibitedKeyPathPart !== KEYPATH_WILDCARD || typeof keyPathPart !== "number")) {
        return false;
      }
    }
    return true;
  });
}
function getBigIntUpcastResponseTransformer(allowedNumericKeyPaths) {
  return getTreeWalkerResponseTransformer([getBigIntUpcastVisitor(allowedNumericKeyPaths)], { keyPath: [] });
}
function getResultResponseTransformer() {
  return (json) => json.result;
}
function getSimulateTransactionAllowedNumericKeypaths() {
  return [
    ["loadedAccountsDataSize"],
    ...jsonParsedAccountsConfigs.map((c) => ["accounts", KEYPATH_WILDCARD, ...c]),
    ...innerInstructionsConfigs.map((c) => ["innerInstructions", KEYPATH_WILDCARD, ...c])
  ];
}
function getThrowSolanaErrorResponseTransformer() {
  return (json, request) => {
    const jsonRpcResponse = json;
    if ("error" in jsonRpcResponse) {
      const { error } = jsonRpcResponse;
      const isSendTransactionPreflightFailure = error && typeof error === "object" && "code" in error && (error.code === -32002 || error.code === -32002n);
      if (isSendTransactionPreflightFailure && "data" in error && error.data) {
        const treeWalker = getTreeWalkerResponseTransformer(
          [getBigIntUpcastVisitor(getSimulateTransactionAllowedNumericKeypaths())],
          { keyPath: [] }
        );
        const transformedData = treeWalker(error.data, request);
        const transformedError = { ...error, data: transformedData };
        throw getSolanaErrorFromJsonRpcError(transformedError);
      }
      throw getSolanaErrorFromJsonRpcError(jsonRpcResponse.error);
    }
    return jsonRpcResponse;
  };
}
function getDefaultResponseTransformerForSolanaRpc(config) {
  return (response, request) => {
    const methodName = request.methodName;
    const keyPaths = config?.allowedNumericKeyPaths && methodName ? config.allowedNumericKeyPaths[methodName] : void 0;
    return pipe(
      response,
      (r) => getThrowSolanaErrorResponseTransformer()(r, request),
      (r) => getResultResponseTransformer()(r, request),
      (r) => getBigIntUpcastResponseTransformer(keyPaths ?? [])(r, request)
    );
  };
}
function getDefaultResponseTransformerForSolanaRpcSubscriptions(config) {
  return (response, request) => {
    const methodName = request.methodName;
    const keyPaths = config?.allowedNumericKeyPaths && methodName ? config.allowedNumericKeyPaths[methodName] : void 0;
    return pipe(response, (r) => getBigIntUpcastResponseTransformer(keyPaths ?? [])(r, request));
  };
}
var KEYPATH_WILDCARD, OPTIONS_OBJECT_POSITION_BY_METHOD, jsonParsedTokenAccountsConfigs, jsonParsedAccountsConfigs, innerInstructionsConfigs, messageConfig;
var init_index_node24 = __esm({
  "node_modules/@solana/rpc-transformers/dist/index.node.mjs"() {
    "use strict";
    init_index_node11();
    init_index_node();
    KEYPATH_WILDCARD = {};
    OPTIONS_OBJECT_POSITION_BY_METHOD = {
      accountNotifications: 1,
      blockNotifications: 1,
      getAccountInfo: 1,
      getBalance: 1,
      getBlock: 1,
      getBlockHeight: 0,
      getBlockProduction: 0,
      getBlocks: 2,
      getBlocksWithLimit: 2,
      getEpochInfo: 0,
      getFeeForMessage: 1,
      getInflationGovernor: 0,
      getInflationReward: 1,
      getLargestAccounts: 0,
      getLatestBlockhash: 0,
      getLeaderSchedule: 1,
      getMinimumBalanceForRentExemption: 1,
      getMultipleAccounts: 1,
      getProgramAccounts: 1,
      getSignaturesForAddress: 1,
      getSlot: 0,
      getSlotLeader: 0,
      getStakeMinimumDelegation: 0,
      getSupply: 0,
      getTokenAccountBalance: 1,
      getTokenAccountsByDelegate: 2,
      getTokenAccountsByOwner: 2,
      getTokenLargestAccounts: 1,
      getTokenSupply: 1,
      getTransaction: 1,
      getTransactionCount: 0,
      getVoteAccounts: 0,
      isBlockhashValid: 1,
      logsNotifications: 1,
      programNotifications: 1,
      requestAirdrop: 2,
      sendTransaction: 1,
      signatureNotifications: 1,
      simulateTransaction: 1
    };
    jsonParsedTokenAccountsConfigs = [
      // parsed Token/Token22 token account
      ["data", "parsed", "info", "tokenAmount", "decimals"],
      ["data", "parsed", "info", "tokenAmount", "uiAmount"],
      ["data", "parsed", "info", "rentExemptReserve", "decimals"],
      ["data", "parsed", "info", "rentExemptReserve", "uiAmount"],
      ["data", "parsed", "info", "delegatedAmount", "decimals"],
      ["data", "parsed", "info", "delegatedAmount", "uiAmount"],
      ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "olderTransferFee", "transferFeeBasisPoints"],
      ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "newerTransferFee", "transferFeeBasisPoints"],
      ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "preUpdateAverageRate"],
      ["data", "parsed", "info", "extensions", KEYPATH_WILDCARD, "state", "currentRate"]
    ];
    jsonParsedAccountsConfigs = [
      ...jsonParsedTokenAccountsConfigs,
      // parsed AddressTableLookup account
      ["data", "parsed", "info", "lastExtendedSlotStartIndex"],
      // parsed Config account
      ["data", "parsed", "info", "slashPenalty"],
      ["data", "parsed", "info", "warmupCooldownRate"],
      // parsed Token/Token22 mint account
      ["data", "parsed", "info", "decimals"],
      // parsed Token/Token22 multisig account
      ["data", "parsed", "info", "numRequiredSigners"],
      ["data", "parsed", "info", "numValidSigners"],
      // parsed Stake account
      ["data", "parsed", "info", "stake", "delegation", "warmupCooldownRate"],
      // parsed Sysvar rent account
      ["data", "parsed", "info", "exemptionThreshold"],
      ["data", "parsed", "info", "burnPercent"],
      // parsed Vote account
      ["data", "parsed", "info", "commission"],
      ["data", "parsed", "info", "votes", KEYPATH_WILDCARD, "confirmationCount"]
    ];
    innerInstructionsConfigs = [
      ["index"],
      ["instructions", KEYPATH_WILDCARD, "accounts", KEYPATH_WILDCARD],
      ["instructions", KEYPATH_WILDCARD, "programIdIndex"],
      ["instructions", KEYPATH_WILDCARD, "stackHeight"]
    ];
    messageConfig = [
      ["addressTableLookups", KEYPATH_WILDCARD, "writableIndexes", KEYPATH_WILDCARD],
      ["addressTableLookups", KEYPATH_WILDCARD, "readonlyIndexes", KEYPATH_WILDCARD],
      ["header", "numReadonlySignedAccounts"],
      ["header", "numReadonlyUnsignedAccounts"],
      ["header", "numRequiredSignatures"],
      ["instructions", KEYPATH_WILDCARD, "accounts", KEYPATH_WILDCARD],
      ["instructions", KEYPATH_WILDCARD, "programIdIndex"],
      ["instructions", KEYPATH_WILDCARD, "stackHeight"]
    ];
  }
});

// node_modules/@solana/rpc-api/dist/index.node.mjs
function createSolanaRpcApi(config) {
  return createJsonRpcApi({
    requestTransformer: getDefaultRequestTransformerForSolanaRpc(config),
    responseTransformer: getDefaultResponseTransformerForSolanaRpc({
      allowedNumericKeyPaths: getAllowedNumericKeypaths()
    })
  });
}
function getAllowedNumericKeypaths() {
  if (!memoizedKeypaths) {
    memoizedKeypaths = {
      getAccountInfo: jsonParsedAccountsConfigs.map((c) => ["value", ...c]),
      getBlock: [
        ["transactions", KEYPATH_WILDCARD, "meta", "preTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
        [
          "transactions",
          KEYPATH_WILDCARD,
          "meta",
          "preTokenBalances",
          KEYPATH_WILDCARD,
          "uiTokenAmount",
          "decimals"
        ],
        ["transactions", KEYPATH_WILDCARD, "meta", "postTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
        [
          "transactions",
          KEYPATH_WILDCARD,
          "meta",
          "postTokenBalances",
          KEYPATH_WILDCARD,
          "uiTokenAmount",
          "decimals"
        ],
        ["transactions", KEYPATH_WILDCARD, "meta", "rewards", KEYPATH_WILDCARD, "commission"],
        ...innerInstructionsConfigs.map((c) => [
          "transactions",
          KEYPATH_WILDCARD,
          "meta",
          "innerInstructions",
          KEYPATH_WILDCARD,
          ...c
        ]),
        ...messageConfig.map((c) => ["transactions", KEYPATH_WILDCARD, "transaction", "message", ...c]),
        ["rewards", KEYPATH_WILDCARD, "commission"]
      ],
      getClusterNodes: [
        [KEYPATH_WILDCARD, "featureSet"],
        [KEYPATH_WILDCARD, "shredVersion"]
      ],
      getInflationGovernor: [["initial"], ["foundation"], ["foundationTerm"], ["taper"], ["terminal"]],
      getInflationRate: [["foundation"], ["total"], ["validator"]],
      getInflationReward: [[KEYPATH_WILDCARD, "commission"]],
      getMultipleAccounts: jsonParsedAccountsConfigs.map((c) => ["value", KEYPATH_WILDCARD, ...c]),
      getProgramAccounts: jsonParsedAccountsConfigs.flatMap((c) => [
        ["value", KEYPATH_WILDCARD, "account", ...c],
        [KEYPATH_WILDCARD, "account", ...c]
      ]),
      getRecentPerformanceSamples: [[KEYPATH_WILDCARD, "samplePeriodSecs"]],
      getTokenAccountBalance: [
        ["value", "decimals"],
        ["value", "uiAmount"]
      ],
      getTokenAccountsByDelegate: jsonParsedTokenAccountsConfigs.map((c) => [
        "value",
        KEYPATH_WILDCARD,
        "account",
        ...c
      ]),
      getTokenAccountsByOwner: jsonParsedTokenAccountsConfigs.map((c) => [
        "value",
        KEYPATH_WILDCARD,
        "account",
        ...c
      ]),
      getTokenLargestAccounts: [
        ["value", KEYPATH_WILDCARD, "decimals"],
        ["value", KEYPATH_WILDCARD, "uiAmount"]
      ],
      getTokenSupply: [
        ["value", "decimals"],
        ["value", "uiAmount"]
      ],
      getTransaction: [
        ["meta", "preTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
        ["meta", "preTokenBalances", KEYPATH_WILDCARD, "uiTokenAmount", "decimals"],
        ["meta", "postTokenBalances", KEYPATH_WILDCARD, "accountIndex"],
        ["meta", "postTokenBalances", KEYPATH_WILDCARD, "uiTokenAmount", "decimals"],
        ["meta", "rewards", KEYPATH_WILDCARD, "commission"],
        ...innerInstructionsConfigs.map((c) => ["meta", "innerInstructions", KEYPATH_WILDCARD, ...c]),
        ...messageConfig.map((c) => ["transaction", "message", ...c])
      ],
      getVersion: [["feature-set"]],
      getVoteAccounts: [
        ["current", KEYPATH_WILDCARD, "commission"],
        ["delinquent", KEYPATH_WILDCARD, "commission"]
      ],
      simulateTransaction: [
        ["value", "loadedAccountsDataSize"],
        ...jsonParsedAccountsConfigs.map((c) => ["value", "accounts", KEYPATH_WILDCARD, ...c]),
        ...innerInstructionsConfigs.map((c) => ["value", "innerInstructions", KEYPATH_WILDCARD, ...c])
      ]
    };
  }
  return memoizedKeypaths;
}
var memoizedKeypaths;
var init_index_node25 = __esm({
  "node_modules/@solana/rpc-api/dist/index.node.mjs"() {
    "use strict";
    init_index_node23();
    init_index_node24();
  }
});

// node_modules/@solana/rpc-transport-http/dist/index.node.mjs
function assertIsAllowedHttpRequestHeaders(headers) {
  const badHeaders = Object.keys(headers).filter((headerName) => {
    const lowercaseHeaderName = headerName.toLowerCase();
    return DISALLOWED_HEADERS[headerName.toLowerCase()] === true || FORBIDDEN_HEADERS[headerName.toLowerCase()] === true || lowercaseHeaderName.startsWith("proxy-") || lowercaseHeaderName.startsWith("sec-");
  });
  if (badHeaders.length > 0) {
    throw new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN, {
      headers: badHeaders
    });
  }
}
function normalizeHeaders(headers) {
  const out = {};
  for (const headerName in headers) {
    out[headerName.toLowerCase()] = headers[headerName];
  }
  return out;
}
function createHttpTransport(config) {
  if (process.env.NODE_ENV !== "production" && false) ;
  const { fromJson, headers, toJson, url } = config;
  if (process.env.NODE_ENV !== "production" && headers) {
    assertIsAllowedHttpRequestHeaders(headers);
  }
  let dispatcherConfig;
  if ("dispatcher_NODE_ONLY" in config) {
    dispatcherConfig = { dispatcher: config.dispatcher_NODE_ONLY };
  }
  const customHeaders = headers && normalizeHeaders(headers);
  return async function makeHttpRequest({
    payload,
    signal
  }) {
    const body = toJson ? toJson(payload) : JSON.stringify(payload);
    const requestInfo = {
      ...dispatcherConfig,
      body,
      headers: {
        ...customHeaders,
        // Keep these headers lowercase so they will override any user-supplied headers above.
        accept: "application/json",
        "content-length": body.length.toString(),
        "content-type": "application/json; charset=utf-8"
      },
      method: "POST",
      signal
    };
    const response = await fetch(url, requestInfo);
    if (!response.ok) {
      throw new SolanaError(SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, {
        headers: response.headers,
        message: response.statusText,
        statusCode: response.status
      });
    }
    if (fromJson) {
      return fromJson(await response.text(), payload);
    }
    return await response.json();
  };
}
function isSolanaRequest(payload) {
  return isJsonRpcPayload(payload) && SOLANA_RPC_METHODS.includes(payload.method);
}
function createHttpTransportForSolanaRpc(config) {
  return createHttpTransport({
    ...config,
    fromJson: (rawResponse, payload) => isSolanaRequest(payload) ? parseJsonWithBigInts(rawResponse) : JSON.parse(rawResponse),
    toJson: (payload) => isSolanaRequest(payload) ? stringifyJsonWithBigInts(payload) : JSON.stringify(payload)
  });
}
var DISALLOWED_HEADERS, FORBIDDEN_HEADERS, SOLANA_RPC_METHODS;
var init_index_node26 = __esm({
  "node_modules/@solana/rpc-transport-http/dist/index.node.mjs"() {
    "use strict";
    init_index_node();
    init_index_node22();
    init_index_node23();
    DISALLOWED_HEADERS = {
      accept: true,
      "content-length": true,
      "content-type": true
    };
    FORBIDDEN_HEADERS = /* @__PURE__ */ Object.assign(
      {
        "accept-charset": true,
        "access-control-request-headers": true,
        "access-control-request-method": true,
        connection: true,
        "content-length": true,
        cookie: true,
        date: true,
        dnt: true,
        expect: true,
        host: true,
        "keep-alive": true,
        "permissions-policy": true,
        // Prefix matching is implemented in code, below.
        // 'proxy-': true,
        // 'sec-': true,
        referer: true,
        te: true,
        trailer: true,
        "transfer-encoding": true,
        upgrade: true,
        via: true
      },
      void 0,
      void 0
    );
    SOLANA_RPC_METHODS = [
      "getAccountInfo",
      "getBalance",
      "getBlock",
      "getBlockCommitment",
      "getBlockHeight",
      "getBlockProduction",
      "getBlocks",
      "getBlocksWithLimit",
      "getBlockTime",
      "getClusterNodes",
      "getEpochInfo",
      "getEpochSchedule",
      "getFeeForMessage",
      "getFirstAvailableBlock",
      "getGenesisHash",
      "getHealth",
      "getHighestSnapshotSlot",
      "getIdentity",
      "getInflationGovernor",
      "getInflationRate",
      "getInflationReward",
      "getLargestAccounts",
      "getLatestBlockhash",
      "getLeaderSchedule",
      "getMaxRetransmitSlot",
      "getMaxShredInsertSlot",
      "getMinimumBalanceForRentExemption",
      "getMultipleAccounts",
      "getProgramAccounts",
      "getRecentPerformanceSamples",
      "getRecentPrioritizationFees",
      "getSignaturesForAddress",
      "getSignatureStatuses",
      "getSlot",
      "getSlotLeader",
      "getSlotLeaders",
      "getStakeMinimumDelegation",
      "getSupply",
      "getTokenAccountBalance",
      "getTokenAccountsByDelegate",
      "getTokenAccountsByOwner",
      "getTokenLargestAccounts",
      "getTokenSupply",
      "getTransaction",
      "getTransactionCount",
      "getVersion",
      "getVoteAccounts",
      "index",
      "isBlockhashValid",
      "minimumLedgerSlot",
      "requestAirdrop",
      "sendTransaction",
      "simulateTransaction"
    ];
  }
});

// node_modules/@solana/fast-stable-stringify/dist/index.node.mjs
function stringify3(val, isArrayProp) {
  let i, max, str, keys, key, propVal, toStr;
  if (val === true) {
    return "true";
  }
  if (val === false) {
    return "false";
  }
  switch (typeof val) {
    case "object":
      if (val === null) {
        return null;
      } else if ("toJSON" in val && typeof val.toJSON === "function") {
        return stringify3(val.toJSON(), isArrayProp);
      } else {
        toStr = objToString.call(val);
        if (toStr === "[object Array]") {
          str = "[";
          max = val.length - 1;
          for (i = 0; i < max; i++) {
            str += stringify3(val[i], true) + ",";
          }
          if (max > -1) {
            str += stringify3(val[i], true);
          }
          return str + "]";
        } else if (toStr === "[object Object]") {
          keys = objKeys(val).sort();
          max = keys.length;
          str = "";
          i = 0;
          while (i < max) {
            key = keys[i];
            propVal = stringify3(val[key], false);
            if (propVal !== void 0) {
              if (str) {
                str += ",";
              }
              str += JSON.stringify(key) + ":" + propVal;
            }
            i++;
          }
          return "{" + str + "}";
        } else {
          return JSON.stringify(val);
        }
      }
    case "function":
    case "undefined":
      return isArrayProp ? null : void 0;
    case "bigint":
      return `${val.toString()}n`;
    case "string":
      return JSON.stringify(val);
    default:
      return isFinite(val) ? val : null;
  }
}
function index_default(val) {
  const returnVal = stringify3(val, false);
  if (returnVal !== void 0) {
    return "" + returnVal;
  }
}
var objToString, objKeys;
var init_index_node27 = __esm({
  "node_modules/@solana/fast-stable-stringify/dist/index.node.mjs"() {
    "use strict";
    objToString = Object.prototype.toString;
    objKeys = Object.keys || function(obj) {
      const keys = [];
      for (const name in obj) {
        keys.push(name);
      }
      return keys;
    };
  }
});

// node_modules/@solana/rpc/dist/index.node.mjs
import { setMaxListeners } from "events";
function createSolanaJsonRpcIntegerOverflowError(methodName, keyPath, value) {
  let argumentLabel = "";
  if (typeof keyPath[0] === "number") {
    const argPosition = keyPath[0] + 1;
    const lastDigit = argPosition % 10;
    const lastTwoDigits = argPosition % 100;
    if (lastDigit == 1 && lastTwoDigits != 11) {
      argumentLabel = argPosition + "st";
    } else if (lastDigit == 2 && lastTwoDigits != 12) {
      argumentLabel = argPosition + "nd";
    } else if (lastDigit == 3 && lastTwoDigits != 13) {
      argumentLabel = argPosition + "rd";
    } else {
      argumentLabel = argPosition + "th";
    }
  } else {
    argumentLabel = `\`${keyPath[0].toString()}\``;
  }
  const path2 = keyPath.length > 1 ? keyPath.slice(1).map((pathPart) => typeof pathPart === "number" ? `[${pathPart}]` : pathPart).join(".") : void 0;
  const error = new SolanaError(SOLANA_ERROR__RPC__INTEGER_OVERFLOW, {
    argumentLabel,
    keyPath,
    methodName,
    optionalPathLabel: path2 ? ` at path \`${path2}\`` : "",
    value,
    ...path2 !== void 0 ? { path: path2 } : void 0
  });
  safeCaptureStackTrace(error, createSolanaJsonRpcIntegerOverflowError);
  return error;
}
function createExplicitAbortToken() {
  return process.env.NODE_ENV !== "production" ? {
    EXPLICIT_ABORT_TOKEN: "This object is thrown from the request that underlies a series of coalesced requests when the last request in that series aborts"
  } : {};
}
function getRpcTransportWithRequestCoalescing(transport, getDeduplicationKey) {
  let coalescedRequestsByDeduplicationKey;
  return async function makeCoalescedHttpRequest(request) {
    const { payload, signal } = request;
    const deduplicationKey = getDeduplicationKey(payload);
    if (deduplicationKey === void 0) {
      return await transport(request);
    }
    if (!coalescedRequestsByDeduplicationKey) {
      queueMicrotask(() => {
        coalescedRequestsByDeduplicationKey = void 0;
      });
      coalescedRequestsByDeduplicationKey = {};
    }
    if (coalescedRequestsByDeduplicationKey[deduplicationKey] == null) {
      const abortController = new e2();
      const responsePromise = (async () => {
        try {
          return await transport({
            ...request,
            signal: abortController.signal
          });
        } catch (e22) {
          if (e22 === (EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken())) {
            return;
          }
          throw e22;
        }
      })();
      coalescedRequestsByDeduplicationKey[deduplicationKey] = {
        abortController,
        numConsumers: 0,
        responsePromise
      };
    }
    const coalescedRequest = coalescedRequestsByDeduplicationKey[deduplicationKey];
    coalescedRequest.numConsumers++;
    if (signal) {
      const responsePromise = coalescedRequest.responsePromise;
      return await new Promise((resolve, reject) => {
        const handleAbort = (e22) => {
          signal.removeEventListener("abort", handleAbort);
          coalescedRequest.numConsumers -= 1;
          queueMicrotask(() => {
            if (coalescedRequest.numConsumers === 0) {
              const abortController = coalescedRequest.abortController;
              abortController.abort(EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken());
            }
          });
          reject(e22.target.reason);
        };
        signal.addEventListener("abort", handleAbort);
        responsePromise.then(resolve).catch(reject).finally(() => {
          signal.removeEventListener("abort", handleAbort);
        });
      });
    } else {
      return await coalescedRequest.responsePromise;
    }
  };
}
function getSolanaRpcPayloadDeduplicationKey(payload) {
  return isJsonRpcPayload(payload) ? index_default([payload.method, payload.params]) : void 0;
}
function normalizeHeaders2(headers) {
  const out = {};
  for (const headerName in headers) {
    out[headerName.toLowerCase()] = headers[headerName];
  }
  return out;
}
function createDefaultRpcTransport(config) {
  return pipe(
    createHttpTransportForSolanaRpc({
      ...config,
      headers: {
        ...{
          // Keep these headers lowercase so they will be overridden by any user-supplied headers below.
          "accept-encoding": (
            // Natively supported by Node LTS v20.18.0 and above.
            "br,gzip,deflate"
          )
          // Brotli, gzip, and Deflate, in that order.
        },
        ...config.headers ? normalizeHeaders2(config.headers) : void 0,
        ...{
          // Keep these headers lowercase so they will override any user-supplied headers above.
          "solana-client": `js/${"5.5.1"}`
        }
      }
    }),
    (transport) => getRpcTransportWithRequestCoalescing(transport, getSolanaRpcPayloadDeduplicationKey)
  );
}
function createSolanaRpc(clusterUrl, config) {
  return createSolanaRpcFromTransport(createDefaultRpcTransport({ url: clusterUrl, ...config }));
}
function createSolanaRpcFromTransport(transport) {
  return createRpc({
    api: createSolanaRpcApi(DEFAULT_RPC_CONFIG),
    transport
  });
}
var DEFAULT_RPC_CONFIG, e2, EXPLICIT_ABORT_TOKEN;
var init_index_node28 = __esm({
  "node_modules/@solana/rpc/dist/index.node.mjs"() {
    "use strict";
    init_index_node25();
    init_index_node25();
    init_index_node23();
    init_index_node23();
    init_index_node();
    init_index_node11();
    init_index_node26();
    init_index_node27();
    DEFAULT_RPC_CONFIG = {
      defaultCommitment: "confirmed",
      onIntegerOverflow(request, keyPath, value) {
        throw createSolanaJsonRpcIntegerOverflowError(request.methodName, keyPath, value);
      }
    };
    e2 = class extends globalThis.AbortController {
      constructor(...t) {
        super(...t), setMaxListeners(Number.MAX_SAFE_INTEGER, this.signal);
      }
    };
  }
});

// node_modules/@solana/rpc-parsed-types/dist/index.node.mjs
var init_index_node29 = __esm({
  "node_modules/@solana/rpc-parsed-types/dist/index.node.mjs"() {
    "use strict";
  }
});

// node_modules/@solana/subscribable/dist/index.node.mjs
import { setMaxListeners as setMaxListeners2 } from "events";
function createExplicitAbortToken2() {
  return /* @__PURE__ */ Symbol(
    process.env.NODE_ENV !== "production" ? "This symbol is thrown from a socket's iterator when the connection is explicitly aborted by the user" : void 0
  );
}
function createAsyncIterableFromDataPublisher({
  abortSignal,
  dataChannelName,
  dataPublisher,
  errorChannelName
}) {
  const iteratorState = /* @__PURE__ */ new Map();
  function publishErrorToAllIterators(reason) {
    for (const [iteratorKey, state] of iteratorState.entries()) {
      if (state.__hasPolled) {
        iteratorState.delete(iteratorKey);
        state.onError(reason);
      } else {
        state.publishQueue.push({
          __type: 1,
          err: reason
        });
      }
    }
  }
  const abortController = new e3();
  abortSignal.addEventListener("abort", () => {
    abortController.abort();
    publishErrorToAllIterators(EXPLICIT_ABORT_TOKEN2 ||= createExplicitAbortToken2());
  });
  const options = { signal: abortController.signal };
  let firstError = UNINITIALIZED;
  dataPublisher.on(
    errorChannelName,
    (err) => {
      if (firstError === UNINITIALIZED) {
        firstError = err;
        abortController.abort();
        publishErrorToAllIterators(err);
      }
    },
    options
  );
  dataPublisher.on(
    dataChannelName,
    (data) => {
      iteratorState.forEach((state, iteratorKey) => {
        if (state.__hasPolled) {
          const { onData } = state;
          iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });
          onData(data);
        } else {
          state.publishQueue.push({
            __type: 0,
            data
          });
        }
      });
    },
    options
  );
  return {
    async *[Symbol.asyncIterator]() {
      if (abortSignal.aborted) {
        return;
      }
      if (firstError !== UNINITIALIZED) {
        throw firstError;
      }
      const iteratorKey = /* @__PURE__ */ Symbol();
      iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });
      try {
        while (true) {
          const state = iteratorState.get(iteratorKey);
          if (!state) {
            throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING);
          }
          if (state.__hasPolled) {
            throw new SolanaError(
              SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE
            );
          }
          const publishQueue = state.publishQueue;
          try {
            if (publishQueue.length) {
              state.publishQueue = [];
              for (const item of publishQueue) {
                if (item.__type === 0) {
                  yield item.data;
                } else {
                  throw item.err;
                }
              }
            } else {
              yield await new Promise((resolve, reject) => {
                iteratorState.set(iteratorKey, {
                  __hasPolled: true,
                  onData: resolve,
                  onError: reject
                });
              });
            }
          } catch (e22) {
            if (e22 === (EXPLICIT_ABORT_TOKEN2 ||= createExplicitAbortToken2())) {
              return;
            } else {
              throw e22;
            }
          }
        }
      } finally {
        iteratorState.delete(iteratorKey);
      }
    }
  };
}
function getDataPublisherFromEventEmitter(eventEmitter) {
  return {
    on(channelName, subscriber, options) {
      function innerListener(ev) {
        if (ev instanceof CustomEvent) {
          const data = ev.detail;
          subscriber(data);
        } else {
          subscriber();
        }
      }
      eventEmitter.addEventListener(channelName, innerListener, options);
      return () => {
        eventEmitter.removeEventListener(channelName, innerListener);
      };
    }
  };
}
function demultiplexDataPublisher(publisher, sourceChannelName, messageTransformer) {
  let innerPublisherState;
  const eventTarget = new s();
  const demultiplexedDataPublisher = getDataPublisherFromEventEmitter(eventTarget);
  return {
    ...demultiplexedDataPublisher,
    on(channelName, subscriber, options) {
      if (!innerPublisherState) {
        const innerPublisherUnsubscribe = publisher.on(sourceChannelName, (sourceMessage) => {
          const transformResult = messageTransformer(sourceMessage);
          if (!transformResult) {
            return;
          }
          const [destinationChannelName, message] = transformResult;
          eventTarget.dispatchEvent(
            new CustomEvent(destinationChannelName, {
              detail: message
            })
          );
        });
        innerPublisherState = {
          dispose: innerPublisherUnsubscribe,
          numSubscribers: 0
        };
      }
      innerPublisherState.numSubscribers++;
      const unsubscribe = demultiplexedDataPublisher.on(channelName, subscriber, options);
      let isActive = true;
      function handleUnsubscribe() {
        if (!isActive) {
          return;
        }
        isActive = false;
        options?.signal.removeEventListener("abort", handleUnsubscribe);
        innerPublisherState.numSubscribers--;
        if (innerPublisherState.numSubscribers === 0) {
          innerPublisherState.dispose();
          innerPublisherState = void 0;
        }
        unsubscribe();
      }
      options?.signal.addEventListener("abort", handleUnsubscribe);
      return handleUnsubscribe;
    }
  };
}
var e3, s, EXPLICIT_ABORT_TOKEN2, UNINITIALIZED;
var init_index_node30 = __esm({
  "node_modules/@solana/subscribable/dist/index.node.mjs"() {
    "use strict";
    init_index_node();
    e3 = class extends globalThis.AbortController {
      constructor(...t) {
        super(...t), setMaxListeners2(Number.MAX_SAFE_INTEGER, this.signal);
      }
    };
    s = class extends globalThis.EventTarget {
      constructor(...t) {
        super(...t), setMaxListeners2(Number.MAX_SAFE_INTEGER, this);
      }
    };
    UNINITIALIZED = /* @__PURE__ */ Symbol();
  }
});

// node_modules/@solana/rpc-subscriptions-spec/dist/index.node.mjs
import { setMaxListeners as setMaxListeners3 } from "events";
function createSubscriptionRpc(rpcConfig) {
  return new Proxy(rpcConfig.api, {
    defineProperty() {
      return false;
    },
    deleteProperty() {
      return false;
    },
    get(target, p, receiver) {
      if (p === "then") {
        return void 0;
      }
      return function(...rawParams) {
        const notificationName = p.toString();
        const createRpcSubscriptionPlan = Reflect.get(target, notificationName, receiver);
        if (!createRpcSubscriptionPlan) {
          throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, {
            notificationName
          });
        }
        const subscriptionPlan = createRpcSubscriptionPlan(...rawParams);
        return createPendingRpcSubscription(rpcConfig.transport, subscriptionPlan);
      };
    }
  });
}
function createPendingRpcSubscription(transport, subscriptionsPlan) {
  return {
    async subscribe({ abortSignal }) {
      const notificationsDataPublisher = await transport({
        signal: abortSignal,
        ...subscriptionsPlan
      });
      return createAsyncIterableFromDataPublisher({
        abortSignal,
        dataChannelName: "notification",
        dataPublisher: notificationsDataPublisher,
        errorChannelName: "error"
      });
    }
  };
}
function createRpcSubscriptionsApi(config) {
  return new Proxy({}, {
    defineProperty() {
      return false;
    },
    deleteProperty() {
      return false;
    },
    get(...args) {
      const [_, p] = args;
      const methodName = p.toString();
      return function(...params) {
        const rawRequest = { methodName, params };
        const request = config.requestTransformer ? config.requestTransformer(rawRequest) : rawRequest;
        return {
          execute(planConfig) {
            return config.planExecutor({ ...planConfig, request });
          },
          request
        };
      };
    }
  });
}
function transformChannelInboundMessages(channel, transform2) {
  return Object.freeze({
    ...channel,
    on(type, subscriber, options) {
      if (type !== "message") {
        return channel.on(
          type,
          subscriber,
          options
        );
      }
      return channel.on(
        "message",
        (message) => subscriber(transform2(message)),
        options
      );
    }
  });
}
function transformChannelOutboundMessages(channel, transform2) {
  return Object.freeze({
    ...channel,
    send: (message) => channel.send(transform2(message))
  });
}
function decrementSubscriberCountAndReturnNewCount(channel, subscriptionId) {
  return augmentSubscriberCountAndReturnNewCount(-1, channel, subscriptionId);
}
function incrementSubscriberCount(channel, subscriptionId) {
  augmentSubscriberCountAndReturnNewCount(1, channel, subscriptionId);
}
function getSubscriberCountBySubscriptionIdForChannel(channel) {
  let subscriberCountBySubscriptionId = subscriberCountBySubscriptionIdByChannel.get(channel);
  if (!subscriberCountBySubscriptionId) {
    subscriberCountBySubscriptionIdByChannel.set(channel, subscriberCountBySubscriptionId = {});
  }
  return subscriberCountBySubscriptionId;
}
function augmentSubscriberCountAndReturnNewCount(amount, channel, subscriptionId) {
  if (subscriptionId === void 0) {
    return;
  }
  const subscriberCountBySubscriptionId = getSubscriberCountBySubscriptionIdForChannel(channel);
  if (!subscriberCountBySubscriptionId[subscriptionId] && amount > 0) {
    subscriberCountBySubscriptionId[subscriptionId] = 0;
  }
  const newCount = amount + subscriberCountBySubscriptionId[subscriptionId];
  if (newCount <= 0) {
    delete subscriberCountBySubscriptionId[subscriptionId];
  } else {
    subscriberCountBySubscriptionId[subscriptionId] = newCount;
  }
  return newCount;
}
function getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(channel, subscribeRequest, responseTransformer) {
  let publisherByResponseTransformer = cache.get(channel);
  if (!publisherByResponseTransformer) {
    cache.set(channel, publisherByResponseTransformer = /* @__PURE__ */ new WeakMap());
  }
  const responseTransformerKey = responseTransformer ?? channel;
  let publisher = publisherByResponseTransformer.get(responseTransformerKey);
  if (!publisher) {
    publisherByResponseTransformer.set(
      responseTransformerKey,
      publisher = demultiplexDataPublisher(channel, "message", (rawMessage) => {
        const message = rawMessage;
        if (!("method" in message)) {
          return;
        }
        const transformedNotification = responseTransformer ? responseTransformer(message.params.result, subscribeRequest) : message.params.result;
        return [`notification:${message.params.subscription}`, transformedNotification];
      })
    );
  }
  return publisher;
}
async function executeRpcPubSubSubscriptionPlan({
  channel,
  responseTransformer,
  signal,
  subscribeRequest,
  unsubscribeMethodName
}) {
  let subscriptionId;
  channel.on(
    "error",
    () => {
      subscriptionId = void 0;
      subscriberCountBySubscriptionIdByChannel.delete(channel);
    },
    { signal }
  );
  const abortPromise = new Promise((_, reject) => {
    function handleAbort() {
      if (decrementSubscriberCountAndReturnNewCount(channel, subscriptionId) === 0) {
        const unsubscribePayload = createRpcMessage({
          methodName: unsubscribeMethodName,
          params: [subscriptionId]
        });
        subscriptionId = void 0;
        channel.send(unsubscribePayload).catch(() => {
        });
      }
      reject(this.reason);
    }
    if (signal.aborted) {
      handleAbort.call(signal);
    } else {
      signal.addEventListener("abort", handleAbort);
    }
  });
  const subscribePayload = createRpcMessage(subscribeRequest);
  await channel.send(subscribePayload);
  const subscriptionIdPromise = new Promise((resolve, reject) => {
    const abortController = new e4();
    signal.addEventListener("abort", abortController.abort.bind(abortController));
    const options = { signal: abortController.signal };
    channel.on(
      "error",
      (err) => {
        abortController.abort();
        reject(err);
      },
      options
    );
    channel.on(
      "message",
      (message) => {
        if (message && typeof message === "object" && "id" in message && message.id === subscribePayload.id) {
          abortController.abort();
          if ("error" in message) {
            reject(getSolanaErrorFromJsonRpcError(message.error));
          } else {
            resolve(message.result);
          }
        }
      },
      options
    );
  });
  subscriptionId = await safeRace([abortPromise, subscriptionIdPromise]);
  if (subscriptionId == null) {
    throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID);
  }
  incrementSubscriberCount(channel, subscriptionId);
  const notificationPublisher = getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(
    channel,
    subscribeRequest,
    responseTransformer
  );
  const notificationKey = `notification:${subscriptionId}`;
  return {
    on(type, listener, options) {
      switch (type) {
        case "notification":
          return notificationPublisher.on(
            notificationKey,
            listener,
            options
          );
        case "error":
          return channel.on(
            "error",
            listener,
            options
          );
        default:
          throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED, {
            channelName: type,
            supportedChannelNames: ["notification", "error"]
          });
      }
    }
  };
}
var e4, subscriberCountBySubscriptionIdByChannel, cache;
var init_index_node31 = __esm({
  "node_modules/@solana/rpc-subscriptions-spec/dist/index.node.mjs"() {
    "use strict";
    init_index_node();
    init_index_node30();
    init_index_node17();
    init_index_node22();
    e4 = class extends globalThis.AbortController {
      constructor(...t) {
        super(...t), setMaxListeners3(Number.MAX_SAFE_INTEGER, this.signal);
      }
    };
    subscriberCountBySubscriptionIdByChannel = /* @__PURE__ */ new WeakMap();
    cache = /* @__PURE__ */ new WeakMap();
  }
});

// node_modules/@solana/rpc-subscriptions-api/dist/index.node.mjs
function createSolanaRpcSubscriptionsApi_INTERNAL(config) {
  const requestTransformer = getDefaultRequestTransformerForSolanaRpc(config);
  const responseTransformer = getDefaultResponseTransformerForSolanaRpcSubscriptions({
    allowedNumericKeyPaths: getAllowedNumericKeypaths2()
  });
  return createRpcSubscriptionsApi({
    planExecutor({ request, ...rest }) {
      return executeRpcPubSubSubscriptionPlan({
        ...rest,
        responseTransformer,
        subscribeRequest: { ...request, methodName: request.methodName.replace(/Notifications$/, "Subscribe") },
        unsubscribeMethodName: request.methodName.replace(/Notifications$/, "Unsubscribe")
      });
    },
    requestTransformer
  });
}
function createSolanaRpcSubscriptionsApi(config) {
  return createSolanaRpcSubscriptionsApi_INTERNAL(config);
}
function createSolanaRpcSubscriptionsApi_UNSTABLE(config) {
  return createSolanaRpcSubscriptionsApi_INTERNAL(
    config
  );
}
function getAllowedNumericKeypaths2() {
  if (!memoizedKeypaths2) {
    memoizedKeypaths2 = {
      accountNotifications: jsonParsedAccountsConfigs.map((c) => ["value", ...c]),
      blockNotifications: [
        [
          "value",
          "block",
          "transactions",
          KEYPATH_WILDCARD,
          "meta",
          "preTokenBalances",
          KEYPATH_WILDCARD,
          "accountIndex"
        ],
        [
          "value",
          "block",
          "transactions",
          KEYPATH_WILDCARD,
          "meta",
          "preTokenBalances",
          KEYPATH_WILDCARD,
          "uiTokenAmount",
          "decimals"
        ],
        [
          "value",
          "block",
          "transactions",
          KEYPATH_WILDCARD,
          "meta",
          "postTokenBalances",
          KEYPATH_WILDCARD,
          "accountIndex"
        ],
        [
          "value",
          "block",
          "transactions",
          KEYPATH_WILDCARD,
          "meta",
          "postTokenBalances",
          KEYPATH_WILDCARD,
          "uiTokenAmount",
          "decimals"
        ],
        ["value", "block", "transactions", KEYPATH_WILDCARD, "meta", "rewards", KEYPATH_WILDCARD, "commission"],
        [
          "value",
          "block",
          "transactions",
          KEYPATH_WILDCARD,
          "meta",
          "innerInstructions",
          KEYPATH_WILDCARD,
          "index"
        ],
        [
          "value",
          "block",
          "transactions",
          KEYPATH_WILDCARD,
          "meta",
          "innerInstructions",
          KEYPATH_WILDCARD,
          "instructions",
          KEYPATH_WILDCARD,
          "programIdIndex"
        ],
        [
          "value",
          "block",
          "transactions",
          KEYPATH_WILDCARD,
          "meta",
          "innerInstructions",
          KEYPATH_WILDCARD,
          "instructions",
          KEYPATH_WILDCARD,
          "accounts",
          KEYPATH_WILDCARD
        ],
        [
          "value",
          "block",
          "transactions",
          KEYPATH_WILDCARD,
          "transaction",
          "message",
          "addressTableLookups",
          KEYPATH_WILDCARD,
          "writableIndexes",
          KEYPATH_WILDCARD
        ],
        [
          "value",
          "block",
          "transactions",
          KEYPATH_WILDCARD,
          "transaction",
          "message",
          "addressTableLookups",
          KEYPATH_WILDCARD,
          "readonlyIndexes",
          KEYPATH_WILDCARD
        ],
        [
          "value",
          "block",
          "transactions",
          KEYPATH_WILDCARD,
          "transaction",
          "message",
          "instructions",
          KEYPATH_WILDCARD,
          "programIdIndex"
        ],
        [
          "value",
          "block",
          "transactions",
          KEYPATH_WILDCARD,
          "transaction",
          "message",
          "instructions",
          KEYPATH_WILDCARD,
          "accounts",
          KEYPATH_WILDCARD
        ],
        [
          "value",
          "block",
          "transactions",
          KEYPATH_WILDCARD,
          "transaction",
          "message",
          "header",
          "numReadonlySignedAccounts"
        ],
        [
          "value",
          "block",
          "transactions",
          KEYPATH_WILDCARD,
          "transaction",
          "message",
          "header",
          "numReadonlyUnsignedAccounts"
        ],
        [
          "value",
          "block",
          "transactions",
          KEYPATH_WILDCARD,
          "transaction",
          "message",
          "header",
          "numRequiredSignatures"
        ],
        ["value", "block", "rewards", KEYPATH_WILDCARD, "commission"]
      ],
      programNotifications: jsonParsedAccountsConfigs.flatMap((c) => [
        ["value", KEYPATH_WILDCARD, "account", ...c],
        [KEYPATH_WILDCARD, "account", ...c]
      ])
    };
  }
  return memoizedKeypaths2;
}
var memoizedKeypaths2;
var init_index_node32 = __esm({
  "node_modules/@solana/rpc-subscriptions-api/dist/index.node.mjs"() {
    "use strict";
    init_index_node31();
    init_index_node24();
  }
});

// node_modules/ws/lib/constants.js
var require_constants = __commonJS({
  "node_modules/ws/lib/constants.js"(exports, module) {
    "use strict";
    var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
    var hasBlob = typeof Blob !== "undefined";
    if (hasBlob) BINARY_TYPES.push("blob");
    module.exports = {
      BINARY_TYPES,
      CLOSE_TIMEOUT: 3e4,
      EMPTY_BUFFER: Buffer.alloc(0),
      GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
      hasBlob,
      kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
      kListener: /* @__PURE__ */ Symbol("kListener"),
      kStatusCode: /* @__PURE__ */ Symbol("status-code"),
      kWebSocket: /* @__PURE__ */ Symbol("websocket"),
      NOOP: () => {
      }
    };
  }
});

// node_modules/ws/lib/buffer-util.js
var require_buffer_util = __commonJS({
  "node_modules/ws/lib/buffer-util.js"(exports, module) {
    "use strict";
    var { EMPTY_BUFFER } = require_constants();
    var FastBuffer = Buffer[Symbol.species];
    function concat3(list, totalLength) {
      if (list.length === 0) return EMPTY_BUFFER;
      if (list.length === 1) return list[0];
      const target = Buffer.allocUnsafe(totalLength);
      let offset = 0;
      for (let i = 0; i < list.length; i++) {
        const buf = list[i];
        target.set(buf, offset);
        offset += buf.length;
      }
      if (offset < totalLength) {
        return new FastBuffer(target.buffer, target.byteOffset, offset);
      }
      return target;
    }
    function _mask(source, mask, output, offset, length) {
      for (let i = 0; i < length; i++) {
        output[offset + i] = source[i] ^ mask[i & 3];
      }
    }
    function _unmask(buffer2, mask) {
      for (let i = 0; i < buffer2.length; i++) {
        buffer2[i] ^= mask[i & 3];
      }
    }
    function toArrayBuffer2(buf) {
      if (buf.length === buf.buffer.byteLength) {
        return buf.buffer;
      }
      return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
    }
    function toBuffer(data) {
      toBuffer.readOnly = true;
      if (Buffer.isBuffer(data)) return data;
      let buf;
      if (data instanceof ArrayBuffer) {
        buf = new FastBuffer(data);
      } else if (ArrayBuffer.isView(data)) {
        buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
      } else {
        buf = Buffer.from(data);
        toBuffer.readOnly = false;
      }
      return buf;
    }
    module.exports = {
      concat: concat3,
      mask: _mask,
      toArrayBuffer: toArrayBuffer2,
      toBuffer,
      unmask: _unmask
    };
    if (!process.env.WS_NO_BUFFER_UTIL) {
      try {
        const bufferUtil = __require("bufferutil");
        module.exports.mask = function(source, mask, output, offset, length) {
          if (length < 48) _mask(source, mask, output, offset, length);
          else bufferUtil.mask(source, mask, output, offset, length);
        };
        module.exports.unmask = function(buffer2, mask) {
          if (buffer2.length < 32) _unmask(buffer2, mask);
          else bufferUtil.unmask(buffer2, mask);
        };
      } catch (e7) {
      }
    }
  }
});

// node_modules/ws/lib/limiter.js
var require_limiter = __commonJS({
  "node_modules/ws/lib/limiter.js"(exports, module) {
    "use strict";
    var kDone = /* @__PURE__ */ Symbol("kDone");
    var kRun = /* @__PURE__ */ Symbol("kRun");
    var Limiter = class {
      /**
       * Creates a new `Limiter`.
       *
       * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
       *     to run concurrently
       */
      constructor(concurrency) {
        this[kDone] = () => {
          this.pending--;
          this[kRun]();
        };
        this.concurrency = concurrency || Infinity;
        this.jobs = [];
        this.pending = 0;
      }
      /**
       * Adds a job to the queue.
       *
       * @param {Function} job The job to run
       * @public
       */
      add(job) {
        this.jobs.push(job);
        this[kRun]();
      }
      /**
       * Removes a job from the queue and runs it if possible.
       *
       * @private
       */
      [kRun]() {
        if (this.pending === this.concurrency) return;
        if (this.jobs.length) {
          const job = this.jobs.shift();
          this.pending++;
          job(this[kDone]);
        }
      }
    };
    module.exports = Limiter;
  }
});

// node_modules/ws/lib/permessage-deflate.js
var require_permessage_deflate = __commonJS({
  "node_modules/ws/lib/permessage-deflate.js"(exports, module) {
    "use strict";
    var zlib = __require("zlib");
    var bufferUtil = require_buffer_util();
    var Limiter = require_limiter();
    var { kStatusCode } = require_constants();
    var FastBuffer = Buffer[Symbol.species];
    var TRAILER = Buffer.from([0, 0, 255, 255]);
    var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
    var kTotalLength = /* @__PURE__ */ Symbol("total-length");
    var kCallback = /* @__PURE__ */ Symbol("callback");
    var kBuffers = /* @__PURE__ */ Symbol("buffers");
    var kError = /* @__PURE__ */ Symbol("error");
    var zlibLimiter;
    var PerMessageDeflate2 = class {
      /**
       * Creates a PerMessageDeflate instance.
       *
       * @param {Object} [options] Configuration options
       * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
       *     for, or request, a custom client window size
       * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
       *     acknowledge disabling of client context takeover
       * @param {Number} [options.concurrencyLimit=10] The number of concurrent
       *     calls to zlib
       * @param {Boolean} [options.isServer=false] Create the instance in either
       *     server or client mode
       * @param {Number} [options.maxPayload=0] The maximum allowed message length
       * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
       *     use of a custom server window size
       * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
       *     disabling of server context takeover
       * @param {Number} [options.threshold=1024] Size (in bytes) below which
       *     messages should not be compressed if context takeover is disabled
       * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
       *     deflate
       * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
       *     inflate
       */
      constructor(options) {
        this._options = options || {};
        this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
        this._maxPayload = this._options.maxPayload | 0;
        this._isServer = !!this._options.isServer;
        this._deflate = null;
        this._inflate = null;
        this.params = null;
        if (!zlibLimiter) {
          const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
          zlibLimiter = new Limiter(concurrency);
        }
      }
      /**
       * @type {String}
       */
      static get extensionName() {
        return "permessage-deflate";
      }
      /**
       * Create an extension negotiation offer.
       *
       * @return {Object} Extension parameters
       * @public
       */
      offer() {
        const params = {};
        if (this._options.serverNoContextTakeover) {
          params.server_no_context_takeover = true;
        }
        if (this._options.clientNoContextTakeover) {
          params.client_no_context_takeover = true;
        }
        if (this._options.serverMaxWindowBits) {
          params.server_max_window_bits = this._options.serverMaxWindowBits;
        }
        if (this._options.clientMaxWindowBits) {
          params.client_max_window_bits = this._options.clientMaxWindowBits;
        } else if (this._options.clientMaxWindowBits == null) {
          params.client_max_window_bits = true;
        }
        return params;
      }
      /**
       * Accept an extension negotiation offer/response.
       *
       * @param {Array} configurations The extension negotiation offers/reponse
       * @return {Object} Accepted configuration
       * @public
       */
      accept(configurations) {
        configurations = this.normalizeParams(configurations);
        this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
        return this.params;
      }
      /**
       * Releases all resources used by the extension.
       *
       * @public
       */
      cleanup() {
        if (this._inflate) {
          this._inflate.close();
          this._inflate = null;
        }
        if (this._deflate) {
          const callback = this._deflate[kCallback];
          this._deflate.close();
          this._deflate = null;
          if (callback) {
            callback(
              new Error(
                "The deflate stream was closed while data was being processed"
              )
            );
          }
        }
      }
      /**
       *  Accept an extension negotiation offer.
       *
       * @param {Array} offers The extension negotiation offers
       * @return {Object} Accepted configuration
       * @private
       */
      acceptAsServer(offers) {
        const opts = this._options;
        const accepted = offers.find((params) => {
          if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
            return false;
          }
          return true;
        });
        if (!accepted) {
          throw new Error("None of the extension offers can be accepted");
        }
        if (opts.serverNoContextTakeover) {
          accepted.server_no_context_takeover = true;
        }
        if (opts.clientNoContextTakeover) {
          accepted.client_no_context_takeover = true;
        }
        if (typeof opts.serverMaxWindowBits === "number") {
          accepted.server_max_window_bits = opts.serverMaxWindowBits;
        }
        if (typeof opts.clientMaxWindowBits === "number") {
          accepted.client_max_window_bits = opts.clientMaxWindowBits;
        } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
          delete accepted.client_max_window_bits;
        }
        return accepted;
      }
      /**
       * Accept the extension negotiation response.
       *
       * @param {Array} response The extension negotiation response
       * @return {Object} Accepted configuration
       * @private
       */
      acceptAsClient(response) {
        const params = response[0];
        if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
          throw new Error('Unexpected parameter "client_no_context_takeover"');
        }
        if (!params.client_max_window_bits) {
          if (typeof this._options.clientMaxWindowBits === "number") {
            params.client_max_window_bits = this._options.clientMaxWindowBits;
          }
        } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
          throw new Error(
            'Unexpected or invalid parameter "client_max_window_bits"'
          );
        }
        return params;
      }
      /**
       * Normalize parameters.
       *
       * @param {Array} configurations The extension negotiation offers/reponse
       * @return {Array} The offers/response with normalized parameters
       * @private
       */
      normalizeParams(configurations) {
        configurations.forEach((params) => {
          Object.keys(params).forEach((key) => {
            let value = params[key];
            if (value.length > 1) {
              throw new Error(`Parameter "${key}" must have only a single value`);
            }
            value = value[0];
            if (key === "client_max_window_bits") {
              if (value !== true) {
                const num2 = +value;
                if (!Number.isInteger(num2) || num2 < 8 || num2 > 15) {
                  throw new TypeError(
                    `Invalid value for parameter "${key}": ${value}`
                  );
                }
                value = num2;
              } else if (!this._isServer) {
                throw new TypeError(
                  `Invalid value for parameter "${key}": ${value}`
                );
              }
            } else if (key === "server_max_window_bits") {
              const num2 = +value;
              if (!Number.isInteger(num2) || num2 < 8 || num2 > 15) {
                throw new TypeError(
                  `Invalid value for parameter "${key}": ${value}`
                );
              }
              value = num2;
            } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
              if (value !== true) {
                throw new TypeError(
                  `Invalid value for parameter "${key}": ${value}`
                );
              }
            } else {
              throw new Error(`Unknown parameter "${key}"`);
            }
            params[key] = value;
          });
        });
        return configurations;
      }
      /**
       * Decompress data. Concurrency limited.
       *
       * @param {Buffer} data Compressed data
       * @param {Boolean} fin Specifies whether or not this is the last fragment
       * @param {Function} callback Callback
       * @public
       */
      decompress(data, fin, callback) {
        zlibLimiter.add((done) => {
          this._decompress(data, fin, (err, result) => {
            done();
            callback(err, result);
          });
        });
      }
      /**
       * Compress data. Concurrency limited.
       *
       * @param {(Buffer|String)} data Data to compress
       * @param {Boolean} fin Specifies whether or not this is the last fragment
       * @param {Function} callback Callback
       * @public
       */
      compress(data, fin, callback) {
        zlibLimiter.add((done) => {
          this._compress(data, fin, (err, result) => {
            done();
            callback(err, result);
          });
        });
      }
      /**
       * Decompress data.
       *
       * @param {Buffer} data Compressed data
       * @param {Boolean} fin Specifies whether or not this is the last fragment
       * @param {Function} callback Callback
       * @private
       */
      _decompress(data, fin, callback) {
        const endpoint = this._isServer ? "client" : "server";
        if (!this._inflate) {
          const key = `${endpoint}_max_window_bits`;
          const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
          this._inflate = zlib.createInflateRaw({
            ...this._options.zlibInflateOptions,
            windowBits
          });
          this._inflate[kPerMessageDeflate] = this;
          this._inflate[kTotalLength] = 0;
          this._inflate[kBuffers] = [];
          this._inflate.on("error", inflateOnError);
          this._inflate.on("data", inflateOnData);
        }
        this._inflate[kCallback] = callback;
        this._inflate.write(data);
        if (fin) this._inflate.write(TRAILER);
        this._inflate.flush(() => {
          const err = this._inflate[kError];
          if (err) {
            this._inflate.close();
            this._inflate = null;
            callback(err);
            return;
          }
          const data2 = bufferUtil.concat(
            this._inflate[kBuffers],
            this._inflate[kTotalLength]
          );
          if (this._inflate._readableState.endEmitted) {
            this._inflate.close();
            this._inflate = null;
          } else {
            this._inflate[kTotalLength] = 0;
            this._inflate[kBuffers] = [];
            if (fin && this.params[`${endpoint}_no_context_takeover`]) {
              this._inflate.reset();
            }
          }
          callback(null, data2);
        });
      }
      /**
       * Compress data.
       *
       * @param {(Buffer|String)} data Data to compress
       * @param {Boolean} fin Specifies whether or not this is the last fragment
       * @param {Function} callback Callback
       * @private
       */
      _compress(data, fin, callback) {
        const endpoint = this._isServer ? "server" : "client";
        if (!this._deflate) {
          const key = `${endpoint}_max_window_bits`;
          const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
          this._deflate = zlib.createDeflateRaw({
            ...this._options.zlibDeflateOptions,
            windowBits
          });
          this._deflate[kTotalLength] = 0;
          this._deflate[kBuffers] = [];
          this._deflate.on("data", deflateOnData);
        }
        this._deflate[kCallback] = callback;
        this._deflate.write(data);
        this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
          if (!this._deflate) {
            return;
          }
          let data2 = bufferUtil.concat(
            this._deflate[kBuffers],
            this._deflate[kTotalLength]
          );
          if (fin) {
            data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
          }
          this._deflate[kCallback] = null;
          this._deflate[kTotalLength] = 0;
          this._deflate[kBuffers] = [];
          if (fin && this.params[`${endpoint}_no_context_takeover`]) {
            this._deflate.reset();
          }
          callback(null, data2);
        });
      }
    };
    module.exports = PerMessageDeflate2;
    function deflateOnData(chunk) {
      this[kBuffers].push(chunk);
      this[kTotalLength] += chunk.length;
    }
    function inflateOnData(chunk) {
      this[kTotalLength] += chunk.length;
      if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
        this[kBuffers].push(chunk);
        return;
      }
      this[kError] = new RangeError("Max payload size exceeded");
      this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
      this[kError][kStatusCode] = 1009;
      this.removeListener("data", inflateOnData);
      this.reset();
    }
    function inflateOnError(err) {
      this[kPerMessageDeflate]._inflate = null;
      if (this[kError]) {
        this[kCallback](this[kError]);
        return;
      }
      err[kStatusCode] = 1007;
      this[kCallback](err);
    }
  }
});

// node_modules/ws/lib/validation.js
var require_validation = __commonJS({
  "node_modules/ws/lib/validation.js"(exports, module) {
    "use strict";
    var { isUtf8 } = __require("buffer");
    var { hasBlob } = require_constants();
    var tokenChars = [
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 0 - 15
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 16 - 31
      0,
      1,
      0,
      1,
      1,
      1,
      1,
      1,
      0,
      0,
      1,
      1,
      0,
      1,
      1,
      0,
      // 32 - 47
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      0,
      0,
      0,
      0,
      0,
      0,
      // 48 - 63
      0,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      // 64 - 79
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      0,
      0,
      0,
      1,
      1,
      // 80 - 95
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      // 96 - 111
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      0,
      1,
      0,
      1,
      0
      // 112 - 127
    ];
    function isValidStatusCode(code) {
      return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
    }
    function _isValidUTF8(buf) {
      const len = buf.length;
      let i = 0;
      while (i < len) {
        if ((buf[i] & 128) === 0) {
          i++;
        } else if ((buf[i] & 224) === 192) {
          if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
            return false;
          }
          i += 2;
        } else if ((buf[i] & 240) === 224) {
          if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
          buf[i] === 237 && (buf[i + 1] & 224) === 160) {
            return false;
          }
          i += 3;
        } else if ((buf[i] & 248) === 240) {
          if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
          buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
            return false;
          }
          i += 4;
        } else {
          return false;
        }
      }
      return true;
    }
    function isBlob(value) {
      return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
    }
    module.exports = {
      isBlob,
      isValidStatusCode,
      isValidUTF8: _isValidUTF8,
      tokenChars
    };
    if (isUtf8) {
      module.exports.isValidUTF8 = function(buf) {
        return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
      };
    } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
      try {
        const isValidUTF8 = __require("utf-8-validate");
        module.exports.isValidUTF8 = function(buf) {
          return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
        };
      } catch (e7) {
      }
    }
  }
});

// node_modules/ws/lib/receiver.js
var require_receiver = __commonJS({
  "node_modules/ws/lib/receiver.js"(exports, module) {
    "use strict";
    var { Writable } = __require("stream");
    var PerMessageDeflate2 = require_permessage_deflate();
    var {
      BINARY_TYPES,
      EMPTY_BUFFER,
      kStatusCode,
      kWebSocket
    } = require_constants();
    var { concat: concat3, toArrayBuffer: toArrayBuffer2, unmask } = require_buffer_util();
    var { isValidStatusCode, isValidUTF8 } = require_validation();
    var FastBuffer = Buffer[Symbol.species];
    var GET_INFO = 0;
    var GET_PAYLOAD_LENGTH_16 = 1;
    var GET_PAYLOAD_LENGTH_64 = 2;
    var GET_MASK = 3;
    var GET_DATA = 4;
    var INFLATING = 5;
    var DEFER_EVENT = 6;
    var Receiver2 = class extends Writable {
      /**
       * Creates a Receiver instance.
       *
       * @param {Object} [options] Options object
       * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
       *     any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
       *     multiple times in the same tick
       * @param {String} [options.binaryType=nodebuffer] The type for binary data
       * @param {Object} [options.extensions] An object containing the negotiated
       *     extensions
       * @param {Boolean} [options.isServer=false] Specifies whether to operate in
       *     client or server mode
       * @param {Number} [options.maxPayload=0] The maximum allowed message length
       * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
       *     not to skip UTF-8 validation for text and close messages
       */
      constructor(options = {}) {
        super();
        this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
        this._binaryType = options.binaryType || BINARY_TYPES[0];
        this._extensions = options.extensions || {};
        this._isServer = !!options.isServer;
        this._maxPayload = options.maxPayload | 0;
        this._skipUTF8Validation = !!options.skipUTF8Validation;
        this[kWebSocket] = void 0;
        this._bufferedBytes = 0;
        this._buffers = [];
        this._compressed = false;
        this._payloadLength = 0;
        this._mask = void 0;
        this._fragmented = 0;
        this._masked = false;
        this._fin = false;
        this._opcode = 0;
        this._totalPayloadLength = 0;
        this._messageLength = 0;
        this._fragments = [];
        this._errored = false;
        this._loop = false;
        this._state = GET_INFO;
      }
      /**
       * Implements `Writable.prototype._write()`.
       *
       * @param {Buffer} chunk The chunk of data to write
       * @param {String} encoding The character encoding of `chunk`
       * @param {Function} cb Callback
       * @private
       */
      _write(chunk, encoding, cb) {
        if (this._opcode === 8 && this._state == GET_INFO) return cb();
        this._bufferedBytes += chunk.length;
        this._buffers.push(chunk);
        this.startLoop(cb);
      }
      /**
       * Consumes `n` bytes from the buffered data.
       *
       * @param {Number} n The number of bytes to consume
       * @return {Buffer} The consumed bytes
       * @private
       */
      consume(n) {
        this._bufferedBytes -= n;
        if (n === this._buffers[0].length) return this._buffers.shift();
        if (n < this._buffers[0].length) {
          const buf = this._buffers[0];
          this._buffers[0] = new FastBuffer(
            buf.buffer,
            buf.byteOffset + n,
            buf.length - n
          );
          return new FastBuffer(buf.buffer, buf.byteOffset, n);
        }
        const dst = Buffer.allocUnsafe(n);
        do {
          const buf = this._buffers[0];
          const offset = dst.length - n;
          if (n >= buf.length) {
            dst.set(this._buffers.shift(), offset);
          } else {
            dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
            this._buffers[0] = new FastBuffer(
              buf.buffer,
              buf.byteOffset + n,
              buf.length - n
            );
          }
          n -= buf.length;
        } while (n > 0);
        return dst;
      }
      /**
       * Starts the parsing loop.
       *
       * @param {Function} cb Callback
       * @private
       */
      startLoop(cb) {
        this._loop = true;
        do {
          switch (this._state) {
            case GET_INFO:
              this.getInfo(cb);
              break;
            case GET_PAYLOAD_LENGTH_16:
              this.getPayloadLength16(cb);
              break;
            case GET_PAYLOAD_LENGTH_64:
              this.getPayloadLength64(cb);
              break;
            case GET_MASK:
              this.getMask();
              break;
            case GET_DATA:
              this.getData(cb);
              break;
            case INFLATING:
            case DEFER_EVENT:
              this._loop = false;
              return;
          }
        } while (this._loop);
        if (!this._errored) cb();
      }
      /**
       * Reads the first two bytes of a frame.
       *
       * @param {Function} cb Callback
       * @private
       */
      getInfo(cb) {
        if (this._bufferedBytes < 2) {
          this._loop = false;
          return;
        }
        const buf = this.consume(2);
        if ((buf[0] & 48) !== 0) {
          const error = this.createError(
            RangeError,
            "RSV2 and RSV3 must be clear",
            true,
            1002,
            "WS_ERR_UNEXPECTED_RSV_2_3"
          );
          cb(error);
          return;
        }
        const compressed = (buf[0] & 64) === 64;
        if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
          const error = this.createError(
            RangeError,
            "RSV1 must be clear",
            true,
            1002,
            "WS_ERR_UNEXPECTED_RSV_1"
          );
          cb(error);
          return;
        }
        this._fin = (buf[0] & 128) === 128;
        this._opcode = buf[0] & 15;
        this._payloadLength = buf[1] & 127;
        if (this._opcode === 0) {
          if (compressed) {
            const error = this.createError(
              RangeError,
              "RSV1 must be clear",
              true,
              1002,
              "WS_ERR_UNEXPECTED_RSV_1"
            );
            cb(error);
            return;
          }
          if (!this._fragmented) {
            const error = this.createError(
              RangeError,
              "invalid opcode 0",
              true,
              1002,
              "WS_ERR_INVALID_OPCODE"
            );
            cb(error);
            return;
          }
          this._opcode = this._fragmented;
        } else if (this._opcode === 1 || this._opcode === 2) {
          if (this._fragmented) {
            const error = this.createError(
              RangeError,
              `invalid opcode ${this._opcode}`,
              true,
              1002,
              "WS_ERR_INVALID_OPCODE"
            );
            cb(error);
            return;
          }
          this._compressed = compressed;
        } else if (this._opcode > 7 && this._opcode < 11) {
          if (!this._fin) {
            const error = this.createError(
              RangeError,
              "FIN must be set",
              true,
              1002,
              "WS_ERR_EXPECTED_FIN"
            );
            cb(error);
            return;
          }
          if (compressed) {
            const error = this.createError(
              RangeError,
              "RSV1 must be clear",
              true,
              1002,
              "WS_ERR_UNEXPECTED_RSV_1"
            );
            cb(error);
            return;
          }
          if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
            const error = this.createError(
              RangeError,
              `invalid payload length ${this._payloadLength}`,
              true,
              1002,
              "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
            );
            cb(error);
            return;
          }
        } else {
          const error = this.createError(
            RangeError,
            `invalid opcode ${this._opcode}`,
            true,
            1002,
            "WS_ERR_INVALID_OPCODE"
          );
          cb(error);
          return;
        }
        if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
        this._masked = (buf[1] & 128) === 128;
        if (this._isServer) {
          if (!this._masked) {
            const error = this.createError(
              RangeError,
              "MASK must be set",
              true,
              1002,
              "WS_ERR_EXPECTED_MASK"
            );
            cb(error);
            return;
          }
        } else if (this._masked) {
          const error = this.createError(
            RangeError,
            "MASK must be clear",
            true,
            1002,
            "WS_ERR_UNEXPECTED_MASK"
          );
          cb(error);
          return;
        }
        if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
        else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
        else this.haveLength(cb);
      }
      /**
       * Gets extended payload length (7+16).
       *
       * @param {Function} cb Callback
       * @private
       */
      getPayloadLength16(cb) {
        if (this._bufferedBytes < 2) {
          this._loop = false;
          return;
        }
        this._payloadLength = this.consume(2).readUInt16BE(0);
        this.haveLength(cb);
      }
      /**
       * Gets extended payload length (7+64).
       *
       * @param {Function} cb Callback
       * @private
       */
      getPayloadLength64(cb) {
        if (this._bufferedBytes < 8) {
          this._loop = false;
          return;
        }
        const buf = this.consume(8);
        const num2 = buf.readUInt32BE(0);
        if (num2 > Math.pow(2, 53 - 32) - 1) {
          const error = this.createError(
            RangeError,
            "Unsupported WebSocket frame: payload length > 2^53 - 1",
            false,
            1009,
            "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
          );
          cb(error);
          return;
        }
        this._payloadLength = num2 * Math.pow(2, 32) + buf.readUInt32BE(4);
        this.haveLength(cb);
      }
      /**
       * Payload length has been read.
       *
       * @param {Function} cb Callback
       * @private
       */
      haveLength(cb) {
        if (this._payloadLength && this._opcode < 8) {
          this._totalPayloadLength += this._payloadLength;
          if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
            const error = this.createError(
              RangeError,
              "Max payload size exceeded",
              false,
              1009,
              "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
            );
            cb(error);
            return;
          }
        }
        if (this._masked) this._state = GET_MASK;
        else this._state = GET_DATA;
      }
      /**
       * Reads mask bytes.
       *
       * @private
       */
      getMask() {
        if (this._bufferedBytes < 4) {
          this._loop = false;
          return;
        }
        this._mask = this.consume(4);
        this._state = GET_DATA;
      }
      /**
       * Reads data bytes.
       *
       * @param {Function} cb Callback
       * @private
       */
      getData(cb) {
        let data = EMPTY_BUFFER;
        if (this._payloadLength) {
          if (this._bufferedBytes < this._payloadLength) {
            this._loop = false;
            return;
          }
          data = this.consume(this._payloadLength);
          if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
            unmask(data, this._mask);
          }
        }
        if (this._opcode > 7) {
          this.controlMessage(data, cb);
          return;
        }
        if (this._compressed) {
          this._state = INFLATING;
          this.decompress(data, cb);
          return;
        }
        if (data.length) {
          this._messageLength = this._totalPayloadLength;
          this._fragments.push(data);
        }
        this.dataMessage(cb);
      }
      /**
       * Decompresses data.
       *
       * @param {Buffer} data Compressed data
       * @param {Function} cb Callback
       * @private
       */
      decompress(data, cb) {
        const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
        perMessageDeflate.decompress(data, this._fin, (err, buf) => {
          if (err) return cb(err);
          if (buf.length) {
            this._messageLength += buf.length;
            if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
              const error = this.createError(
                RangeError,
                "Max payload size exceeded",
                false,
                1009,
                "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
              );
              cb(error);
              return;
            }
            this._fragments.push(buf);
          }
          this.dataMessage(cb);
          if (this._state === GET_INFO) this.startLoop(cb);
        });
      }
      /**
       * Handles a data message.
       *
       * @param {Function} cb Callback
       * @private
       */
      dataMessage(cb) {
        if (!this._fin) {
          this._state = GET_INFO;
          return;
        }
        const messageLength = this._messageLength;
        const fragments = this._fragments;
        this._totalPayloadLength = 0;
        this._messageLength = 0;
        this._fragmented = 0;
        this._fragments = [];
        if (this._opcode === 2) {
          let data;
          if (this._binaryType === "nodebuffer") {
            data = concat3(fragments, messageLength);
          } else if (this._binaryType === "arraybuffer") {
            data = toArrayBuffer2(concat3(fragments, messageLength));
          } else if (this._binaryType === "blob") {
            data = new Blob(fragments);
          } else {
            data = fragments;
          }
          if (this._allowSynchronousEvents) {
            this.emit("message", data, true);
            this._state = GET_INFO;
          } else {
            this._state = DEFER_EVENT;
            setImmediate(() => {
              this.emit("message", data, true);
              this._state = GET_INFO;
              this.startLoop(cb);
            });
          }
        } else {
          const buf = concat3(fragments, messageLength);
          if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
            const error = this.createError(
              Error,
              "invalid UTF-8 sequence",
              true,
              1007,
              "WS_ERR_INVALID_UTF8"
            );
            cb(error);
            return;
          }
          if (this._state === INFLATING || this._allowSynchronousEvents) {
            this.emit("message", buf, false);
            this._state = GET_INFO;
          } else {
            this._state = DEFER_EVENT;
            setImmediate(() => {
              this.emit("message", buf, false);
              this._state = GET_INFO;
              this.startLoop(cb);
            });
          }
        }
      }
      /**
       * Handles a control message.
       *
       * @param {Buffer} data Data to handle
       * @return {(Error|RangeError|undefined)} A possible error
       * @private
       */
      controlMessage(data, cb) {
        if (this._opcode === 8) {
          if (data.length === 0) {
            this._loop = false;
            this.emit("conclude", 1005, EMPTY_BUFFER);
            this.end();
          } else {
            const code = data.readUInt16BE(0);
            if (!isValidStatusCode(code)) {
              const error = this.createError(
                RangeError,
                `invalid status code ${code}`,
                true,
                1002,
                "WS_ERR_INVALID_CLOSE_CODE"
              );
              cb(error);
              return;
            }
            const buf = new FastBuffer(
              data.buffer,
              data.byteOffset + 2,
              data.length - 2
            );
            if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
              const error = this.createError(
                Error,
                "invalid UTF-8 sequence",
                true,
                1007,
                "WS_ERR_INVALID_UTF8"
              );
              cb(error);
              return;
            }
            this._loop = false;
            this.emit("conclude", code, buf);
            this.end();
          }
          this._state = GET_INFO;
          return;
        }
        if (this._allowSynchronousEvents) {
          this.emit(this._opcode === 9 ? "ping" : "pong", data);
          this._state = GET_INFO;
        } else {
          this._state = DEFER_EVENT;
          setImmediate(() => {
            this.emit(this._opcode === 9 ? "ping" : "pong", data);
            this._state = GET_INFO;
            this.startLoop(cb);
          });
        }
      }
      /**
       * Builds an error object.
       *
       * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
       * @param {String} message The error message
       * @param {Boolean} prefix Specifies whether or not to add a default prefix to
       *     `message`
       * @param {Number} statusCode The status code
       * @param {String} errorCode The exposed error code
       * @return {(Error|RangeError)} The error
       * @private
       */
      createError(ErrorCtor, message, prefix, statusCode, errorCode) {
        this._loop = false;
        this._errored = true;
        const err = new ErrorCtor(
          prefix ? `Invalid WebSocket frame: ${message}` : message
        );
        Error.captureStackTrace(err, this.createError);
        err.code = errorCode;
        err[kStatusCode] = statusCode;
        return err;
      }
    };
    module.exports = Receiver2;
  }
});

// node_modules/ws/lib/sender.js
var require_sender = __commonJS({
  "node_modules/ws/lib/sender.js"(exports, module) {
    "use strict";
    var { Duplex } = __require("stream");
    var { randomFillSync } = __require("crypto");
    var PerMessageDeflate2 = require_permessage_deflate();
    var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
    var { isBlob, isValidStatusCode } = require_validation();
    var { mask: applyMask, toBuffer } = require_buffer_util();
    var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
    var maskBuffer = Buffer.alloc(4);
    var RANDOM_POOL_SIZE = 8 * 1024;
    var randomPool;
    var randomPoolPointer = RANDOM_POOL_SIZE;
    var DEFAULT = 0;
    var DEFLATING = 1;
    var GET_BLOB_DATA = 2;
    var Sender2 = class _Sender {
      /**
       * Creates a Sender instance.
       *
       * @param {Duplex} socket The connection socket
       * @param {Object} [extensions] An object containing the negotiated extensions
       * @param {Function} [generateMask] The function used to generate the masking
       *     key
       */
      constructor(socket, extensions, generateMask) {
        this._extensions = extensions || {};
        if (generateMask) {
          this._generateMask = generateMask;
          this._maskBuffer = Buffer.alloc(4);
        }
        this._socket = socket;
        this._firstFragment = true;
        this._compress = false;
        this._bufferedBytes = 0;
        this._queue = [];
        this._state = DEFAULT;
        this.onerror = NOOP;
        this[kWebSocket] = void 0;
      }
      /**
       * Frames a piece of data according to the HyBi WebSocket protocol.
       *
       * @param {(Buffer|String)} data The data to frame
       * @param {Object} options Options object
       * @param {Boolean} [options.fin=false] Specifies whether or not to set the
       *     FIN bit
       * @param {Function} [options.generateMask] The function used to generate the
       *     masking key
       * @param {Boolean} [options.mask=false] Specifies whether or not to mask
       *     `data`
       * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
       *     key
       * @param {Number} options.opcode The opcode
       * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
       *     modified
       * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
       *     RSV1 bit
       * @return {(Buffer|String)[]} The framed data
       * @public
       */
      static frame(data, options) {
        let mask;
        let merge = false;
        let offset = 2;
        let skipMasking = false;
        if (options.mask) {
          mask = options.maskBuffer || maskBuffer;
          if (options.generateMask) {
            options.generateMask(mask);
          } else {
            if (randomPoolPointer === RANDOM_POOL_SIZE) {
              if (randomPool === void 0) {
                randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
              }
              randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
              randomPoolPointer = 0;
            }
            mask[0] = randomPool[randomPoolPointer++];
            mask[1] = randomPool[randomPoolPointer++];
            mask[2] = randomPool[randomPoolPointer++];
            mask[3] = randomPool[randomPoolPointer++];
          }
          skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
          offset = 6;
        }
        let dataLength;
        if (typeof data === "string") {
          if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
            dataLength = options[kByteLength];
          } else {
            data = Buffer.from(data);
            dataLength = data.length;
          }
        } else {
          dataLength = data.length;
          merge = options.mask && options.readOnly && !skipMasking;
        }
        let payloadLength = dataLength;
        if (dataLength >= 65536) {
          offset += 8;
          payloadLength = 127;
        } else if (dataLength > 125) {
          offset += 2;
          payloadLength = 126;
        }
        const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
        target[0] = options.fin ? options.opcode | 128 : options.opcode;
        if (options.rsv1) target[0] |= 64;
        target[1] = payloadLength;
        if (payloadLength === 126) {
          target.writeUInt16BE(dataLength, 2);
        } else if (payloadLength === 127) {
          target[2] = target[3] = 0;
          target.writeUIntBE(dataLength, 4, 6);
        }
        if (!options.mask) return [target, data];
        target[1] |= 128;
        target[offset - 4] = mask[0];
        target[offset - 3] = mask[1];
        target[offset - 2] = mask[2];
        target[offset - 1] = mask[3];
        if (skipMasking) return [target, data];
        if (merge) {
          applyMask(data, mask, target, offset, dataLength);
          return [target];
        }
        applyMask(data, mask, data, 0, dataLength);
        return [target, data];
      }
      /**
       * Sends a close message to the other peer.
       *
       * @param {Number} [code] The status code component of the body
       * @param {(String|Buffer)} [data] The message component of the body
       * @param {Boolean} [mask=false] Specifies whether or not to mask the message
       * @param {Function} [cb] Callback
       * @public
       */
      close(code, data, mask, cb) {
        let buf;
        if (code === void 0) {
          buf = EMPTY_BUFFER;
        } else if (typeof code !== "number" || !isValidStatusCode(code)) {
          throw new TypeError("First argument must be a valid error code number");
        } else if (data === void 0 || !data.length) {
          buf = Buffer.allocUnsafe(2);
          buf.writeUInt16BE(code, 0);
        } else {
          const length = Buffer.byteLength(data);
          if (length > 123) {
            throw new RangeError("The message must not be greater than 123 bytes");
          }
          buf = Buffer.allocUnsafe(2 + length);
          buf.writeUInt16BE(code, 0);
          if (typeof data === "string") {
            buf.write(data, 2);
          } else {
            buf.set(data, 2);
          }
        }
        const options = {
          [kByteLength]: buf.length,
          fin: true,
          generateMask: this._generateMask,
          mask,
          maskBuffer: this._maskBuffer,
          opcode: 8,
          readOnly: false,
          rsv1: false
        };
        if (this._state !== DEFAULT) {
          this.enqueue([this.dispatch, buf, false, options, cb]);
        } else {
          this.sendFrame(_Sender.frame(buf, options), cb);
        }
      }
      /**
       * Sends a ping message to the other peer.
       *
       * @param {*} data The message to send
       * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
       * @param {Function} [cb] Callback
       * @public
       */
      ping(data, mask, cb) {
        let byteLength;
        let readOnly;
        if (typeof data === "string") {
          byteLength = Buffer.byteLength(data);
          readOnly = false;
        } else if (isBlob(data)) {
          byteLength = data.size;
          readOnly = false;
        } else {
          data = toBuffer(data);
          byteLength = data.length;
          readOnly = toBuffer.readOnly;
        }
        if (byteLength > 125) {
          throw new RangeError("The data size must not be greater than 125 bytes");
        }
        const options = {
          [kByteLength]: byteLength,
          fin: true,
          generateMask: this._generateMask,
          mask,
          maskBuffer: this._maskBuffer,
          opcode: 9,
          readOnly,
          rsv1: false
        };
        if (isBlob(data)) {
          if (this._state !== DEFAULT) {
            this.enqueue([this.getBlobData, data, false, options, cb]);
          } else {
            this.getBlobData(data, false, options, cb);
          }
        } else if (this._state !== DEFAULT) {
          this.enqueue([this.dispatch, data, false, options, cb]);
        } else {
          this.sendFrame(_Sender.frame(data, options), cb);
        }
      }
      /**
       * Sends a pong message to the other peer.
       *
       * @param {*} data The message to send
       * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
       * @param {Function} [cb] Callback
       * @public
       */
      pong(data, mask, cb) {
        let byteLength;
        let readOnly;
        if (typeof data === "string") {
          byteLength = Buffer.byteLength(data);
          readOnly = false;
        } else if (isBlob(data)) {
          byteLength = data.size;
          readOnly = false;
        } else {
          data = toBuffer(data);
          byteLength = data.length;
          readOnly = toBuffer.readOnly;
        }
        if (byteLength > 125) {
          throw new RangeError("The data size must not be greater than 125 bytes");
        }
        const options = {
          [kByteLength]: byteLength,
          fin: true,
          generateMask: this._generateMask,
          mask,
          maskBuffer: this._maskBuffer,
          opcode: 10,
          readOnly,
          rsv1: false
        };
        if (isBlob(data)) {
          if (this._state !== DEFAULT) {
            this.enqueue([this.getBlobData, data, false, options, cb]);
          } else {
            this.getBlobData(data, false, options, cb);
          }
        } else if (this._state !== DEFAULT) {
          this.enqueue([this.dispatch, data, false, options, cb]);
        } else {
          this.sendFrame(_Sender.frame(data, options), cb);
        }
      }
      /**
       * Sends a data message to the other peer.
       *
       * @param {*} data The message to send
       * @param {Object} options Options object
       * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
       *     or text
       * @param {Boolean} [options.compress=false] Specifies whether or not to
       *     compress `data`
       * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
       *     last one
       * @param {Boolean} [options.mask=false] Specifies whether or not to mask
       *     `data`
       * @param {Function} [cb] Callback
       * @public
       */
      send(data, options, cb) {
        const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
        let opcode = options.binary ? 2 : 1;
        let rsv1 = options.compress;
        let byteLength;
        let readOnly;
        if (typeof data === "string") {
          byteLength = Buffer.byteLength(data);
          readOnly = false;
        } else if (isBlob(data)) {
          byteLength = data.size;
          readOnly = false;
        } else {
          data = toBuffer(data);
          byteLength = data.length;
          readOnly = toBuffer.readOnly;
        }
        if (this._firstFragment) {
          this._firstFragment = false;
          if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
            rsv1 = byteLength >= perMessageDeflate._threshold;
          }
          this._compress = rsv1;
        } else {
          rsv1 = false;
          opcode = 0;
        }
        if (options.fin) this._firstFragment = true;
        const opts = {
          [kByteLength]: byteLength,
          fin: options.fin,
          generateMask: this._generateMask,
          mask: options.mask,
          maskBuffer: this._maskBuffer,
          opcode,
          readOnly,
          rsv1
        };
        if (isBlob(data)) {
          if (this._state !== DEFAULT) {
            this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
          } else {
            this.getBlobData(data, this._compress, opts, cb);
          }
        } else if (this._state !== DEFAULT) {
          this.enqueue([this.dispatch, data, this._compress, opts, cb]);
        } else {
          this.dispatch(data, this._compress, opts, cb);
        }
      }
      /**
       * Gets the contents of a blob as binary data.
       *
       * @param {Blob} blob The blob
       * @param {Boolean} [compress=false] Specifies whether or not to compress
       *     the data
       * @param {Object} options Options object
       * @param {Boolean} [options.fin=false] Specifies whether or not to set the
       *     FIN bit
       * @param {Function} [options.generateMask] The function used to generate the
       *     masking key
       * @param {Boolean} [options.mask=false] Specifies whether or not to mask
       *     `data`
       * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
       *     key
       * @param {Number} options.opcode The opcode
       * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
       *     modified
       * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
       *     RSV1 bit
       * @param {Function} [cb] Callback
       * @private
       */
      getBlobData(blob, compress, options, cb) {
        this._bufferedBytes += options[kByteLength];
        this._state = GET_BLOB_DATA;
        blob.arrayBuffer().then((arrayBuffer) => {
          if (this._socket.destroyed) {
            const err = new Error(
              "The socket was closed while the blob was being read"
            );
            process.nextTick(callCallbacks, this, err, cb);
            return;
          }
          this._bufferedBytes -= options[kByteLength];
          const data = toBuffer(arrayBuffer);
          if (!compress) {
            this._state = DEFAULT;
            this.sendFrame(_Sender.frame(data, options), cb);
            this.dequeue();
          } else {
            this.dispatch(data, compress, options, cb);
          }
        }).catch((err) => {
          process.nextTick(onError, this, err, cb);
        });
      }
      /**
       * Dispatches a message.
       *
       * @param {(Buffer|String)} data The message to send
       * @param {Boolean} [compress=false] Specifies whether or not to compress
       *     `data`
       * @param {Object} options Options object
       * @param {Boolean} [options.fin=false] Specifies whether or not to set the
       *     FIN bit
       * @param {Function} [options.generateMask] The function used to generate the
       *     masking key
       * @param {Boolean} [options.mask=false] Specifies whether or not to mask
       *     `data`
       * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
       *     key
       * @param {Number} options.opcode The opcode
       * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
       *     modified
       * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
       *     RSV1 bit
       * @param {Function} [cb] Callback
       * @private
       */
      dispatch(data, compress, options, cb) {
        if (!compress) {
          this.sendFrame(_Sender.frame(data, options), cb);
          return;
        }
        const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
        this._bufferedBytes += options[kByteLength];
        this._state = DEFLATING;
        perMessageDeflate.compress(data, options.fin, (_, buf) => {
          if (this._socket.destroyed) {
            const err = new Error(
              "The socket was closed while data was being compressed"
            );
            callCallbacks(this, err, cb);
            return;
          }
          this._bufferedBytes -= options[kByteLength];
          this._state = DEFAULT;
          options.readOnly = false;
          this.sendFrame(_Sender.frame(buf, options), cb);
          this.dequeue();
        });
      }
      /**
       * Executes queued send operations.
       *
       * @private
       */
      dequeue() {
        while (this._state === DEFAULT && this._queue.length) {
          const params = this._queue.shift();
          this._bufferedBytes -= params[3][kByteLength];
          Reflect.apply(params[0], this, params.slice(1));
        }
      }
      /**
       * Enqueues a send operation.
       *
       * @param {Array} params Send operation parameters.
       * @private
       */
      enqueue(params) {
        this._bufferedBytes += params[3][kByteLength];
        this._queue.push(params);
      }
      /**
       * Sends a frame.
       *
       * @param {(Buffer | String)[]} list The frame to send
       * @param {Function} [cb] Callback
       * @private
       */
      sendFrame(list, cb) {
        if (list.length === 2) {
          this._socket.cork();
          this._socket.write(list[0]);
          this._socket.write(list[1], cb);
          this._socket.uncork();
        } else {
          this._socket.write(list[0], cb);
        }
      }
    };
    module.exports = Sender2;
    function callCallbacks(sender, err, cb) {
      if (typeof cb === "function") cb(err);
      for (let i = 0; i < sender._queue.length; i++) {
        const params = sender._queue[i];
        const callback = params[params.length - 1];
        if (typeof callback === "function") callback(err);
      }
    }
    function onError(sender, err, cb) {
      callCallbacks(sender, err, cb);
      sender.onerror(err);
    }
  }
});

// node_modules/ws/lib/event-target.js
var require_event_target = __commonJS({
  "node_modules/ws/lib/event-target.js"(exports, module) {
    "use strict";
    var { kForOnEventAttribute, kListener } = require_constants();
    var kCode = /* @__PURE__ */ Symbol("kCode");
    var kData = /* @__PURE__ */ Symbol("kData");
    var kError = /* @__PURE__ */ Symbol("kError");
    var kMessage = /* @__PURE__ */ Symbol("kMessage");
    var kReason = /* @__PURE__ */ Symbol("kReason");
    var kTarget = /* @__PURE__ */ Symbol("kTarget");
    var kType = /* @__PURE__ */ Symbol("kType");
    var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
    var Event2 = class {
      /**
       * Create a new `Event`.
       *
       * @param {String} type The name of the event
       * @throws {TypeError} If the `type` argument is not specified
       */
      constructor(type) {
        this[kTarget] = null;
        this[kType] = type;
      }
      /**
       * @type {*}
       */
      get target() {
        return this[kTarget];
      }
      /**
       * @type {String}
       */
      get type() {
        return this[kType];
      }
    };
    Object.defineProperty(Event2.prototype, "target", { enumerable: true });
    Object.defineProperty(Event2.prototype, "type", { enumerable: true });
    var CloseEvent = class extends Event2 {
      /**
       * Create a new `CloseEvent`.
       *
       * @param {String} type The name of the event
       * @param {Object} [options] A dictionary object that allows for setting
       *     attributes via object members of the same name
       * @param {Number} [options.code=0] The status code explaining why the
       *     connection was closed
       * @param {String} [options.reason=''] A human-readable string explaining why
       *     the connection was closed
       * @param {Boolean} [options.wasClean=false] Indicates whether or not the
       *     connection was cleanly closed
       */
      constructor(type, options = {}) {
        super(type);
        this[kCode] = options.code === void 0 ? 0 : options.code;
        this[kReason] = options.reason === void 0 ? "" : options.reason;
        this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
      }
      /**
       * @type {Number}
       */
      get code() {
        return this[kCode];
      }
      /**
       * @type {String}
       */
      get reason() {
        return this[kReason];
      }
      /**
       * @type {Boolean}
       */
      get wasClean() {
        return this[kWasClean];
      }
    };
    Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
    Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
    Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
    var ErrorEvent = class extends Event2 {
      /**
       * Create a new `ErrorEvent`.
       *
       * @param {String} type The name of the event
       * @param {Object} [options] A dictionary object that allows for setting
       *     attributes via object members of the same name
       * @param {*} [options.error=null] The error that generated this event
       * @param {String} [options.message=''] The error message
       */
      constructor(type, options = {}) {
        super(type);
        this[kError] = options.error === void 0 ? null : options.error;
        this[kMessage] = options.message === void 0 ? "" : options.message;
      }
      /**
       * @type {*}
       */
      get error() {
        return this[kError];
      }
      /**
       * @type {String}
       */
      get message() {
        return this[kMessage];
      }
    };
    Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
    Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
    var MessageEvent = class extends Event2 {
      /**
       * Create a new `MessageEvent`.
       *
       * @param {String} type The name of the event
       * @param {Object} [options] A dictionary object that allows for setting
       *     attributes via object members of the same name
       * @param {*} [options.data=null] The message content
       */
      constructor(type, options = {}) {
        super(type);
        this[kData] = options.data === void 0 ? null : options.data;
      }
      /**
       * @type {*}
       */
      get data() {
        return this[kData];
      }
    };
    Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
    var EventTarget2 = {
      /**
       * Register an event listener.
       *
       * @param {String} type A string representing the event type to listen for
       * @param {(Function|Object)} handler The listener to add
       * @param {Object} [options] An options object specifies characteristics about
       *     the event listener
       * @param {Boolean} [options.once=false] A `Boolean` indicating that the
       *     listener should be invoked at most once after being added. If `true`,
       *     the listener would be automatically removed when invoked.
       * @public
       */
      addEventListener(type, handler, options = {}) {
        for (const listener of this.listeners(type)) {
          if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
            return;
          }
        }
        let wrapper;
        if (type === "message") {
          wrapper = function onMessage(data, isBinary) {
            const event = new MessageEvent("message", {
              data: isBinary ? data : data.toString()
            });
            event[kTarget] = this;
            callListener(handler, this, event);
          };
        } else if (type === "close") {
          wrapper = function onClose(code, message) {
            const event = new CloseEvent("close", {
              code,
              reason: message.toString(),
              wasClean: this._closeFrameReceived && this._closeFrameSent
            });
            event[kTarget] = this;
            callListener(handler, this, event);
          };
        } else if (type === "error") {
          wrapper = function onError(error) {
            const event = new ErrorEvent("error", {
              error,
              message: error.message
            });
            event[kTarget] = this;
            callListener(handler, this, event);
          };
        } else if (type === "open") {
          wrapper = function onOpen() {
            const event = new Event2("open");
            event[kTarget] = this;
            callListener(handler, this, event);
          };
        } else {
          return;
        }
        wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
        wrapper[kListener] = handler;
        if (options.once) {
          this.once(type, wrapper);
        } else {
          this.on(type, wrapper);
        }
      },
      /**
       * Remove an event listener.
       *
       * @param {String} type A string representing the event type to remove
       * @param {(Function|Object)} handler The listener to remove
       * @public
       */
      removeEventListener(type, handler) {
        for (const listener of this.listeners(type)) {
          if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
            this.removeListener(type, listener);
            break;
          }
        }
      }
    };
    module.exports = {
      CloseEvent,
      ErrorEvent,
      Event: Event2,
      EventTarget: EventTarget2,
      MessageEvent
    };
    function callListener(listener, thisArg, event) {
      if (typeof listener === "object" && listener.handleEvent) {
        listener.handleEvent.call(listener, event);
      } else {
        listener.call(thisArg, event);
      }
    }
  }
});

// node_modules/ws/lib/extension.js
var require_extension = __commonJS({
  "node_modules/ws/lib/extension.js"(exports, module) {
    "use strict";
    var { tokenChars } = require_validation();
    function push(dest, name, elem) {
      if (dest[name] === void 0) dest[name] = [elem];
      else dest[name].push(elem);
    }
    function parse(header) {
      const offers = /* @__PURE__ */ Object.create(null);
      let params = /* @__PURE__ */ Object.create(null);
      let mustUnescape = false;
      let isEscaping = false;
      let inQuotes = false;
      let extensionName;
      let paramName;
      let start = -1;
      let code = -1;
      let end = -1;
      let i = 0;
      for (; i < header.length; i++) {
        code = header.charCodeAt(i);
        if (extensionName === void 0) {
          if (end === -1 && tokenChars[code] === 1) {
            if (start === -1) start = i;
          } else if (i !== 0 && (code === 32 || code === 9)) {
            if (end === -1 && start !== -1) end = i;
          } else if (code === 59 || code === 44) {
            if (start === -1) {
              throw new SyntaxError(`Unexpected character at index ${i}`);
            }
            if (end === -1) end = i;
            const name = header.slice(start, end);
            if (code === 44) {
              push(offers, name, params);
              params = /* @__PURE__ */ Object.create(null);
            } else {
              extensionName = name;
            }
            start = end = -1;
          } else {
            throw new SyntaxError(`Unexpected character at index ${i}`);
          }
        } else if (paramName === void 0) {
          if (end === -1 && tokenChars[code] === 1) {
            if (start === -1) start = i;
          } else if (code === 32 || code === 9) {
            if (end === -1 && start !== -1) end = i;
          } else if (code === 59 || code === 44) {
            if (start === -1) {
              throw new SyntaxError(`Unexpected character at index ${i}`);
            }
            if (end === -1) end = i;
            push(params, header.slice(start, end), true);
            if (code === 44) {
              push(offers, extensionName, params);
              params = /* @__PURE__ */ Object.create(null);
              extensionName = void 0;
            }
            start = end = -1;
          } else if (code === 61 && start !== -1 && end === -1) {
            paramName = header.slice(start, i);
            start = end = -1;
          } else {
            throw new SyntaxError(`Unexpected character at index ${i}`);
          }
        } else {
          if (isEscaping) {
            if (tokenChars[code] !== 1) {
              throw new SyntaxError(`Unexpected character at index ${i}`);
            }
            if (start === -1) start = i;
            else if (!mustUnescape) mustUnescape = true;
            isEscaping = false;
          } else if (inQuotes) {
            if (tokenChars[code] === 1) {
              if (start === -1) start = i;
            } else if (code === 34 && start !== -1) {
              inQuotes = false;
              end = i;
            } else if (code === 92) {
              isEscaping = true;
            } else {
              throw new SyntaxError(`Unexpected character at index ${i}`);
            }
          } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
            inQuotes = true;
          } else if (end === -1 && tokenChars[code] === 1) {
            if (start === -1) start = i;
          } else if (start !== -1 && (code === 32 || code === 9)) {
            if (end === -1) end = i;
          } else if (code === 59 || code === 44) {
            if (start === -1) {
              throw new SyntaxError(`Unexpected character at index ${i}`);
            }
            if (end === -1) end = i;
            let value = header.slice(start, end);
            if (mustUnescape) {
              value = value.replace(/\\/g, "");
              mustUnescape = false;
            }
            push(params, paramName, value);
            if (code === 44) {
              push(offers, extensionName, params);
              params = /* @__PURE__ */ Object.create(null);
              extensionName = void 0;
            }
            paramName = void 0;
            start = end = -1;
          } else {
            throw new SyntaxError(`Unexpected character at index ${i}`);
          }
        }
      }
      if (start === -1 || inQuotes || code === 32 || code === 9) {
        throw new SyntaxError("Unexpected end of input");
      }
      if (end === -1) end = i;
      const token = header.slice(start, end);
      if (extensionName === void 0) {
        push(offers, token, params);
      } else {
        if (paramName === void 0) {
          push(params, token, true);
        } else if (mustUnescape) {
          push(params, paramName, token.replace(/\\/g, ""));
        } else {
          push(params, paramName, token);
        }
        push(offers, extensionName, params);
      }
      return offers;
    }
    function format(extensions) {
      return Object.keys(extensions).map((extension2) => {
        let configurations = extensions[extension2];
        if (!Array.isArray(configurations)) configurations = [configurations];
        return configurations.map((params) => {
          return [extension2].concat(
            Object.keys(params).map((k) => {
              let values = params[k];
              if (!Array.isArray(values)) values = [values];
              return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
            })
          ).join("; ");
        }).join(", ");
      }).join(", ");
    }
    module.exports = { format, parse };
  }
});

// node_modules/ws/lib/websocket.js
var require_websocket = __commonJS({
  "node_modules/ws/lib/websocket.js"(exports, module) {
    "use strict";
    var EventEmitter = __require("events");
    var https = __require("https");
    var http2 = __require("http");
    var net = __require("net");
    var tls = __require("tls");
    var { randomBytes: randomBytes8, createHash: createHash4 } = __require("crypto");
    var { Duplex, Readable } = __require("stream");
    var { URL: URL2 } = __require("url");
    var PerMessageDeflate2 = require_permessage_deflate();
    var Receiver2 = require_receiver();
    var Sender2 = require_sender();
    var { isBlob } = require_validation();
    var {
      BINARY_TYPES,
      CLOSE_TIMEOUT,
      EMPTY_BUFFER,
      GUID,
      kForOnEventAttribute,
      kListener,
      kStatusCode,
      kWebSocket,
      NOOP
    } = require_constants();
    var {
      EventTarget: { addEventListener, removeEventListener }
    } = require_event_target();
    var { format, parse } = require_extension();
    var { toBuffer } = require_buffer_util();
    var kAborted = /* @__PURE__ */ Symbol("kAborted");
    var protocolVersions = [8, 13];
    var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
    var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
    var WebSocket2 = class _WebSocket extends EventEmitter {
      /**
       * Create a new `WebSocket`.
       *
       * @param {(String|URL)} address The URL to which to connect
       * @param {(String|String[])} [protocols] The subprotocols
       * @param {Object} [options] Connection options
       */
      constructor(address2, protocols, options) {
        super();
        this._binaryType = BINARY_TYPES[0];
        this._closeCode = 1006;
        this._closeFrameReceived = false;
        this._closeFrameSent = false;
        this._closeMessage = EMPTY_BUFFER;
        this._closeTimer = null;
        this._errorEmitted = false;
        this._extensions = {};
        this._paused = false;
        this._protocol = "";
        this._readyState = _WebSocket.CONNECTING;
        this._receiver = null;
        this._sender = null;
        this._socket = null;
        if (address2 !== null) {
          this._bufferedAmount = 0;
          this._isServer = false;
          this._redirects = 0;
          if (protocols === void 0) {
            protocols = [];
          } else if (!Array.isArray(protocols)) {
            if (typeof protocols === "object" && protocols !== null) {
              options = protocols;
              protocols = [];
            } else {
              protocols = [protocols];
            }
          }
          initAsClient(this, address2, protocols, options);
        } else {
          this._autoPong = options.autoPong;
          this._closeTimeout = options.closeTimeout;
          this._isServer = true;
        }
      }
      /**
       * For historical reasons, the custom "nodebuffer" type is used by the default
       * instead of "blob".
       *
       * @type {String}
       */
      get binaryType() {
        return this._binaryType;
      }
      set binaryType(type) {
        if (!BINARY_TYPES.includes(type)) return;
        this._binaryType = type;
        if (this._receiver) this._receiver._binaryType = type;
      }
      /**
       * @type {Number}
       */
      get bufferedAmount() {
        if (!this._socket) return this._bufferedAmount;
        return this._socket._writableState.length + this._sender._bufferedBytes;
      }
      /**
       * @type {String}
       */
      get extensions() {
        return Object.keys(this._extensions).join();
      }
      /**
       * @type {Boolean}
       */
      get isPaused() {
        return this._paused;
      }
      /**
       * @type {Function}
       */
      /* istanbul ignore next */
      get onclose() {
        return null;
      }
      /**
       * @type {Function}
       */
      /* istanbul ignore next */
      get onerror() {
        return null;
      }
      /**
       * @type {Function}
       */
      /* istanbul ignore next */
      get onopen() {
        return null;
      }
      /**
       * @type {Function}
       */
      /* istanbul ignore next */
      get onmessage() {
        return null;
      }
      /**
       * @type {String}
       */
      get protocol() {
        return this._protocol;
      }
      /**
       * @type {Number}
       */
      get readyState() {
        return this._readyState;
      }
      /**
       * @type {String}
       */
      get url() {
        return this._url;
      }
      /**
       * Set up the socket and the internal resources.
       *
       * @param {Duplex} socket The network socket between the server and client
       * @param {Buffer} head The first packet of the upgraded stream
       * @param {Object} options Options object
       * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
       *     any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
       *     multiple times in the same tick
       * @param {Function} [options.generateMask] The function used to generate the
       *     masking key
       * @param {Number} [options.maxPayload=0] The maximum allowed message size
       * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
       *     not to skip UTF-8 validation for text and close messages
       * @private
       */
      setSocket(socket, head, options) {
        const receiver = new Receiver2({
          allowSynchronousEvents: options.allowSynchronousEvents,
          binaryType: this.binaryType,
          extensions: this._extensions,
          isServer: this._isServer,
          maxPayload: options.maxPayload,
          skipUTF8Validation: options.skipUTF8Validation
        });
        const sender = new Sender2(socket, this._extensions, options.generateMask);
        this._receiver = receiver;
        this._sender = sender;
        this._socket = socket;
        receiver[kWebSocket] = this;
        sender[kWebSocket] = this;
        socket[kWebSocket] = this;
        receiver.on("conclude", receiverOnConclude);
        receiver.on("drain", receiverOnDrain);
        receiver.on("error", receiverOnError);
        receiver.on("message", receiverOnMessage);
        receiver.on("ping", receiverOnPing);
        receiver.on("pong", receiverOnPong);
        sender.onerror = senderOnError;
        if (socket.setTimeout) socket.setTimeout(0);
        if (socket.setNoDelay) socket.setNoDelay();
        if (head.length > 0) socket.unshift(head);
        socket.on("close", socketOnClose);
        socket.on("data", socketOnData);
        socket.on("end", socketOnEnd);
        socket.on("error", socketOnError);
        this._readyState = _WebSocket.OPEN;
        this.emit("open");
      }
      /**
       * Emit the `'close'` event.
       *
       * @private
       */
      emitClose() {
        if (!this._socket) {
          this._readyState = _WebSocket.CLOSED;
          this.emit("close", this._closeCode, this._closeMessage);
          return;
        }
        if (this._extensions[PerMessageDeflate2.extensionName]) {
          this._extensions[PerMessageDeflate2.extensionName].cleanup();
        }
        this._receiver.removeAllListeners();
        this._readyState = _WebSocket.CLOSED;
        this.emit("close", this._closeCode, this._closeMessage);
      }
      /**
       * Start a closing handshake.
       *
       *          +----------+   +-----------+   +----------+
       *     - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
       *    |     +----------+   +-----------+   +----------+     |
       *          +----------+   +-----------+         |
       * CLOSING  |ws.close()|<--|close frame|<--+-----+       CLOSING
       *          +----------+   +-----------+   |
       *    |           |                        |   +---+        |
       *                +------------------------+-->|fin| - - - -
       *    |         +---+                      |   +---+
       *     - - - - -|fin|<---------------------+
       *              +---+
       *
       * @param {Number} [code] Status code explaining why the connection is closing
       * @param {(String|Buffer)} [data] The reason why the connection is
       *     closing
       * @public
       */
      close(code, data) {
        if (this.readyState === _WebSocket.CLOSED) return;
        if (this.readyState === _WebSocket.CONNECTING) {
          const msg = "WebSocket was closed before the connection was established";
          abortHandshake(this, this._req, msg);
          return;
        }
        if (this.readyState === _WebSocket.CLOSING) {
          if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
            this._socket.end();
          }
          return;
        }
        this._readyState = _WebSocket.CLOSING;
        this._sender.close(code, data, !this._isServer, (err) => {
          if (err) return;
          this._closeFrameSent = true;
          if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
            this._socket.end();
          }
        });
        setCloseTimer(this);
      }
      /**
       * Pause the socket.
       *
       * @public
       */
      pause() {
        if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
          return;
        }
        this._paused = true;
        this._socket.pause();
      }
      /**
       * Send a ping.
       *
       * @param {*} [data] The data to send
       * @param {Boolean} [mask] Indicates whether or not to mask `data`
       * @param {Function} [cb] Callback which is executed when the ping is sent
       * @public
       */
      ping(data, mask, cb) {
        if (this.readyState === _WebSocket.CONNECTING) {
          throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
        }
        if (typeof data === "function") {
          cb = data;
          data = mask = void 0;
        } else if (typeof mask === "function") {
          cb = mask;
          mask = void 0;
        }
        if (typeof data === "number") data = data.toString();
        if (this.readyState !== _WebSocket.OPEN) {
          sendAfterClose(this, data, cb);
          return;
        }
        if (mask === void 0) mask = !this._isServer;
        this._sender.ping(data || EMPTY_BUFFER, mask, cb);
      }
      /**
       * Send a pong.
       *
       * @param {*} [data] The data to send
       * @param {Boolean} [mask] Indicates whether or not to mask `data`
       * @param {Function} [cb] Callback which is executed when the pong is sent
       * @public
       */
      pong(data, mask, cb) {
        if (this.readyState === _WebSocket.CONNECTING) {
          throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
        }
        if (typeof data === "function") {
          cb = data;
          data = mask = void 0;
        } else if (typeof mask === "function") {
          cb = mask;
          mask = void 0;
        }
        if (typeof data === "number") data = data.toString();
        if (this.readyState !== _WebSocket.OPEN) {
          sendAfterClose(this, data, cb);
          return;
        }
        if (mask === void 0) mask = !this._isServer;
        this._sender.pong(data || EMPTY_BUFFER, mask, cb);
      }
      /**
       * Resume the socket.
       *
       * @public
       */
      resume() {
        if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
          return;
        }
        this._paused = false;
        if (!this._receiver._writableState.needDrain) this._socket.resume();
      }
      /**
       * Send a data message.
       *
       * @param {*} data The message to send
       * @param {Object} [options] Options object
       * @param {Boolean} [options.binary] Specifies whether `data` is binary or
       *     text
       * @param {Boolean} [options.compress] Specifies whether or not to compress
       *     `data`
       * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
       *     last one
       * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
       * @param {Function} [cb] Callback which is executed when data is written out
       * @public
       */
      send(data, options, cb) {
        if (this.readyState === _WebSocket.CONNECTING) {
          throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
        }
        if (typeof options === "function") {
          cb = options;
          options = {};
        }
        if (typeof data === "number") data = data.toString();
        if (this.readyState !== _WebSocket.OPEN) {
          sendAfterClose(this, data, cb);
          return;
        }
        const opts = {
          binary: typeof data !== "string",
          mask: !this._isServer,
          compress: true,
          fin: true,
          ...options
        };
        if (!this._extensions[PerMessageDeflate2.extensionName]) {
          opts.compress = false;
        }
        this._sender.send(data || EMPTY_BUFFER, opts, cb);
      }
      /**
       * Forcibly close the connection.
       *
       * @public
       */
      terminate() {
        if (this.readyState === _WebSocket.CLOSED) return;
        if (this.readyState === _WebSocket.CONNECTING) {
          const msg = "WebSocket was closed before the connection was established";
          abortHandshake(this, this._req, msg);
          return;
        }
        if (this._socket) {
          this._readyState = _WebSocket.CLOSING;
          this._socket.destroy();
        }
      }
    };
    Object.defineProperty(WebSocket2, "CONNECTING", {
      enumerable: true,
      value: readyStates.indexOf("CONNECTING")
    });
    Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
      enumerable: true,
      value: readyStates.indexOf("CONNECTING")
    });
    Object.defineProperty(WebSocket2, "OPEN", {
      enumerable: true,
      value: readyStates.indexOf("OPEN")
    });
    Object.defineProperty(WebSocket2.prototype, "OPEN", {
      enumerable: true,
      value: readyStates.indexOf("OPEN")
    });
    Object.defineProperty(WebSocket2, "CLOSING", {
      enumerable: true,
      value: readyStates.indexOf("CLOSING")
    });
    Object.defineProperty(WebSocket2.prototype, "CLOSING", {
      enumerable: true,
      value: readyStates.indexOf("CLOSING")
    });
    Object.defineProperty(WebSocket2, "CLOSED", {
      enumerable: true,
      value: readyStates.indexOf("CLOSED")
    });
    Object.defineProperty(WebSocket2.prototype, "CLOSED", {
      enumerable: true,
      value: readyStates.indexOf("CLOSED")
    });
    [
      "binaryType",
      "bufferedAmount",
      "extensions",
      "isPaused",
      "protocol",
      "readyState",
      "url"
    ].forEach((property) => {
      Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
    });
    ["open", "error", "close", "message"].forEach((method) => {
      Object.defineProperty(WebSocket2.prototype, `on${method}`, {
        enumerable: true,
        get() {
          for (const listener of this.listeners(method)) {
            if (listener[kForOnEventAttribute]) return listener[kListener];
          }
          return null;
        },
        set(handler) {
          for (const listener of this.listeners(method)) {
            if (listener[kForOnEventAttribute]) {
              this.removeListener(method, listener);
              break;
            }
          }
          if (typeof handler !== "function") return;
          this.addEventListener(method, handler, {
            [kForOnEventAttribute]: true
          });
        }
      });
    });
    WebSocket2.prototype.addEventListener = addEventListener;
    WebSocket2.prototype.removeEventListener = removeEventListener;
    module.exports = WebSocket2;
    function initAsClient(websocket, address2, protocols, options) {
      const opts = {
        allowSynchronousEvents: true,
        autoPong: true,
        closeTimeout: CLOSE_TIMEOUT,
        protocolVersion: protocolVersions[1],
        maxPayload: 100 * 1024 * 1024,
        skipUTF8Validation: false,
        perMessageDeflate: true,
        followRedirects: false,
        maxRedirects: 10,
        ...options,
        socketPath: void 0,
        hostname: void 0,
        protocol: void 0,
        timeout: void 0,
        method: "GET",
        host: void 0,
        path: void 0,
        port: void 0
      };
      websocket._autoPong = opts.autoPong;
      websocket._closeTimeout = opts.closeTimeout;
      if (!protocolVersions.includes(opts.protocolVersion)) {
        throw new RangeError(
          `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
        );
      }
      let parsedUrl;
      if (address2 instanceof URL2) {
        parsedUrl = address2;
      } else {
        try {
          parsedUrl = new URL2(address2);
        } catch {
          throw new SyntaxError(`Invalid URL: ${address2}`);
        }
      }
      if (parsedUrl.protocol === "http:") {
        parsedUrl.protocol = "ws:";
      } else if (parsedUrl.protocol === "https:") {
        parsedUrl.protocol = "wss:";
      }
      websocket._url = parsedUrl.href;
      const isSecure = parsedUrl.protocol === "wss:";
      const isIpcUrl = parsedUrl.protocol === "ws+unix:";
      let invalidUrlMessage;
      if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
        invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
      } else if (isIpcUrl && !parsedUrl.pathname) {
        invalidUrlMessage = "The URL's pathname is empty";
      } else if (parsedUrl.hash) {
        invalidUrlMessage = "The URL contains a fragment identifier";
      }
      if (invalidUrlMessage) {
        const err = new SyntaxError(invalidUrlMessage);
        if (websocket._redirects === 0) {
          throw err;
        } else {
          emitErrorAndClose(websocket, err);
          return;
        }
      }
      const defaultPort = isSecure ? 443 : 80;
      const key = randomBytes8(16).toString("base64");
      const request = isSecure ? https.request : http2.request;
      const protocolSet = /* @__PURE__ */ new Set();
      let perMessageDeflate;
      opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
      opts.defaultPort = opts.defaultPort || defaultPort;
      opts.port = parsedUrl.port || defaultPort;
      opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
      opts.headers = {
        ...opts.headers,
        "Sec-WebSocket-Version": opts.protocolVersion,
        "Sec-WebSocket-Key": key,
        Connection: "Upgrade",
        Upgrade: "websocket"
      };
      opts.path = parsedUrl.pathname + parsedUrl.search;
      opts.timeout = opts.handshakeTimeout;
      if (opts.perMessageDeflate) {
        perMessageDeflate = new PerMessageDeflate2({
          ...opts.perMessageDeflate,
          isServer: false,
          maxPayload: opts.maxPayload
        });
        opts.headers["Sec-WebSocket-Extensions"] = format({
          [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
        });
      }
      if (protocols.length) {
        for (const protocol of protocols) {
          if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
            throw new SyntaxError(
              "An invalid or duplicated subprotocol was specified"
            );
          }
          protocolSet.add(protocol);
        }
        opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
      }
      if (opts.origin) {
        if (opts.protocolVersion < 13) {
          opts.headers["Sec-WebSocket-Origin"] = opts.origin;
        } else {
          opts.headers.Origin = opts.origin;
        }
      }
      if (parsedUrl.username || parsedUrl.password) {
        opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
      }
      if (isIpcUrl) {
        const parts = opts.path.split(":");
        opts.socketPath = parts[0];
        opts.path = parts[1];
      }
      let req;
      if (opts.followRedirects) {
        if (websocket._redirects === 0) {
          websocket._originalIpc = isIpcUrl;
          websocket._originalSecure = isSecure;
          websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
          const headers = options && options.headers;
          options = { ...options, headers: {} };
          if (headers) {
            for (const [key2, value] of Object.entries(headers)) {
              options.headers[key2.toLowerCase()] = value;
            }
          }
        } else if (websocket.listenerCount("redirect") === 0) {
          const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
          if (!isSameHost || websocket._originalSecure && !isSecure) {
            delete opts.headers.authorization;
            delete opts.headers.cookie;
            if (!isSameHost) delete opts.headers.host;
            opts.auth = void 0;
          }
        }
        if (opts.auth && !options.headers.authorization) {
          options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
        }
        req = websocket._req = request(opts);
        if (websocket._redirects) {
          websocket.emit("redirect", websocket.url, req);
        }
      } else {
        req = websocket._req = request(opts);
      }
      if (opts.timeout) {
        req.on("timeout", () => {
          abortHandshake(websocket, req, "Opening handshake has timed out");
        });
      }
      req.on("error", (err) => {
        if (req === null || req[kAborted]) return;
        req = websocket._req = null;
        emitErrorAndClose(websocket, err);
      });
      req.on("response", (res) => {
        const location = res.headers.location;
        const statusCode = res.statusCode;
        if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
          if (++websocket._redirects > opts.maxRedirects) {
            abortHandshake(websocket, req, "Maximum redirects exceeded");
            return;
          }
          req.abort();
          let addr;
          try {
            addr = new URL2(location, address2);
          } catch (e7) {
            const err = new SyntaxError(`Invalid URL: ${location}`);
            emitErrorAndClose(websocket, err);
            return;
          }
          initAsClient(websocket, addr, protocols, options);
        } else if (!websocket.emit("unexpected-response", req, res)) {
          abortHandshake(
            websocket,
            req,
            `Unexpected server response: ${res.statusCode}`
          );
        }
      });
      req.on("upgrade", (res, socket, head) => {
        websocket.emit("upgrade", res);
        if (websocket.readyState !== WebSocket2.CONNECTING) return;
        req = websocket._req = null;
        const upgrade = res.headers.upgrade;
        if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
          abortHandshake(websocket, socket, "Invalid Upgrade header");
          return;
        }
        const digest = createHash4("sha1").update(key + GUID).digest("base64");
        if (res.headers["sec-websocket-accept"] !== digest) {
          abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
          return;
        }
        const serverProt = res.headers["sec-websocket-protocol"];
        let protError;
        if (serverProt !== void 0) {
          if (!protocolSet.size) {
            protError = "Server sent a subprotocol but none was requested";
          } else if (!protocolSet.has(serverProt)) {
            protError = "Server sent an invalid subprotocol";
          }
        } else if (protocolSet.size) {
          protError = "Server sent no subprotocol";
        }
        if (protError) {
          abortHandshake(websocket, socket, protError);
          return;
        }
        if (serverProt) websocket._protocol = serverProt;
        const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
        if (secWebSocketExtensions !== void 0) {
          if (!perMessageDeflate) {
            const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
            abortHandshake(websocket, socket, message);
            return;
          }
          let extensions;
          try {
            extensions = parse(secWebSocketExtensions);
          } catch (err) {
            const message = "Invalid Sec-WebSocket-Extensions header";
            abortHandshake(websocket, socket, message);
            return;
          }
          const extensionNames = Object.keys(extensions);
          if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
            const message = "Server indicated an extension that was not requested";
            abortHandshake(websocket, socket, message);
            return;
          }
          try {
            perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
          } catch (err) {
            const message = "Invalid Sec-WebSocket-Extensions header";
            abortHandshake(websocket, socket, message);
            return;
          }
          websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
        }
        websocket.setSocket(socket, head, {
          allowSynchronousEvents: opts.allowSynchronousEvents,
          generateMask: opts.generateMask,
          maxPayload: opts.maxPayload,
          skipUTF8Validation: opts.skipUTF8Validation
        });
      });
      if (opts.finishRequest) {
        opts.finishRequest(req, websocket);
      } else {
        req.end();
      }
    }
    function emitErrorAndClose(websocket, err) {
      websocket._readyState = WebSocket2.CLOSING;
      websocket._errorEmitted = true;
      websocket.emit("error", err);
      websocket.emitClose();
    }
    function netConnect(options) {
      options.path = options.socketPath;
      return net.connect(options);
    }
    function tlsConnect(options) {
      options.path = void 0;
      if (!options.servername && options.servername !== "") {
        options.servername = net.isIP(options.host) ? "" : options.host;
      }
      return tls.connect(options);
    }
    function abortHandshake(websocket, stream, message) {
      websocket._readyState = WebSocket2.CLOSING;
      const err = new Error(message);
      Error.captureStackTrace(err, abortHandshake);
      if (stream.setHeader) {
        stream[kAborted] = true;
        stream.abort();
        if (stream.socket && !stream.socket.destroyed) {
          stream.socket.destroy();
        }
        process.nextTick(emitErrorAndClose, websocket, err);
      } else {
        stream.destroy(err);
        stream.once("error", websocket.emit.bind(websocket, "error"));
        stream.once("close", websocket.emitClose.bind(websocket));
      }
    }
    function sendAfterClose(websocket, data, cb) {
      if (data) {
        const length = isBlob(data) ? data.size : toBuffer(data).length;
        if (websocket._socket) websocket._sender._bufferedBytes += length;
        else websocket._bufferedAmount += length;
      }
      if (cb) {
        const err = new Error(
          `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
        );
        process.nextTick(cb, err);
      }
    }
    function receiverOnConclude(code, reason) {
      const websocket = this[kWebSocket];
      websocket._closeFrameReceived = true;
      websocket._closeMessage = reason;
      websocket._closeCode = code;
      if (websocket._socket[kWebSocket] === void 0) return;
      websocket._socket.removeListener("data", socketOnData);
      process.nextTick(resume, websocket._socket);
      if (code === 1005) websocket.close();
      else websocket.close(code, reason);
    }
    function receiverOnDrain() {
      const websocket = this[kWebSocket];
      if (!websocket.isPaused) websocket._socket.resume();
    }
    function receiverOnError(err) {
      const websocket = this[kWebSocket];
      if (websocket._socket[kWebSocket] !== void 0) {
        websocket._socket.removeListener("data", socketOnData);
        process.nextTick(resume, websocket._socket);
        websocket.close(err[kStatusCode]);
      }
      if (!websocket._errorEmitted) {
        websocket._errorEmitted = true;
        websocket.emit("error", err);
      }
    }
    function receiverOnFinish() {
      this[kWebSocket].emitClose();
    }
    function receiverOnMessage(data, isBinary) {
      this[kWebSocket].emit("message", data, isBinary);
    }
    function receiverOnPing(data) {
      const websocket = this[kWebSocket];
      if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
      websocket.emit("ping", data);
    }
    function receiverOnPong(data) {
      this[kWebSocket].emit("pong", data);
    }
    function resume(stream) {
      stream.resume();
    }
    function senderOnError(err) {
      const websocket = this[kWebSocket];
      if (websocket.readyState === WebSocket2.CLOSED) return;
      if (websocket.readyState === WebSocket2.OPEN) {
        websocket._readyState = WebSocket2.CLOSING;
        setCloseTimer(websocket);
      }
      this._socket.end();
      if (!websocket._errorEmitted) {
        websocket._errorEmitted = true;
        websocket.emit("error", err);
      }
    }
    function setCloseTimer(websocket) {
      websocket._closeTimer = setTimeout(
        websocket._socket.destroy.bind(websocket._socket),
        websocket._closeTimeout
      );
    }
    function socketOnClose() {
      const websocket = this[kWebSocket];
      this.removeListener("close", socketOnClose);
      this.removeListener("data", socketOnData);
      this.removeListener("end", socketOnEnd);
      websocket._readyState = WebSocket2.CLOSING;
      if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
        const chunk = this.read(this._readableState.length);
        websocket._receiver.write(chunk);
      }
      websocket._receiver.end();
      this[kWebSocket] = void 0;
      clearTimeout(websocket._closeTimer);
      if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
        websocket.emitClose();
      } else {
        websocket._receiver.on("error", receiverOnFinish);
        websocket._receiver.on("finish", receiverOnFinish);
      }
    }
    function socketOnData(chunk) {
      if (!this[kWebSocket]._receiver.write(chunk)) {
        this.pause();
      }
    }
    function socketOnEnd() {
      const websocket = this[kWebSocket];
      websocket._readyState = WebSocket2.CLOSING;
      websocket._receiver.end();
      this.end();
    }
    function socketOnError() {
      const websocket = this[kWebSocket];
      this.removeListener("error", socketOnError);
      this.on("error", NOOP);
      if (websocket) {
        websocket._readyState = WebSocket2.CLOSING;
        this.destroy();
      }
    }
  }
});

// node_modules/ws/lib/stream.js
var require_stream = __commonJS({
  "node_modules/ws/lib/stream.js"(exports, module) {
    "use strict";
    var WebSocket2 = require_websocket();
    var { Duplex } = __require("stream");
    function emitClose(stream) {
      stream.emit("close");
    }
    function duplexOnEnd() {
      if (!this.destroyed && this._writableState.finished) {
        this.destroy();
      }
    }
    function duplexOnError(err) {
      this.removeListener("error", duplexOnError);
      this.destroy();
      if (this.listenerCount("error") === 0) {
        this.emit("error", err);
      }
    }
    function createWebSocketStream2(ws, options) {
      let terminateOnDestroy = true;
      const duplex = new Duplex({
        ...options,
        autoDestroy: false,
        emitClose: false,
        objectMode: false,
        writableObjectMode: false
      });
      ws.on("message", function message(msg, isBinary) {
        const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
        if (!duplex.push(data)) ws.pause();
      });
      ws.once("error", function error(err) {
        if (duplex.destroyed) return;
        terminateOnDestroy = false;
        duplex.destroy(err);
      });
      ws.once("close", function close() {
        if (duplex.destroyed) return;
        duplex.push(null);
      });
      duplex._destroy = function(err, callback) {
        if (ws.readyState === ws.CLOSED) {
          callback(err);
          process.nextTick(emitClose, duplex);
          return;
        }
        let called = false;
        ws.once("error", function error(err2) {
          called = true;
          callback(err2);
        });
        ws.once("close", function close() {
          if (!called) callback(err);
          process.nextTick(emitClose, duplex);
        });
        if (terminateOnDestroy) ws.terminate();
      };
      duplex._final = function(callback) {
        if (ws.readyState === ws.CONNECTING) {
          ws.once("open", function open2() {
            duplex._final(callback);
          });
          return;
        }
        if (ws._socket === null) return;
        if (ws._socket._writableState.finished) {
          callback();
          if (duplex._readableState.endEmitted) duplex.destroy();
        } else {
          ws._socket.once("finish", function finish() {
            callback();
          });
          ws.close();
        }
      };
      duplex._read = function() {
        if (ws.isPaused) ws.resume();
      };
      duplex._write = function(chunk, encoding, callback) {
        if (ws.readyState === ws.CONNECTING) {
          ws.once("open", function open2() {
            duplex._write(chunk, encoding, callback);
          });
          return;
        }
        ws.send(chunk, callback);
      };
      duplex.on("end", duplexOnEnd);
      duplex.on("error", duplexOnError);
      return duplex;
    }
    module.exports = createWebSocketStream2;
  }
});

// node_modules/ws/lib/subprotocol.js
var require_subprotocol = __commonJS({
  "node_modules/ws/lib/subprotocol.js"(exports, module) {
    "use strict";
    var { tokenChars } = require_validation();
    function parse(header) {
      const protocols = /* @__PURE__ */ new Set();
      let start = -1;
      let end = -1;
      let i = 0;
      for (i; i < header.length; i++) {
        const code = header.charCodeAt(i);
        if (end === -1 && tokenChars[code] === 1) {
          if (start === -1) start = i;
        } else if (i !== 0 && (code === 32 || code === 9)) {
          if (end === -1 && start !== -1) end = i;
        } else if (code === 44) {
          if (start === -1) {
            throw new SyntaxError(`Unexpected character at index ${i}`);
          }
          if (end === -1) end = i;
          const protocol2 = header.slice(start, end);
          if (protocols.has(protocol2)) {
            throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
          }
          protocols.add(protocol2);
          start = end = -1;
        } else {
          throw new SyntaxError(`Unexpected character at index ${i}`);
        }
      }
      if (start === -1 || end !== -1) {
        throw new SyntaxError("Unexpected end of input");
      }
      const protocol = header.slice(start, i);
      if (protocols.has(protocol)) {
        throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
      }
      protocols.add(protocol);
      return protocols;
    }
    module.exports = { parse };
  }
});

// node_modules/ws/lib/websocket-server.js
var require_websocket_server = __commonJS({
  "node_modules/ws/lib/websocket-server.js"(exports, module) {
    "use strict";
    var EventEmitter = __require("events");
    var http2 = __require("http");
    var { Duplex } = __require("stream");
    var { createHash: createHash4 } = __require("crypto");
    var extension2 = require_extension();
    var PerMessageDeflate2 = require_permessage_deflate();
    var subprotocol2 = require_subprotocol();
    var WebSocket2 = require_websocket();
    var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
    var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
    var RUNNING = 0;
    var CLOSING = 1;
    var CLOSED = 2;
    var WebSocketServer2 = class extends EventEmitter {
      /**
       * Create a `WebSocketServer` instance.
       *
       * @param {Object} options Configuration options
       * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
       *     any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
       *     multiple times in the same tick
       * @param {Boolean} [options.autoPong=true] Specifies whether or not to
       *     automatically send a pong in response to a ping
       * @param {Number} [options.backlog=511] The maximum length of the queue of
       *     pending connections
       * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
       *     track clients
       * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
       *     wait for the closing handshake to finish after `websocket.close()` is
       *     called
       * @param {Function} [options.handleProtocols] A hook to handle protocols
       * @param {String} [options.host] The hostname where to bind the server
       * @param {Number} [options.maxPayload=104857600] The maximum allowed message
       *     size
       * @param {Boolean} [options.noServer=false] Enable no server mode
       * @param {String} [options.path] Accept only connections matching this path
       * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
       *     permessage-deflate
       * @param {Number} [options.port] The port where to bind the server
       * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
       *     server to use
       * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
       *     not to skip UTF-8 validation for text and close messages
       * @param {Function} [options.verifyClient] A hook to reject connections
       * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
       *     class to use. It must be the `WebSocket` class or class that extends it
       * @param {Function} [callback] A listener for the `listening` event
       */
      constructor(options, callback) {
        super();
        options = {
          allowSynchronousEvents: true,
          autoPong: true,
          maxPayload: 100 * 1024 * 1024,
          skipUTF8Validation: false,
          perMessageDeflate: false,
          handleProtocols: null,
          clientTracking: true,
          closeTimeout: CLOSE_TIMEOUT,
          verifyClient: null,
          noServer: false,
          backlog: null,
          // use default (511 as implemented in net.js)
          server: null,
          host: null,
          path: null,
          port: null,
          WebSocket: WebSocket2,
          ...options
        };
        if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
          throw new TypeError(
            'One and only one of the "port", "server", or "noServer" options must be specified'
          );
        }
        if (options.port != null) {
          this._server = http2.createServer((req, res) => {
            const body = http2.STATUS_CODES[426];
            res.writeHead(426, {
              "Content-Length": body.length,
              "Content-Type": "text/plain"
            });
            res.end(body);
          });
          this._server.listen(
            options.port,
            options.host,
            options.backlog,
            callback
          );
        } else if (options.server) {
          this._server = options.server;
        }
        if (this._server) {
          const emitConnection = this.emit.bind(this, "connection");
          this._removeListeners = addListeners(this._server, {
            listening: this.emit.bind(this, "listening"),
            error: this.emit.bind(this, "error"),
            upgrade: (req, socket, head) => {
              this.handleUpgrade(req, socket, head, emitConnection);
            }
          });
        }
        if (options.perMessageDeflate === true) options.perMessageDeflate = {};
        if (options.clientTracking) {
          this.clients = /* @__PURE__ */ new Set();
          this._shouldEmitClose = false;
        }
        this.options = options;
        this._state = RUNNING;
      }
      /**
       * Returns the bound address, the address family name, and port of the server
       * as reported by the operating system if listening on an IP socket.
       * If the server is listening on a pipe or UNIX domain socket, the name is
       * returned as a string.
       *
       * @return {(Object|String|null)} The address of the server
       * @public
       */
      address() {
        if (this.options.noServer) {
          throw new Error('The server is operating in "noServer" mode');
        }
        if (!this._server) return null;
        return this._server.address();
      }
      /**
       * Stop the server from accepting new connections and emit the `'close'` event
       * when all existing connections are closed.
       *
       * @param {Function} [cb] A one-time listener for the `'close'` event
       * @public
       */
      close(cb) {
        if (this._state === CLOSED) {
          if (cb) {
            this.once("close", () => {
              cb(new Error("The server is not running"));
            });
          }
          process.nextTick(emitClose, this);
          return;
        }
        if (cb) this.once("close", cb);
        if (this._state === CLOSING) return;
        this._state = CLOSING;
        if (this.options.noServer || this.options.server) {
          if (this._server) {
            this._removeListeners();
            this._removeListeners = this._server = null;
          }
          if (this.clients) {
            if (!this.clients.size) {
              process.nextTick(emitClose, this);
            } else {
              this._shouldEmitClose = true;
            }
          } else {
            process.nextTick(emitClose, this);
          }
        } else {
          const server = this._server;
          this._removeListeners();
          this._removeListeners = this._server = null;
          server.close(() => {
            emitClose(this);
          });
        }
      }
      /**
       * See if a given request should be handled by this server instance.
       *
       * @param {http.IncomingMessage} req Request object to inspect
       * @return {Boolean} `true` if the request is valid, else `false`
       * @public
       */
      shouldHandle(req) {
        if (this.options.path) {
          const index2 = req.url.indexOf("?");
          const pathname = index2 !== -1 ? req.url.slice(0, index2) : req.url;
          if (pathname !== this.options.path) return false;
        }
        return true;
      }
      /**
       * Handle a HTTP Upgrade request.
       *
       * @param {http.IncomingMessage} req The request object
       * @param {Duplex} socket The network socket between the server and client
       * @param {Buffer} head The first packet of the upgraded stream
       * @param {Function} cb Callback
       * @public
       */
      handleUpgrade(req, socket, head, cb) {
        socket.on("error", socketOnError);
        const key = req.headers["sec-websocket-key"];
        const upgrade = req.headers.upgrade;
        const version4 = +req.headers["sec-websocket-version"];
        if (req.method !== "GET") {
          const message = "Invalid HTTP method";
          abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
          return;
        }
        if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
          const message = "Invalid Upgrade header";
          abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
          return;
        }
        if (key === void 0 || !keyRegex.test(key)) {
          const message = "Missing or invalid Sec-WebSocket-Key header";
          abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
          return;
        }
        if (version4 !== 13 && version4 !== 8) {
          const message = "Missing or invalid Sec-WebSocket-Version header";
          abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
            "Sec-WebSocket-Version": "13, 8"
          });
          return;
        }
        if (!this.shouldHandle(req)) {
          abortHandshake(socket, 400);
          return;
        }
        const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
        let protocols = /* @__PURE__ */ new Set();
        if (secWebSocketProtocol !== void 0) {
          try {
            protocols = subprotocol2.parse(secWebSocketProtocol);
          } catch (err) {
            const message = "Invalid Sec-WebSocket-Protocol header";
            abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
            return;
          }
        }
        const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
        const extensions = {};
        if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
          const perMessageDeflate = new PerMessageDeflate2({
            ...this.options.perMessageDeflate,
            isServer: true,
            maxPayload: this.options.maxPayload
          });
          try {
            const offers = extension2.parse(secWebSocketExtensions);
            if (offers[PerMessageDeflate2.extensionName]) {
              perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
              extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
            }
          } catch (err) {
            const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
            abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
            return;
          }
        }
        if (this.options.verifyClient) {
          const info = {
            origin: req.headers[`${version4 === 8 ? "sec-websocket-origin" : "origin"}`],
            secure: !!(req.socket.authorized || req.socket.encrypted),
            req
          };
          if (this.options.verifyClient.length === 2) {
            this.options.verifyClient(info, (verified, code, message, headers) => {
              if (!verified) {
                return abortHandshake(socket, code || 401, message, headers);
              }
              this.completeUpgrade(
                extensions,
                key,
                protocols,
                req,
                socket,
                head,
                cb
              );
            });
            return;
          }
          if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
        }
        this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
      }
      /**
       * Upgrade the connection to WebSocket.
       *
       * @param {Object} extensions The accepted extensions
       * @param {String} key The value of the `Sec-WebSocket-Key` header
       * @param {Set} protocols The subprotocols
       * @param {http.IncomingMessage} req The request object
       * @param {Duplex} socket The network socket between the server and client
       * @param {Buffer} head The first packet of the upgraded stream
       * @param {Function} cb Callback
       * @throws {Error} If called more than once with the same socket
       * @private
       */
      completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
        if (!socket.readable || !socket.writable) return socket.destroy();
        if (socket[kWebSocket]) {
          throw new Error(
            "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
          );
        }
        if (this._state > RUNNING) return abortHandshake(socket, 503);
        const digest = createHash4("sha1").update(key + GUID).digest("base64");
        const headers = [
          "HTTP/1.1 101 Switching Protocols",
          "Upgrade: websocket",
          "Connection: Upgrade",
          `Sec-WebSocket-Accept: ${digest}`
        ];
        const ws = new this.options.WebSocket(null, void 0, this.options);
        if (protocols.size) {
          const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
          if (protocol) {
            headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
            ws._protocol = protocol;
          }
        }
        if (extensions[PerMessageDeflate2.extensionName]) {
          const params = extensions[PerMessageDeflate2.extensionName].params;
          const value = extension2.format({
            [PerMessageDeflate2.extensionName]: [params]
          });
          headers.push(`Sec-WebSocket-Extensions: ${value}`);
          ws._extensions = extensions;
        }
        this.emit("headers", headers, req);
        socket.write(headers.concat("\r\n").join("\r\n"));
        socket.removeListener("error", socketOnError);
        ws.setSocket(socket, head, {
          allowSynchronousEvents: this.options.allowSynchronousEvents,
          maxPayload: this.options.maxPayload,
          skipUTF8Validation: this.options.skipUTF8Validation
        });
        if (this.clients) {
          this.clients.add(ws);
          ws.on("close", () => {
            this.clients.delete(ws);
            if (this._shouldEmitClose && !this.clients.size) {
              process.nextTick(emitClose, this);
            }
          });
        }
        cb(ws, req);
      }
    };
    module.exports = WebSocketServer2;
    function addListeners(server, map) {
      for (const event of Object.keys(map)) server.on(event, map[event]);
      return function removeListeners() {
        for (const event of Object.keys(map)) {
          server.removeListener(event, map[event]);
        }
      };
    }
    function emitClose(server) {
      server._state = CLOSED;
      server.emit("close");
    }
    function socketOnError() {
      this.destroy();
    }
    function abortHandshake(socket, code, message, headers) {
      message = message || http2.STATUS_CODES[code];
      headers = {
        Connection: "close",
        "Content-Type": "text/html",
        "Content-Length": Buffer.byteLength(message),
        ...headers
      };
      socket.once("finish", socket.destroy);
      socket.end(
        `HTTP/1.1 ${code} ${http2.STATUS_CODES[code]}\r
` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
      );
    }
    function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
      if (server.listenerCount("wsClientError")) {
        const err = new Error(message);
        Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
        server.emit("wsClientError", err, socket, req);
      } else {
        abortHandshake(socket, code, message, headers);
      }
    }
  }
});

// node_modules/ws/wrapper.mjs
var import_stream, import_extension, import_permessage_deflate, import_receiver, import_sender, import_subprotocol, import_websocket, import_websocket_server, wrapper_default;
var init_wrapper = __esm({
  "node_modules/ws/wrapper.mjs"() {
    "use strict";
    import_stream = __toESM(require_stream(), 1);
    import_extension = __toESM(require_extension(), 1);
    import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
    import_receiver = __toESM(require_receiver(), 1);
    import_sender = __toESM(require_sender(), 1);
    import_subprotocol = __toESM(require_subprotocol(), 1);
    import_websocket = __toESM(require_websocket(), 1);
    import_websocket_server = __toESM(require_websocket_server(), 1);
    wrapper_default = import_websocket.default;
  }
});

// node_modules/@solana/rpc-subscriptions-channel-websocket/dist/index.node.mjs
import { setMaxListeners as setMaxListeners4 } from "events";
function createWebSocketChannel({
  sendBufferHighWatermark,
  signal,
  url
}) {
  if (signal.aborted) {
    return Promise.reject(signal.reason);
  }
  let bufferDrainWatcher;
  let hasConnected = false;
  const listenerRemovers = /* @__PURE__ */ new Set();
  function cleanupListeners() {
    listenerRemovers.forEach((r) => {
      r();
    });
    listenerRemovers.clear();
  }
  function handleAbort() {
    cleanupListeners();
    if (!hasConnected) {
      rejectOpen(signal.reason);
    }
    if (webSocket.readyState !== l.CLOSED && webSocket.readyState !== l.CLOSING) {
      webSocket.close(NORMAL_CLOSURE_CODE);
    }
  }
  function handleClose(ev) {
    cleanupListeners();
    bufferDrainWatcher?.onCancel();
    signal.removeEventListener("abort", handleAbort);
    webSocket.removeEventListener("close", handleClose);
    webSocket.removeEventListener("error", handleError);
    webSocket.removeEventListener("message", handleMessage);
    webSocket.removeEventListener("open", handleOpen);
    if (!signal.aborted && !(ev.wasClean && ev.code === NORMAL_CLOSURE_CODE)) {
      eventTarget.dispatchEvent(
        new CustomEvent("error", {
          detail: new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED, {
            cause: ev
          })
        })
      );
    }
  }
  function handleError(ev) {
    if (signal.aborted) {
      return;
    }
    if (!hasConnected) {
      const failedToConnectError = new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT, {
        errorEvent: ev
      });
      rejectOpen(failedToConnectError);
      eventTarget.dispatchEvent(
        new CustomEvent("error", {
          detail: failedToConnectError
        })
      );
    }
  }
  function handleMessage(ev) {
    if (signal.aborted) {
      return;
    }
    eventTarget.dispatchEvent(new CustomEvent("message", { detail: ev.data }));
  }
  const eventTarget = new s2();
  const dataPublisher = getDataPublisherFromEventEmitter(eventTarget);
  function handleOpen() {
    hasConnected = true;
    resolveOpen({
      ...dataPublisher,
      async send(message) {
        if (webSocket.readyState !== l.OPEN) {
          throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED);
        }
        if (!bufferDrainWatcher && webSocket.bufferedAmount > sendBufferHighWatermark) {
          let onCancel;
          const promise = new Promise((resolve, reject) => {
            const intervalId = setInterval(() => {
              if (webSocket.readyState !== l.OPEN || !(webSocket.bufferedAmount > sendBufferHighWatermark)) {
                clearInterval(intervalId);
                bufferDrainWatcher = void 0;
                resolve();
              }
            }, 16);
            onCancel = () => {
              bufferDrainWatcher = void 0;
              clearInterval(intervalId);
              reject(
                new SolanaError(
                  SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED
                )
              );
            };
          });
          bufferDrainWatcher = {
            onCancel,
            promise
          };
        }
        if (bufferDrainWatcher) {
          if (ArrayBuffer.isView(message) && !(message instanceof DataView)) {
            const TypedArrayConstructor = message.constructor;
            message = new TypedArrayConstructor(message);
          }
          await bufferDrainWatcher.promise;
        }
        webSocket.send(message);
      }
    });
  }
  const webSocket = new l(url);
  signal.addEventListener("abort", handleAbort);
  webSocket.addEventListener("close", handleClose);
  webSocket.addEventListener("error", handleError);
  webSocket.addEventListener("message", handleMessage);
  webSocket.addEventListener("open", handleOpen);
  let rejectOpen;
  let resolveOpen;
  return new Promise((resolve, reject) => {
    rejectOpen = reject;
    resolveOpen = resolve;
  });
}
var s2, l, NORMAL_CLOSURE_CODE;
var init_index_node33 = __esm({
  "node_modules/@solana/rpc-subscriptions-channel-websocket/dist/index.node.mjs"() {
    "use strict";
    init_index_node();
    init_index_node30();
    init_wrapper();
    s2 = class extends globalThis.EventTarget {
      constructor(...t) {
        super(...t), setMaxListeners4(Number.MAX_SAFE_INTEGER, this);
      }
    };
    l = globalThis.WebSocket ? globalThis.WebSocket : wrapper_default;
    NORMAL_CLOSURE_CODE = 1e3;
  }
});

// node_modules/@solana/rpc-subscriptions/dist/index.node.mjs
import { setMaxListeners as setMaxListeners5 } from "events";
function createSolanaJsonRpcIntegerOverflowError2(methodName, keyPath, value) {
  let argumentLabel = "";
  if (typeof keyPath[0] === "number") {
    const argPosition = keyPath[0] + 1;
    const lastDigit = argPosition % 10;
    const lastTwoDigits = argPosition % 100;
    if (lastDigit == 1 && lastTwoDigits != 11) {
      argumentLabel = argPosition + "st";
    } else if (lastDigit == 2 && lastTwoDigits != 12) {
      argumentLabel = argPosition + "nd";
    } else if (lastDigit == 3 && lastTwoDigits != 13) {
      argumentLabel = argPosition + "rd";
    } else {
      argumentLabel = argPosition + "th";
    }
  } else {
    argumentLabel = `\`${keyPath[0].toString()}\``;
  }
  const path2 = keyPath.length > 1 ? keyPath.slice(1).map((pathPart) => typeof pathPart === "number" ? `[${pathPart}]` : pathPart).join(".") : void 0;
  const error = new SolanaError(SOLANA_ERROR__RPC__INTEGER_OVERFLOW, {
    argumentLabel,
    keyPath,
    methodName,
    optionalPathLabel: path2 ? ` at path \`${path2}\`` : "",
    value,
    ...path2 !== void 0 ? { path: path2 } : void 0
  });
  safeCaptureStackTrace(error, createSolanaJsonRpcIntegerOverflowError2);
  return error;
}
function getRpcSubscriptionsChannelWithAutoping({
  abortSignal: callerAbortSignal,
  channel,
  intervalMs
}) {
  let intervalId;
  function sendPing() {
    channel.send(PING_PAYLOAD).catch((e22) => {
      if (isSolanaError(e22, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED)) {
        pingerAbortController.abort();
      }
    });
  }
  function restartPingTimer() {
    clearInterval(intervalId);
    intervalId = setInterval(sendPing, intervalMs);
  }
  const pingerAbortController = new e5();
  pingerAbortController.signal.addEventListener("abort", () => {
    clearInterval(intervalId);
  });
  callerAbortSignal.addEventListener("abort", () => {
    pingerAbortController.abort();
  });
  channel.on(
    "error",
    () => {
      pingerAbortController.abort();
    },
    { signal: pingerAbortController.signal }
  );
  channel.on("message", restartPingTimer, { signal: pingerAbortController.signal });
  {
    restartPingTimer();
  }
  return {
    ...channel,
    send(...args) {
      if (!pingerAbortController.signal.aborted) {
        restartPingTimer();
      }
      return channel.send(...args);
    }
  };
}
function createChannelPool() {
  return {
    entries: [],
    freeChannelIndex: -1
  };
}
function getChannelPoolingChannelCreator(createChannel, { maxSubscriptionsPerChannel, minChannels }) {
  const pool = createChannelPool();
  function recomputeFreeChannelIndex() {
    if (pool.entries.length < minChannels) {
      pool.freeChannelIndex = -1;
      return;
    }
    let mostFreeChannel;
    for (let ii = 0; ii < pool.entries.length; ii++) {
      const nextPoolIndex = (pool.freeChannelIndex + ii + 2) % pool.entries.length;
      const nextPoolEntry = (
        // Start from the item two positions after the current item. This way, the
        // search will finish on the item after the current one. This ensures that, if
        // any channels tie for having the most capacity, the one that will be chosen is
        // the one immediately to the current one's right (wrapping around).
        pool.entries[nextPoolIndex]
      );
      if (nextPoolEntry.subscriptionCount < maxSubscriptionsPerChannel && (!mostFreeChannel || mostFreeChannel.subscriptionCount >= nextPoolEntry.subscriptionCount)) {
        mostFreeChannel = {
          poolIndex: nextPoolIndex,
          subscriptionCount: nextPoolEntry.subscriptionCount
        };
      }
    }
    pool.freeChannelIndex = mostFreeChannel?.poolIndex ?? -1;
  }
  return function getExistingChannelWithMostCapacityOrCreateChannel({ abortSignal }) {
    let poolEntry;
    function destroyPoolEntry() {
      const index2 = pool.entries.findIndex((entry) => entry === poolEntry);
      pool.entries.splice(index2, 1);
      poolEntry.dispose();
      recomputeFreeChannelIndex();
    }
    if (pool.freeChannelIndex === -1) {
      const abortController = new e5();
      const newChannelPromise = createChannel({ abortSignal: abortController.signal });
      newChannelPromise.then((newChannel) => {
        newChannel.on("error", destroyPoolEntry, { signal: abortController.signal });
      }).catch(destroyPoolEntry);
      poolEntry = {
        channel: newChannelPromise,
        dispose() {
          abortController.abort();
        },
        subscriptionCount: 0
      };
      pool.entries.push(poolEntry);
    } else {
      poolEntry = pool.entries[pool.freeChannelIndex];
    }
    poolEntry.subscriptionCount++;
    abortSignal.addEventListener("abort", function destroyConsumer() {
      poolEntry.subscriptionCount--;
      if (poolEntry.subscriptionCount === 0) {
        destroyPoolEntry();
      } else if (pool.freeChannelIndex !== -1) {
        pool.freeChannelIndex--;
        recomputeFreeChannelIndex();
      }
    });
    recomputeFreeChannelIndex();
    return poolEntry.channel;
  };
}
function getRpcSubscriptionsChannelWithJSONSerialization(channel) {
  return pipe(
    channel,
    (c) => transformChannelInboundMessages(c, JSON.parse),
    (c) => transformChannelOutboundMessages(c, JSON.stringify)
  );
}
function getRpcSubscriptionsChannelWithBigIntJSONSerialization(channel) {
  return pipe(
    channel,
    (c) => transformChannelInboundMessages(c, parseJsonWithBigInts),
    (c) => transformChannelOutboundMessages(c, stringifyJsonWithBigInts)
  );
}
function createDefaultSolanaRpcSubscriptionsChannelCreator(config) {
  return createDefaultRpcSubscriptionsChannelCreatorImpl({
    ...config,
    jsonSerializer: getRpcSubscriptionsChannelWithBigIntJSONSerialization
  });
}
function createDefaultRpcSubscriptionsChannelCreator(config) {
  return createDefaultRpcSubscriptionsChannelCreatorImpl({
    ...config,
    jsonSerializer: getRpcSubscriptionsChannelWithJSONSerialization
  });
}
function createDefaultRpcSubscriptionsChannelCreatorImpl(config) {
  if (/^wss?:/i.test(config.url) === false) {
    const protocolMatch = config.url.match(/^([^:]+):/);
    throw new DOMException(
      protocolMatch ? `Failed to construct 'WebSocket': The URL's scheme must be either 'ws' or 'wss'. '${protocolMatch[1]}:' is not allowed.` : `Failed to construct 'WebSocket': The URL '${config.url}' is invalid.`
    );
  }
  const { intervalMs, ...rest } = config;
  const createDefaultRpcSubscriptionsChannel = (({ abortSignal }) => {
    return createWebSocketChannel({
      ...rest,
      sendBufferHighWatermark: config.sendBufferHighWatermark ?? // Let 128KB of data into the WebSocket buffer before buffering it in the app.
      131072,
      signal: abortSignal
    }).then(config.jsonSerializer).then(
      (channel) => getRpcSubscriptionsChannelWithAutoping({
        abortSignal,
        channel,
        intervalMs: intervalMs ?? 5e3
      })
    );
  });
  return getChannelPoolingChannelCreator(createDefaultRpcSubscriptionsChannel, {
    maxSubscriptionsPerChannel: config.maxSubscriptionsPerChannel ?? /**
    * A note about this default. The idea here is that, because some RPC providers impose
    * an upper limit on the number of subscriptions you can make per channel, we must
    * choose a number low enough to avoid hitting that limit. Without knowing what provider
    * a given person is using, or what their limit is, we have to choose the lowest of all
    * known limits. As of this writing (October 2024) that is the public mainnet RPC node
    * (api.mainnet-beta.solana.com) at 100 subscriptions.
    */
    100,
    minChannels: config.minChannels ?? 1
  });
}
function getRpcSubscriptionsTransportWithSubscriptionCoalescing(transport) {
  const cache2 = /* @__PURE__ */ new Map();
  return function rpcSubscriptionsTransportWithSubscriptionCoalescing(config) {
    const { request, signal } = config;
    const subscriptionConfigurationHash = index_default([request.methodName, request.params]);
    let cachedDataPublisherPromise = cache2.get(subscriptionConfigurationHash);
    if (!cachedDataPublisherPromise) {
      const abortController = new e5();
      const dataPublisherPromise = transport({
        ...config,
        signal: abortController.signal
      });
      dataPublisherPromise.then((dataPublisher) => {
        dataPublisher.on(
          "error",
          () => {
            cache2.delete(subscriptionConfigurationHash);
            abortController.abort();
          },
          { signal: abortController.signal }
        );
      }).catch(() => {
      });
      cache2.set(
        subscriptionConfigurationHash,
        cachedDataPublisherPromise = {
          abortController,
          dataPublisherPromise,
          numSubscribers: 0
        }
      );
    }
    cachedDataPublisherPromise.numSubscribers++;
    signal.addEventListener(
      "abort",
      () => {
        cachedDataPublisherPromise.numSubscribers--;
        if (cachedDataPublisherPromise.numSubscribers === 0) {
          queueMicrotask(() => {
            if (cachedDataPublisherPromise.numSubscribers === 0) {
              cache2.delete(subscriptionConfigurationHash);
              cachedDataPublisherPromise.abortController.abort();
            }
          });
        }
      },
      { signal: cachedDataPublisherPromise.abortController.signal }
    );
    return cachedDataPublisherPromise.dataPublisherPromise;
  };
}
function createDefaultRpcSubscriptionsTransport({
  createChannel
}) {
  return pipe(
    createRpcSubscriptionsTransportFromChannelCreator(
      createChannel
    ),
    (transport) => getRpcSubscriptionsTransportWithSubscriptionCoalescing(transport)
  );
}
function createRpcSubscriptionsTransportFromChannelCreator(createChannel) {
  return (async ({ execute, signal }) => {
    const channel = await createChannel({ abortSignal: signal });
    return await execute({ channel, signal });
  });
}
function createSolanaRpcSubscriptionsImpl(clusterUrl, config) {
  const transport = createDefaultRpcSubscriptionsTransport({
    createChannel: createDefaultSolanaRpcSubscriptionsChannelCreator({ ...config, url: clusterUrl })
  });
  return createSolanaRpcSubscriptionsFromTransport(transport);
}
function createSolanaRpcSubscriptions(clusterUrl, config) {
  return createSolanaRpcSubscriptionsImpl(clusterUrl, config);
}
function createSolanaRpcSubscriptions_UNSTABLE(clusterUrl, config) {
  return createSolanaRpcSubscriptionsImpl(
    clusterUrl,
    config
  );
}
function createSolanaRpcSubscriptionsFromTransport(transport) {
  return createSubscriptionRpc({
    api: createSolanaRpcSubscriptionsApi(DEFAULT_RPC_SUBSCRIPTIONS_CONFIG),
    transport
  });
}
var DEFAULT_RPC_SUBSCRIPTIONS_CONFIG, e5, PING_PAYLOAD;
var init_index_node34 = __esm({
  "node_modules/@solana/rpc-subscriptions/dist/index.node.mjs"() {
    "use strict";
    init_index_node32();
    init_index_node32();
    init_index_node31();
    init_index_node31();
    init_index_node();
    init_index_node33();
    init_index_node11();
    init_index_node22();
    init_index_node27();
    DEFAULT_RPC_SUBSCRIPTIONS_CONFIG = {
      defaultCommitment: "confirmed",
      onIntegerOverflow(request, keyPath, value) {
        throw createSolanaJsonRpcIntegerOverflowError2(request.methodName, keyPath, value);
      }
    };
    e5 = class extends globalThis.AbortController {
      constructor(...t) {
        super(...t), setMaxListeners5(Number.MAX_SAFE_INTEGER, this.signal);
      }
    };
    PING_PAYLOAD = {
      jsonrpc: "2.0",
      method: "ping"
    };
  }
});

// node_modules/@solana/signers/dist/index.node.mjs
function deduplicateSigners(signers) {
  const deduplicated = {};
  signers.forEach((signer) => {
    if (!deduplicated[signer.address]) {
      deduplicated[signer.address] = signer;
    } else if (deduplicated[signer.address] !== signer) {
      throw new SolanaError(SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS, {
        address: signer.address
      });
    }
  });
  return Object.values(deduplicated);
}
function isTransactionModifyingSigner(value) {
  return "modifyAndSignTransactions" in value && typeof value.modifyAndSignTransactions === "function";
}
function assertIsTransactionModifyingSigner(value) {
  if (!isTransactionModifyingSigner(value)) {
    throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER, {
      address: value.address
    });
  }
}
function isTransactionPartialSigner(value) {
  return "signTransactions" in value && typeof value.signTransactions === "function";
}
function assertIsTransactionPartialSigner(value) {
  if (!isTransactionPartialSigner(value)) {
    throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER, {
      address: value.address
    });
  }
}
function isTransactionSendingSigner(value) {
  return "signAndSendTransactions" in value && typeof value.signAndSendTransactions === "function";
}
function assertIsTransactionSendingSigner(value) {
  if (!isTransactionSendingSigner(value)) {
    throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER, {
      address: value.address
    });
  }
}
function isTransactionSigner(value) {
  return isTransactionPartialSigner(value) || isTransactionModifyingSigner(value) || isTransactionSendingSigner(value);
}
function assertIsTransactionSigner(value) {
  if (!isTransactionSigner(value)) {
    throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER, {
      address: value.address
    });
  }
}
function getSignersFromInstruction(instruction) {
  return deduplicateSigners(
    (instruction.accounts ?? []).flatMap((account) => "signer" in account ? account.signer : [])
  );
}
function getSignersFromTransactionMessage(transaction) {
  return deduplicateSigners([
    ...transaction.feePayer && isTransactionSigner(transaction.feePayer) ? [transaction.feePayer] : [],
    ...transaction.instructions.flatMap(getSignersFromInstruction)
  ]);
}
function addSignersToInstruction(signers, instruction) {
  if (!instruction.accounts || instruction.accounts.length === 0) {
    return instruction;
  }
  const signerByAddress = new Map(deduplicateSigners(signers).map((signer) => [signer.address, signer]));
  return Object.freeze({
    ...instruction,
    accounts: instruction.accounts.map((account) => {
      const signer = signerByAddress.get(account.address);
      if (!isSignerRole(account.role) || "signer" in account || !signer) {
        return account;
      }
      return Object.freeze({ ...account, signer });
    })
  });
}
function addSignersToTransactionMessage(signers, transactionMessage) {
  const feePayerSigner = hasAddressOnlyFeePayer(transactionMessage) ? signers.find((signer) => signer.address === transactionMessage.feePayer.address) : void 0;
  if (!feePayerSigner && transactionMessage.instructions.length === 0) {
    return transactionMessage;
  }
  return Object.freeze({
    ...transactionMessage,
    ...feePayerSigner ? { feePayer: feePayerSigner } : null,
    instructions: transactionMessage.instructions.map((instruction) => addSignersToInstruction(signers, instruction))
  });
}
function hasAddressOnlyFeePayer(message) {
  return !!message && "feePayer" in message && !!message.feePayer && typeof message.feePayer.address === "string" && !isTransactionSigner(message.feePayer);
}
function setTransactionMessageFeePayerSigner(feePayer, transactionMessage) {
  Object.freeze(feePayer);
  const out = { ...transactionMessage, feePayer };
  Object.freeze(out);
  return out;
}
function isMessagePartialSigner(value) {
  return "signMessages" in value && typeof value.signMessages === "function";
}
function assertIsMessagePartialSigner(value) {
  if (!isMessagePartialSigner(value)) {
    throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER, {
      address: value.address
    });
  }
}
function isKeyPairSigner(value) {
  return "keyPair" in value && typeof value.keyPair === "object" && isMessagePartialSigner(value) && isTransactionPartialSigner(value);
}
function assertIsKeyPairSigner(value) {
  if (!isKeyPairSigner(value)) {
    throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER, {
      address: value.address
    });
  }
}
async function createSignerFromKeyPair(keyPair) {
  const address2 = await getAddressFromPublicKey(keyPair.publicKey);
  const out = {
    address: address2,
    keyPair,
    signMessages: (messages) => Promise.all(
      messages.map(
        async (message) => Object.freeze({ [address2]: await signBytes(keyPair.privateKey, message.content) })
      )
    ),
    signTransactions: (transactions) => Promise.all(
      transactions.map(async (transaction) => {
        const signedTransaction = await partiallySignTransaction([keyPair], transaction);
        return Object.freeze({ [address2]: signedTransaction.signatures[address2] });
      })
    )
  };
  return Object.freeze(out);
}
async function generateKeyPairSigner() {
  return await createSignerFromKeyPair(await generateKeyPair());
}
async function createKeyPairSignerFromBytes(bytes, extractable) {
  return await createSignerFromKeyPair(await createKeyPairFromBytes(bytes, extractable));
}
async function createKeyPairSignerFromPrivateKeyBytes(bytes, extractable) {
  return await createSignerFromKeyPair(await createKeyPairFromPrivateKeyBytes(bytes, extractable));
}
function isMessageModifyingSigner(value) {
  return isAddress2(value.address) && "modifyAndSignMessages" in value && typeof value.modifyAndSignMessages === "function";
}
function assertIsMessageModifyingSigner(value) {
  if (!isMessageModifyingSigner(value)) {
    throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER, {
      address: value.address
    });
  }
}
function isMessageSigner(value) {
  return isMessagePartialSigner(value) || isMessageModifyingSigner(value);
}
function assertIsMessageSigner(value) {
  if (!isMessageSigner(value)) {
    throw new SolanaError(SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER, {
      address: value.address
    });
  }
}
function createNoopSigner(address2) {
  const out = {
    address: address2,
    signMessages: (messages) => Promise.resolve(messages.map(() => Object.freeze({}))),
    signTransactions: (transactions) => Promise.resolve(transactions.map(() => Object.freeze({})))
  };
  return Object.freeze(out);
}
function getSignersFromOffchainMessage({
  requiredSignatories
}) {
  const messageSigners = requiredSignatories.filter(isMessageSigner);
  return deduplicateSigners(messageSigners);
}
async function partiallySignOffchainMessageWithSigners(offchainMessage, config) {
  const { partialSigners, modifyingSigners } = categorizeMessageSigners(
    getSignersFromOffchainMessage(offchainMessage)
  );
  return await signModifyingAndPartialMessageSigners(offchainMessage, modifyingSigners, partialSigners, config);
}
async function signOffchainMessageWithSigners(offchainMessage, config) {
  const signedOffchainMessageEnvelope = await partiallySignOffchainMessageWithSigners(offchainMessage, config);
  assertIsFullySignedOffchainMessageEnvelope(signedOffchainMessageEnvelope);
  return signedOffchainMessageEnvelope;
}
function categorizeMessageSigners(signers) {
  const modifyingSigners = identifyMessageModifyingSigners(signers);
  const partialSigners = signers.filter(isMessagePartialSigner).filter((signer) => !modifyingSigners.includes(signer));
  return Object.freeze({ modifyingSigners, partialSigners });
}
function identifyMessageModifyingSigners(signers) {
  const modifyingSigners = signers.filter(isMessageModifyingSigner);
  if (modifyingSigners.length === 0) return [];
  const nonPartialSigners = modifyingSigners.filter((signer) => !isMessagePartialSigner(signer));
  if (nonPartialSigners.length > 0) return nonPartialSigners;
  return [modifyingSigners[0]];
}
async function signModifyingAndPartialMessageSigners(offchainMessage, modifyingSigners = [], partialSigners = [], config) {
  const offchainMessageEnvelope = compileOffchainMessageEnvelope(offchainMessage);
  const modifiedOffchainMessage = await modifyingSigners.reduce(async (offchainMessageEnvelope2, modifyingSigner) => {
    config?.abortSignal?.throwIfAborted();
    const [message] = await modifyingSigner.modifyAndSignMessages([await offchainMessageEnvelope2], config);
    return Object.freeze(message);
  }, Promise.resolve(offchainMessageEnvelope));
  config?.abortSignal?.throwIfAborted();
  const signatureDictionaries = await Promise.all(
    partialSigners.map(async (partialSigner) => {
      const [signatures] = await partialSigner.signMessages([modifiedOffchainMessage], config);
      return signatures;
    })
  );
  return Object.freeze({
    ...modifiedOffchainMessage,
    signatures: Object.freeze(
      signatureDictionaries.reduce((signatures, signatureDictionary) => {
        return { ...signatures, ...signatureDictionary };
      }, modifiedOffchainMessage.signatures ?? {})
    )
  });
}
function isTransactionMessageWithSingleSendingSigner(transaction) {
  try {
    assertIsTransactionMessageWithSingleSendingSigner(transaction);
    return true;
  } catch {
    return false;
  }
}
function assertIsTransactionMessageWithSingleSendingSigner(transaction) {
  const signers = getSignersFromTransactionMessage(transaction);
  const sendingSigners = signers.filter(isTransactionSendingSigner);
  if (sendingSigners.length === 0) {
    throw new SolanaError(SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING);
  }
  const sendingOnlySigners = sendingSigners.filter(
    (signer) => !isTransactionPartialSigner(signer) && !isTransactionModifyingSigner(signer)
  );
  if (sendingOnlySigners.length > 1) {
    throw new SolanaError(SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS);
  }
}
async function partiallySignTransactionMessageWithSigners(transactionMessage, config) {
  const { partialSigners, modifyingSigners } = categorizeTransactionSigners(
    deduplicateSigners(getSignersFromTransactionMessage(transactionMessage).filter(isTransactionSigner)),
    { identifySendingSigner: false }
  );
  return await signModifyingAndPartialTransactionSigners(
    transactionMessage,
    modifyingSigners,
    partialSigners,
    config
  );
}
async function signTransactionMessageWithSigners(transactionMessage, config) {
  const signedTransaction = await partiallySignTransactionMessageWithSigners(transactionMessage, config);
  assertIsFullySignedTransaction(signedTransaction);
  return signedTransaction;
}
async function signAndSendTransactionMessageWithSigners(transaction, config) {
  assertIsTransactionMessageWithSingleSendingSigner(transaction);
  const abortSignal = config?.abortSignal;
  const { partialSigners, modifyingSigners, sendingSigner } = categorizeTransactionSigners(
    deduplicateSigners(getSignersFromTransactionMessage(transaction).filter(isTransactionSigner))
  );
  abortSignal?.throwIfAborted();
  const signedTransaction = await signModifyingAndPartialTransactionSigners(
    transaction,
    modifyingSigners,
    partialSigners,
    config
  );
  if (!sendingSigner) {
    throw new SolanaError(SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING);
  }
  abortSignal?.throwIfAborted();
  const [signature2] = await sendingSigner.signAndSendTransactions([signedTransaction], config);
  abortSignal?.throwIfAborted();
  return signature2;
}
function categorizeTransactionSigners(signers, config = {}) {
  const identifySendingSigner = config.identifySendingSigner ?? true;
  const sendingSigner = identifySendingSigner ? identifyTransactionSendingSigner(signers) : null;
  const otherSigners = signers.filter(
    (signer) => signer !== sendingSigner && (isTransactionModifyingSigner(signer) || isTransactionPartialSigner(signer))
  );
  const modifyingSigners = identifyTransactionModifyingSigners(otherSigners);
  const partialSigners = otherSigners.filter(isTransactionPartialSigner).filter((signer) => !modifyingSigners.includes(signer));
  return Object.freeze({ modifyingSigners, partialSigners, sendingSigner });
}
function identifyTransactionSendingSigner(signers) {
  const sendingSigners = signers.filter(isTransactionSendingSigner);
  if (sendingSigners.length === 0) return null;
  const sendingOnlySigners = sendingSigners.filter(
    (signer) => !isTransactionModifyingSigner(signer) && !isTransactionPartialSigner(signer)
  );
  if (sendingOnlySigners.length > 0) {
    return sendingOnlySigners[0];
  }
  return sendingSigners[0];
}
function identifyTransactionModifyingSigners(signers) {
  const modifyingSigners = signers.filter(isTransactionModifyingSigner);
  if (modifyingSigners.length === 0) return [];
  const nonPartialSigners = modifyingSigners.filter((signer) => !isTransactionPartialSigner(signer));
  if (nonPartialSigners.length > 0) return nonPartialSigners;
  return [modifyingSigners[0]];
}
async function signModifyingAndPartialTransactionSigners(transactionMessage, modifyingSigners = [], partialSigners = [], config) {
  const transaction = compileTransaction(transactionMessage);
  const modifiedTransaction = await modifyingSigners.reduce(
    async (transaction2, modifyingSigner) => {
      config?.abortSignal?.throwIfAborted();
      const [tx] = await modifyingSigner.modifyAndSignTransactions([await transaction2], config);
      return Object.freeze(tx);
    },
    Promise.resolve(transaction)
  );
  config?.abortSignal?.throwIfAborted();
  const signatureDictionaries = await Promise.all(
    partialSigners.map(async (partialSigner) => {
      const [signatures] = await partialSigner.signTransactions([modifiedTransaction], config);
      return signatures;
    })
  );
  return Object.freeze({
    ...modifiedTransaction,
    signatures: Object.freeze(
      signatureDictionaries.reduce((signatures, signatureDictionary) => {
        return { ...signatures, ...signatureDictionary };
      }, modifiedTransaction.signatures ?? {})
    )
  });
}
function createSignableMessage(content, signatures = {}) {
  return Object.freeze({
    content: typeof content === "string" ? new o2().encode(content) : content,
    signatures: Object.freeze({ ...signatures })
  });
}
var o2;
var init_index_node35 = __esm({
  "node_modules/@solana/signers/dist/index.node.mjs"() {
    "use strict";
    init_index_node();
    init_index_node12();
    init_index_node6();
    init_index_node15();
    init_index_node16();
    init_index_node19();
    o2 = globalThis.TextEncoder;
  }
});

// node_modules/@solana/transaction-confirmation/dist/index.node.mjs
import { setMaxListeners as setMaxListeners6 } from "events";
function createBlockHeightExceedencePromiseFactory({
  rpc,
  rpcSubscriptions
}) {
  return async function getBlockHeightExceedencePromise({
    abortSignal: callerAbortSignal,
    commitment,
    lastValidBlockHeight
  }) {
    callerAbortSignal.throwIfAborted();
    const abortController = new e6();
    const handleAbort = () => {
      abortController.abort();
    };
    callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
    async function getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight() {
      const { absoluteSlot, blockHeight } = await rpc.getEpochInfo({ commitment }).send({ abortSignal: abortController.signal });
      return {
        blockHeight,
        differenceBetweenSlotHeightAndBlockHeight: absoluteSlot - blockHeight
      };
    }
    try {
      const [slotNotifications, { blockHeight: initialBlockHeight, differenceBetweenSlotHeightAndBlockHeight }] = await Promise.all([
        rpcSubscriptions.slotNotifications().subscribe({ abortSignal: abortController.signal }),
        getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight()
      ]);
      callerAbortSignal.throwIfAborted();
      let currentBlockHeight = initialBlockHeight;
      if (currentBlockHeight <= lastValidBlockHeight) {
        let lastKnownDifferenceBetweenSlotHeightAndBlockHeight = differenceBetweenSlotHeightAndBlockHeight;
        for await (const slotNotification of slotNotifications) {
          const { slot } = slotNotification;
          if (slot - lastKnownDifferenceBetweenSlotHeightAndBlockHeight > lastValidBlockHeight) {
            const {
              blockHeight: recheckedBlockHeight,
              differenceBetweenSlotHeightAndBlockHeight: currentDifferenceBetweenSlotHeightAndBlockHeight
            } = await getBlockHeightAndDifferenceBetweenSlotHeightAndBlockHeight();
            currentBlockHeight = recheckedBlockHeight;
            if (currentBlockHeight > lastValidBlockHeight) {
              break;
            } else {
              lastKnownDifferenceBetweenSlotHeightAndBlockHeight = currentDifferenceBetweenSlotHeightAndBlockHeight;
            }
          }
        }
      }
      callerAbortSignal.throwIfAborted();
      throw new SolanaError(SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED, {
        currentBlockHeight,
        lastValidBlockHeight
      });
    } finally {
      abortController.abort();
    }
  };
}
function createNonceInvalidationPromiseFactory({
  rpc,
  rpcSubscriptions
}) {
  return async function getNonceInvalidationPromise({
    abortSignal: callerAbortSignal,
    commitment,
    currentNonceValue: expectedNonceValue,
    nonceAccountAddress
  }) {
    const abortController = new e6();
    function handleAbort() {
      abortController.abort();
    }
    callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
    const accountNotifications = await rpcSubscriptions.accountNotifications(nonceAccountAddress, { commitment, encoding: "base64" }).subscribe({ abortSignal: abortController.signal });
    const base58Decoder2 = getBase58Decoder();
    const base64Encoder = getBase64Encoder();
    function getNonceFromAccountData([base64EncodedBytes]) {
      const data = base64Encoder.encode(base64EncodedBytes);
      const nonceValueBytes = data.slice(NONCE_VALUE_OFFSET, NONCE_VALUE_OFFSET + 32);
      return base58Decoder2.decode(nonceValueBytes);
    }
    const nonceAccountDidAdvancePromise = (async () => {
      for await (const accountNotification of accountNotifications) {
        const nonceValue = getNonceFromAccountData(accountNotification.value.data);
        if (nonceValue !== expectedNonceValue) {
          throw new SolanaError(SOLANA_ERROR__INVALID_NONCE, {
            actualNonceValue: nonceValue,
            expectedNonceValue
          });
        }
      }
    })();
    const nonceIsAlreadyInvalidPromise = (async () => {
      const { value: nonceAccount } = await rpc.getAccountInfo(nonceAccountAddress, {
        commitment,
        dataSlice: { length: 32, offset: NONCE_VALUE_OFFSET },
        encoding: "base58"
      }).send({ abortSignal: abortController.signal });
      if (!nonceAccount) {
        throw new SolanaError(SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND, {
          nonceAccountAddress
        });
      }
      const nonceValue = (
        // This works because we asked for the exact slice of data representing the nonce
        // value, and furthermore asked for it in `base58` encoding.
        nonceAccount.data[0]
      );
      if (nonceValue !== expectedNonceValue) {
        throw new SolanaError(SOLANA_ERROR__INVALID_NONCE, {
          actualNonceValue: nonceValue,
          expectedNonceValue
        });
      } else {
        await new Promise(() => {
        });
      }
    })();
    try {
      return await safeRace([nonceAccountDidAdvancePromise, nonceIsAlreadyInvalidPromise]);
    } finally {
      abortController.abort();
    }
  };
}
function createRecentSignatureConfirmationPromiseFactory({
  rpc,
  rpcSubscriptions
}) {
  return async function getRecentSignatureConfirmationPromise({
    abortSignal: callerAbortSignal,
    commitment,
    signature: signature2
  }) {
    const abortController = new e6();
    function handleAbort() {
      abortController.abort();
    }
    callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
    const signatureStatusNotifications = await rpcSubscriptions.signatureNotifications(signature2, { commitment }).subscribe({ abortSignal: abortController.signal });
    const signatureDidCommitPromise = (async () => {
      for await (const signatureStatusNotification of signatureStatusNotifications) {
        if (signatureStatusNotification.value.err) {
          throw getSolanaErrorFromTransactionError(signatureStatusNotification.value.err);
        } else {
          return;
        }
      }
    })();
    const signatureStatusLookupPromise = (async () => {
      const { value: signatureStatusResults } = await rpc.getSignatureStatuses([signature2]).send({ abortSignal: abortController.signal });
      const signatureStatus = signatureStatusResults[0];
      if (signatureStatus?.err) {
        throw getSolanaErrorFromTransactionError(signatureStatus.err);
      } else if (signatureStatus?.confirmationStatus && commitmentComparator(signatureStatus.confirmationStatus, commitment) >= 0) {
        return;
      } else {
        await new Promise(() => {
        });
      }
    })();
    try {
      return await safeRace([signatureDidCommitPromise, signatureStatusLookupPromise]);
    } finally {
      abortController.abort();
    }
  };
}
async function getTimeoutPromise({ abortSignal: callerAbortSignal, commitment }) {
  return await new Promise((_, reject) => {
    const handleAbort = (e22) => {
      clearTimeout(timeoutId);
      const abortError = new DOMException(e22.target.reason, "AbortError");
      reject(abortError);
    };
    callerAbortSignal.addEventListener("abort", handleAbort);
    const timeoutMs = commitment === "processed" ? 3e4 : 6e4;
    const startMs = performance.now();
    const timeoutId = (
      // We use `setTimeout` instead of `AbortSignal.timeout()` because we want to measure
      // elapsed time instead of active time.
      // See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout_static
      setTimeout(() => {
        const elapsedMs = performance.now() - startMs;
        reject(new DOMException(`Timeout elapsed after ${elapsedMs} ms`, "TimeoutError"));
      }, timeoutMs)
    );
  });
}
async function raceStrategies(signature2, config, getSpecificStrategiesForRace) {
  const { abortSignal: callerAbortSignal, commitment, getRecentSignatureConfirmationPromise } = config;
  callerAbortSignal?.throwIfAborted();
  const abortController = new e6();
  if (callerAbortSignal) {
    const handleAbort = () => {
      abortController.abort();
    };
    callerAbortSignal.addEventListener("abort", handleAbort, { signal: abortController.signal });
  }
  try {
    const specificStrategies = getSpecificStrategiesForRace({
      ...config,
      abortSignal: abortController.signal
    });
    return await safeRace([
      getRecentSignatureConfirmationPromise({
        abortSignal: abortController.signal,
        commitment,
        signature: signature2
      }),
      ...specificStrategies
    ]);
  } finally {
    abortController.abort();
  }
}
async function waitForDurableNonceTransactionConfirmation(config) {
  await raceStrategies(
    getSignatureFromTransaction(config.transaction),
    config,
    function getSpecificStrategiesForRace({ abortSignal, commitment, getNonceInvalidationPromise, transaction }) {
      return [
        getNonceInvalidationPromise({
          abortSignal,
          commitment,
          currentNonceValue: transaction.lifetimeConstraint.nonce,
          nonceAccountAddress: transaction.lifetimeConstraint.nonceAccountAddress
        })
      ];
    }
  );
}
async function waitForRecentTransactionConfirmation(config) {
  await raceStrategies(
    getSignatureFromTransaction(config.transaction),
    config,
    function getSpecificStrategiesForRace({
      abortSignal,
      commitment,
      getBlockHeightExceedencePromise,
      transaction
    }) {
      return [
        getBlockHeightExceedencePromise({
          abortSignal,
          commitment,
          lastValidBlockHeight: transaction.lifetimeConstraint.lastValidBlockHeight
        })
      ];
    }
  );
}
async function waitForRecentTransactionConfirmationUntilTimeout(config) {
  await raceStrategies(
    config.signature,
    config,
    function getSpecificStrategiesForRace({ abortSignal, commitment, getTimeoutPromise: getTimeoutPromise2 }) {
      return [
        getTimeoutPromise2({
          abortSignal,
          commitment
        })
      ];
    }
  );
}
var e6, NONCE_VALUE_OFFSET;
var init_index_node36 = __esm({
  "node_modules/@solana/transaction-confirmation/dist/index.node.mjs"() {
    "use strict";
    init_index_node();
    init_index_node3();
    init_index_node17();
    init_index_node13();
    init_index_node16();
    e6 = class extends globalThis.AbortController {
      constructor(...t) {
        super(...t), setMaxListeners6(Number.MAX_SAFE_INTEGER, this.signal);
      }
    };
    NONCE_VALUE_OFFSET = 4 + // version(u32)
    4 + // state(u32)
    32;
  }
});

// node_modules/@solana/kit/dist/index.node.mjs
var index_node_exports = {};
__export(index_node_exports, {
  AccountRole: () => AccountRole,
  BASE_ACCOUNT_SIZE: () => BASE_ACCOUNT_SIZE,
  DEFAULT_RPC_CONFIG: () => DEFAULT_RPC_CONFIG,
  DEFAULT_RPC_SUBSCRIPTIONS_CONFIG: () => DEFAULT_RPC_SUBSCRIPTIONS_CONFIG,
  Endian: () => Endian,
  MAX_SUPPORTED_TRANSACTION_VERSION: () => MAX_SUPPORTED_TRANSACTION_VERSION,
  OffchainMessageContentFormat: () => OffchainMessageContentFormat,
  SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND: () => SOLANA_ERROR__ACCOUNTS__ACCOUNT_NOT_FOUND,
  SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED: () => SOLANA_ERROR__ACCOUNTS__EXPECTED_ALL_ACCOUNTS_TO_BE_DECODED,
  SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT: () => SOLANA_ERROR__ACCOUNTS__EXPECTED_DECODED_ACCOUNT,
  SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT: () => SOLANA_ERROR__ACCOUNTS__FAILED_TO_DECODE_ACCOUNT,
  SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND: () => SOLANA_ERROR__ACCOUNTS__ONE_OR_MORE_ACCOUNTS_NOT_FOUND,
  SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED: () => SOLANA_ERROR__ADDRESSES__FAILED_TO_FIND_VIABLE_PDA_BUMP_SEED,
  SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS: () => SOLANA_ERROR__ADDRESSES__INVALID_BASE58_ENCODED_ADDRESS,
  SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH: () => SOLANA_ERROR__ADDRESSES__INVALID_BYTE_LENGTH,
  SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY: () => SOLANA_ERROR__ADDRESSES__INVALID_ED25519_PUBLIC_KEY,
  SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS: () => SOLANA_ERROR__ADDRESSES__INVALID_OFF_CURVE_ADDRESS,
  SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE: () => SOLANA_ERROR__ADDRESSES__INVALID_SEEDS_POINT_ON_CURVE,
  SOLANA_ERROR__ADDRESSES__MALFORMED_PDA: () => SOLANA_ERROR__ADDRESSES__MALFORMED_PDA,
  SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED: () => SOLANA_ERROR__ADDRESSES__MAX_NUMBER_OF_PDA_SEEDS_EXCEEDED,
  SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED: () => SOLANA_ERROR__ADDRESSES__MAX_PDA_SEED_LENGTH_EXCEEDED,
  SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE: () => SOLANA_ERROR__ADDRESSES__PDA_BUMP_SEED_OUT_OF_RANGE,
  SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER: () => SOLANA_ERROR__ADDRESSES__PDA_ENDS_WITH_PDA_MARKER,
  SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE: () => SOLANA_ERROR__ADDRESSES__STRING_LENGTH_OUT_OF_RANGE,
  SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE: () => SOLANA_ERROR__BLOCKHASH_STRING_LENGTH_OUT_OF_RANGE,
  SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED: () => SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED,
  SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY: () => SOLANA_ERROR__CODECS__CANNOT_DECODE_EMPTY_BYTE_ARRAY,
  SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS: () => SOLANA_ERROR__CODECS__CANNOT_USE_LEXICAL_VALUES_AS_ENUM_DISCRIMINATORS,
  SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL: () => SOLANA_ERROR__CODECS__ENCODED_BYTES_MUST_NOT_INCLUDE_SENTINEL,
  SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH: () => SOLANA_ERROR__CODECS__ENCODER_DECODER_FIXED_SIZE_MISMATCH,
  SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH: () => SOLANA_ERROR__CODECS__ENCODER_DECODER_MAX_SIZE_MISMATCH,
  SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH: () => SOLANA_ERROR__CODECS__ENCODER_DECODER_SIZE_COMPATIBILITY_MISMATCH,
  SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE: () => SOLANA_ERROR__CODECS__ENUM_DISCRIMINATOR_OUT_OF_RANGE,
  SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY: () => SOLANA_ERROR__CODECS__EXPECTED_DECODER_TO_CONSUME_ENTIRE_BYTE_ARRAY,
  SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH: () => SOLANA_ERROR__CODECS__EXPECTED_FIXED_LENGTH,
  SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH: () => SOLANA_ERROR__CODECS__EXPECTED_POSITIVE_BYTE_LENGTH,
  SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH: () => SOLANA_ERROR__CODECS__EXPECTED_VARIABLE_LENGTH,
  SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE: () => SOLANA_ERROR__CODECS__EXPECTED_ZERO_VALUE_TO_MATCH_ITEM_FIXED_SIZE,
  SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH: () => SOLANA_ERROR__CODECS__INVALID_BYTE_LENGTH,
  SOLANA_ERROR__CODECS__INVALID_CONSTANT: () => SOLANA_ERROR__CODECS__INVALID_CONSTANT,
  SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT: () => SOLANA_ERROR__CODECS__INVALID_DISCRIMINATED_UNION_VARIANT,
  SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT: () => SOLANA_ERROR__CODECS__INVALID_ENUM_VARIANT,
  SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT: () => SOLANA_ERROR__CODECS__INVALID_LITERAL_UNION_VARIANT,
  SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS: () => SOLANA_ERROR__CODECS__INVALID_NUMBER_OF_ITEMS,
  SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE: () => SOLANA_ERROR__CODECS__INVALID_STRING_FOR_BASE,
  SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE: () => SOLANA_ERROR__CODECS__LITERAL_UNION_DISCRIMINATOR_OUT_OF_RANGE,
  SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE: () => SOLANA_ERROR__CODECS__NUMBER_OUT_OF_RANGE,
  SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE: () => SOLANA_ERROR__CODECS__OFFSET_OUT_OF_RANGE,
  SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES: () => SOLANA_ERROR__CODECS__SENTINEL_MISSING_IN_DECODED_BYTES,
  SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE: () => SOLANA_ERROR__CODECS__UNION_VARIANT_OUT_OF_RANGE,
  SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED: () => SOLANA_ERROR__CRYPTO__RANDOM_VALUES_FUNCTION_UNIMPLEMENTED,
  SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED: () => SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_ALREADY_INITIALIZED,
  SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED: () => SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_FAILED,
  SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING: () => SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,
  SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED: () => SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_SIZE_CHANGED,
  SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL: () => SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_DATA_TOO_SMALL,
  SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE: () => SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_EXECUTABLE,
  SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT: () => SOLANA_ERROR__INSTRUCTION_ERROR__ACCOUNT_NOT_RENT_EXEMPT,
  SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW: () => SOLANA_ERROR__INSTRUCTION_ERROR__ARITHMETIC_OVERFLOW,
  SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR: () => SOLANA_ERROR__INSTRUCTION_ERROR__BORSH_IO_ERROR,
  SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS: () => SOLANA_ERROR__INSTRUCTION_ERROR__BUILTIN_PROGRAMS_MUST_CONSUME_COMPUTE_UNITS,
  SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH: () => SOLANA_ERROR__INSTRUCTION_ERROR__CALL_DEPTH,
  SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED: () => SOLANA_ERROR__INSTRUCTION_ERROR__COMPUTATIONAL_BUDGET_EXCEEDED,
  SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM: () => SOLANA_ERROR__INSTRUCTION_ERROR__CUSTOM,
  SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX: () => SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_INDEX,
  SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC: () => SOLANA_ERROR__INSTRUCTION_ERROR__DUPLICATE_ACCOUNT_OUT_OF_SYNC,
  SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT: () => SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_ACCOUNT_NOT_RENT_EXEMPT,
  SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED: () => SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_DATA_MODIFIED,
  SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE: () => SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_LAMPORT_CHANGE,
  SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED: () => SOLANA_ERROR__INSTRUCTION_ERROR__EXECUTABLE_MODIFIED,
  SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED: () => SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_DATA_MODIFIED,
  SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND: () => SOLANA_ERROR__INSTRUCTION_ERROR__EXTERNAL_ACCOUNT_LAMPORT_SPEND,
  SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR: () => SOLANA_ERROR__INSTRUCTION_ERROR__GENERIC_ERROR,
  SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER: () => SOLANA_ERROR__INSTRUCTION_ERROR__ILLEGAL_OWNER,
  SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE: () => SOLANA_ERROR__INSTRUCTION_ERROR__IMMUTABLE,
  SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY: () => SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_AUTHORITY,
  SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID: () => SOLANA_ERROR__INSTRUCTION_ERROR__INCORRECT_PROGRAM_ID,
  SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS: () => SOLANA_ERROR__INSTRUCTION_ERROR__INSUFFICIENT_FUNDS,
  SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA: () => SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_DATA,
  SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER: () => SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ACCOUNT_OWNER,
  SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT: () => SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ARGUMENT,
  SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR: () => SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_ERROR,
  SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA: () => SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_INSTRUCTION_DATA,
  SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC: () => SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_REALLOC,
  SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS: () => SOLANA_ERROR__INSTRUCTION_ERROR__INVALID_SEEDS,
  SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED: () => SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_DATA_ALLOCATIONS_EXCEEDED,
  SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED: () => SOLANA_ERROR__INSTRUCTION_ERROR__MAX_ACCOUNTS_EXCEEDED,
  SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED: () => SOLANA_ERROR__INSTRUCTION_ERROR__MAX_INSTRUCTION_TRACE_LENGTH_EXCEEDED,
  SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED: () => SOLANA_ERROR__INSTRUCTION_ERROR__MAX_SEED_LENGTH_EXCEEDED,
  SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT: () => SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_ACCOUNT,
  SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE: () => SOLANA_ERROR__INSTRUCTION_ERROR__MISSING_REQUIRED_SIGNATURE,
  SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID: () => SOLANA_ERROR__INSTRUCTION_ERROR__MODIFIED_PROGRAM_ID,
  SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS: () => SOLANA_ERROR__INSTRUCTION_ERROR__NOT_ENOUGH_ACCOUNT_KEYS,
  SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION: () => SOLANA_ERROR__INSTRUCTION_ERROR__PRIVILEGE_ESCALATION,
  SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE: () => SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_ENVIRONMENT_SETUP_FAILURE,
  SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE: () => SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPILE,
  SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE: () => SOLANA_ERROR__INSTRUCTION_ERROR__PROGRAM_FAILED_TO_COMPLETE,
  SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED: () => SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_DATA_MODIFIED,
  SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE: () => SOLANA_ERROR__INSTRUCTION_ERROR__READONLY_LAMPORT_CHANGE,
  SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED: () => SOLANA_ERROR__INSTRUCTION_ERROR__REENTRANCY_NOT_ALLOWED,
  SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED: () => SOLANA_ERROR__INSTRUCTION_ERROR__RENT_EPOCH_MODIFIED,
  SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION: () => SOLANA_ERROR__INSTRUCTION_ERROR__UNBALANCED_INSTRUCTION,
  SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT: () => SOLANA_ERROR__INSTRUCTION_ERROR__UNINITIALIZED_ACCOUNT,
  SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN: () => SOLANA_ERROR__INSTRUCTION_ERROR__UNKNOWN,
  SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID: () => SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_PROGRAM_ID,
  SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR: () => SOLANA_ERROR__INSTRUCTION_ERROR__UNSUPPORTED_SYSVAR,
  SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN: () => SOLANA_ERROR__INSTRUCTION_PLANS__EMPTY_INSTRUCTION_PLAN,
  SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT: () => SOLANA_ERROR__INSTRUCTION_PLANS__EXPECTED_SUCCESSFUL_TRANSACTION_PLAN_RESULT,
  SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND: () => SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_SINGLE_TRANSACTION_PLAN_RESULT_NOT_FOUND,
  SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN: () => SOLANA_ERROR__INSTRUCTION_PLANS__FAILED_TO_EXECUTE_TRANSACTION_PLAN,
  SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN: () => SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_CANNOT_ACCOMMODATE_PLAN,
  SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE: () => SOLANA_ERROR__INSTRUCTION_PLANS__MESSAGE_PACKER_ALREADY_COMPLETE,
  SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED: () => SOLANA_ERROR__INSTRUCTION_PLANS__NON_DIVISIBLE_TRANSACTION_PLANS_NOT_SUPPORTED,
  SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN: () => SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_INSTRUCTION_PLAN,
  SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN: () => SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN,
  SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT: () => SOLANA_ERROR__INSTRUCTION_PLANS__UNEXPECTED_TRANSACTION_PLAN_RESULT,
  SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS: () => SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_ACCOUNTS,
  SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA: () => SOLANA_ERROR__INSTRUCTION__EXPECTED_TO_HAVE_DATA,
  SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH: () => SOLANA_ERROR__INSTRUCTION__PROGRAM_ID_MISMATCH,
  SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH: () => SOLANA_ERROR__INVALID_BLOCKHASH_BYTE_LENGTH,
  SOLANA_ERROR__INVALID_NONCE: () => SOLANA_ERROR__INVALID_NONCE,
  SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING: () => SOLANA_ERROR__INVARIANT_VIOLATION__CACHED_ABORTABLE_ITERABLE_CACHE_ENTRY_MISSING,
  SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED: () => SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,
  SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND: () => SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_INSTRUCTION_PLAN_KIND,
  SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND: () => SOLANA_ERROR__INVARIANT_VIOLATION__INVALID_TRANSACTION_PLAN_KIND,
  SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE: () => SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,
  SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING: () => SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,
  SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE: () => SOLANA_ERROR__INVARIANT_VIOLATION__SWITCH_MUST_BE_EXHAUSTIVE,
  SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR: () => SOLANA_ERROR__JSON_RPC__INTERNAL_ERROR,
  SOLANA_ERROR__JSON_RPC__INVALID_PARAMS: () => SOLANA_ERROR__JSON_RPC__INVALID_PARAMS,
  SOLANA_ERROR__JSON_RPC__INVALID_REQUEST: () => SOLANA_ERROR__JSON_RPC__INVALID_REQUEST,
  SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND: () => SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND,
  SOLANA_ERROR__JSON_RPC__PARSE_ERROR: () => SOLANA_ERROR__JSON_RPC__PARSE_ERROR,
  SOLANA_ERROR__JSON_RPC__SCAN_ERROR: () => SOLANA_ERROR__JSON_RPC__SCAN_ERROR,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_CLEANED_UP,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_NOT_AVAILABLE,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_BLOCK_STATUS_NOT_AVAILABLE_YET,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_EPOCH_REWARDS_PERIOD_ACTIVE,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_KEY_EXCLUDED_FROM_SECONDARY_INDEX,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_SLOT_SKIPPED,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_LONG_TERM_STORAGE_UNREACHABLE,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_MIN_CONTEXT_SLOT_NOT_REACHED,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NODE_UNHEALTHY,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_NO_SNAPSHOT,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_NOT_EPOCH_BOUNDARY,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SLOT_SKIPPED,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_HISTORY_NOT_AVAILABLE,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_PRECOMPILE_VERIFICATION_FAILURE,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_LEN_MISMATCH,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_TRANSACTION_SIGNATURE_VERIFICATION_FAILURE,
  SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION: () => SOLANA_ERROR__JSON_RPC__SERVER_ERROR_UNSUPPORTED_TRANSACTION_VERSION,
  SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH: () => SOLANA_ERROR__KEYS__INVALID_KEY_PAIR_BYTE_LENGTH,
  SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH: () => SOLANA_ERROR__KEYS__INVALID_PRIVATE_KEY_BYTE_LENGTH,
  SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH: () => SOLANA_ERROR__KEYS__INVALID_SIGNATURE_BYTE_LENGTH,
  SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY: () => SOLANA_ERROR__KEYS__PUBLIC_KEY_MUST_MATCH_PRIVATE_KEY,
  SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE: () => SOLANA_ERROR__KEYS__SIGNATURE_STRING_LENGTH_OUT_OF_RANGE,
  SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE: () => SOLANA_ERROR__LAMPORTS_OUT_OF_RANGE,
  SOLANA_ERROR__MALFORMED_BIGINT_STRING: () => SOLANA_ERROR__MALFORMED_BIGINT_STRING,
  SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR: () => SOLANA_ERROR__MALFORMED_JSON_RPC_ERROR,
  SOLANA_ERROR__MALFORMED_NUMBER_STRING: () => SOLANA_ERROR__MALFORMED_NUMBER_STRING,
  SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND: () => SOLANA_ERROR__NONCE_ACCOUNT_NOT_FOUND,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__ADDRESSES_CANNOT_SIGN_OFFCHAIN_MESSAGE,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__APPLICATION_DOMAIN_STRING_LENGTH_OUT_OF_RANGE,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__ENVELOPE_SIGNERS_MISMATCH,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__INVALID_APPLICATION_DOMAIN_BYTE_LENGTH,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__MAXIMUM_LENGTH_EXCEEDED,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_FORMAT_MISMATCH,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_LENGTH_MISMATCH,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__MESSAGE_MUST_BE_NON_EMPTY,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_ENVELOPE_SIGNATURES_CANNOT_BE_ZERO,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_REQUIRED_SIGNERS_CANNOT_BE_ZERO,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__NUM_SIGNATURES_MISMATCH,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__RESTRICTED_ASCII_BODY_CHARACTER_OUT_OF_RANGE,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_SORTED,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATORIES_MUST_BE_UNIQUE,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURES_MISSING,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__SIGNATURE_VERIFICATION_FAILURE,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__UNEXPECTED_VERSION,
  SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED: () => SOLANA_ERROR__OFFCHAIN_MESSAGE__VERSION_NUMBER_NOT_SUPPORTED,
  SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN: () => SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN,
  SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED: () => SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED,
  SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED: () => SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED,
  SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT: () => SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT,
  SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID: () => SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID,
  SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD: () => SOLANA_ERROR__RPC__API_PLAN_MISSING_FOR_RPC_METHOD,
  SOLANA_ERROR__RPC__INTEGER_OVERFLOW: () => SOLANA_ERROR__RPC__INTEGER_OVERFLOW,
  SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR: () => SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,
  SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN: () => SOLANA_ERROR__RPC__TRANSPORT_HTTP_HEADER_FORBIDDEN,
  SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS: () => SOLANA_ERROR__SIGNER__ADDRESS_CANNOT_HAVE_MULTIPLE_SIGNERS,
  SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER: () => SOLANA_ERROR__SIGNER__EXPECTED_KEY_PAIR_SIGNER,
  SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER: () => SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_MODIFYING_SIGNER,
  SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER: () => SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_PARTIAL_SIGNER,
  SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER: () => SOLANA_ERROR__SIGNER__EXPECTED_MESSAGE_SIGNER,
  SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER: () => SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_MODIFYING_SIGNER,
  SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER: () => SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_PARTIAL_SIGNER,
  SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER: () => SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SENDING_SIGNER,
  SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER: () => SOLANA_ERROR__SIGNER__EXPECTED_TRANSACTION_SIGNER,
  SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS: () => SOLANA_ERROR__SIGNER__TRANSACTION_CANNOT_HAVE_MULTIPLE_SENDING_SIGNERS,
  SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING: () => SOLANA_ERROR__SIGNER__TRANSACTION_SENDING_SIGNER_MISSING,
  SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED: () => SOLANA_ERROR__SIGNER__WALLET_MULTISIGN_UNIMPLEMENTED,
  SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY: () => SOLANA_ERROR__SUBTLE_CRYPTO__CANNOT_EXPORT_NON_EXTRACTABLE_KEY,
  SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED: () => SOLANA_ERROR__SUBTLE_CRYPTO__DIGEST_UNIMPLEMENTED,
  SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT: () => SOLANA_ERROR__SUBTLE_CRYPTO__DISALLOWED_IN_INSECURE_CONTEXT,
  SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED: () => SOLANA_ERROR__SUBTLE_CRYPTO__ED25519_ALGORITHM_UNIMPLEMENTED,
  SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED: () => SOLANA_ERROR__SUBTLE_CRYPTO__EXPORT_FUNCTION_UNIMPLEMENTED,
  SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED: () => SOLANA_ERROR__SUBTLE_CRYPTO__GENERATE_FUNCTION_UNIMPLEMENTED,
  SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED: () => SOLANA_ERROR__SUBTLE_CRYPTO__SIGN_FUNCTION_UNIMPLEMENTED,
  SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED: () => SOLANA_ERROR__SUBTLE_CRYPTO__VERIFY_FUNCTION_UNIMPLEMENTED,
  SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE: () => SOLANA_ERROR__TIMESTAMP_OUT_OF_RANGE,
  SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING: () => SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_BORROW_OUTSTANDING,
  SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE: () => SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_IN_USE,
  SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE: () => SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_LOADED_TWICE,
  SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND: () => SOLANA_ERROR__TRANSACTION_ERROR__ACCOUNT_NOT_FOUND,
  SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND: () => SOLANA_ERROR__TRANSACTION_ERROR__ADDRESS_LOOKUP_TABLE_NOT_FOUND,
  SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED: () => SOLANA_ERROR__TRANSACTION_ERROR__ALREADY_PROCESSED,
  SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND: () => SOLANA_ERROR__TRANSACTION_ERROR__BLOCKHASH_NOT_FOUND,
  SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP: () => SOLANA_ERROR__TRANSACTION_ERROR__CALL_CHAIN_TOO_DEEP,
  SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE: () => SOLANA_ERROR__TRANSACTION_ERROR__CLUSTER_MAINTENANCE,
  SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION: () => SOLANA_ERROR__TRANSACTION_ERROR__DUPLICATE_INSTRUCTION,
  SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE: () => SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_FEE,
  SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT: () => SOLANA_ERROR__TRANSACTION_ERROR__INSUFFICIENT_FUNDS_FOR_RENT,
  SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE: () => SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_FOR_FEE,
  SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX: () => SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ACCOUNT_INDEX,
  SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA: () => SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_DATA,
  SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX: () => SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_INDEX,
  SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER: () => SOLANA_ERROR__TRANSACTION_ERROR__INVALID_ADDRESS_LOOKUP_TABLE_OWNER,
  SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT: () => SOLANA_ERROR__TRANSACTION_ERROR__INVALID_LOADED_ACCOUNTS_DATA_SIZE_LIMIT,
  SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION: () => SOLANA_ERROR__TRANSACTION_ERROR__INVALID_PROGRAM_FOR_EXECUTION,
  SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT: () => SOLANA_ERROR__TRANSACTION_ERROR__INVALID_RENT_PAYING_ACCOUNT,
  SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT: () => SOLANA_ERROR__TRANSACTION_ERROR__INVALID_WRITABLE_ACCOUNT,
  SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED: () => SOLANA_ERROR__TRANSACTION_ERROR__MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED,
  SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE: () => SOLANA_ERROR__TRANSACTION_ERROR__MISSING_SIGNATURE_FOR_FEE,
  SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND: () => SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_ACCOUNT_NOT_FOUND,
  SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED: () => SOLANA_ERROR__TRANSACTION_ERROR__PROGRAM_EXECUTION_TEMPORARILY_RESTRICTED,
  SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED: () => SOLANA_ERROR__TRANSACTION_ERROR__RESANITIZATION_NEEDED,
  SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE: () => SOLANA_ERROR__TRANSACTION_ERROR__SANITIZE_FAILURE,
  SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE: () => SOLANA_ERROR__TRANSACTION_ERROR__SIGNATURE_FAILURE,
  SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS: () => SOLANA_ERROR__TRANSACTION_ERROR__TOO_MANY_ACCOUNT_LOCKS,
  SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION: () => SOLANA_ERROR__TRANSACTION_ERROR__UNBALANCED_TRANSACTION,
  SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN: () => SOLANA_ERROR__TRANSACTION_ERROR__UNKNOWN,
  SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION: () => SOLANA_ERROR__TRANSACTION_ERROR__UNSUPPORTED_VERSION,
  SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT: () => SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_BLOCK_LIMIT,
  SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT: () => SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_ACCOUNT_DATA_TOTAL_LIMIT,
  SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT: () => SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_ACCOUNT_COST_LIMIT,
  SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT: () => SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_BLOCK_COST_LIMIT,
  SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT: () => SOLANA_ERROR__TRANSACTION_ERROR__WOULD_EXCEED_MAX_VOTE_COST_LIMIT,
  SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION: () => SOLANA_ERROR__TRANSACTION__ADDRESSES_CANNOT_SIGN_TRANSACTION,
  SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING: () => SOLANA_ERROR__TRANSACTION__ADDRESS_MISSING,
  SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES: () => SOLANA_ERROR__TRANSACTION__CANNOT_ENCODE_WITH_EMPTY_SIGNATURES,
  SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT: () => SOLANA_ERROR__TRANSACTION__EXCEEDS_SIZE_LIMIT,
  SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME: () => SOLANA_ERROR__TRANSACTION__EXPECTED_BLOCKHASH_LIFETIME,
  SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME: () => SOLANA_ERROR__TRANSACTION__EXPECTED_NONCE_LIFETIME,
  SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING: () => SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_CONTENTS_MISSING,
  SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE: () => SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_ADDRESS_LOOKUP_TABLE_INDEX_OUT_OF_RANGE,
  SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING: () => SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_FEE_PAYER_MISSING,
  SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND: () => SOLANA_ERROR__TRANSACTION__FAILED_TO_DECOMPILE_INSTRUCTION_PROGRAM_ADDRESS_NOT_FOUND,
  SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT: () => SOLANA_ERROR__TRANSACTION__FAILED_TO_ESTIMATE_COMPUTE_LIMIT,
  SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT: () => SOLANA_ERROR__TRANSACTION__FAILED_WHEN_SIMULATING_TO_ESTIMATE_COMPUTE_LIMIT,
  SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING: () => SOLANA_ERROR__TRANSACTION__FEE_PAYER_MISSING,
  SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING: () => SOLANA_ERROR__TRANSACTION__FEE_PAYER_SIGNATURE_MISSING,
  SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE: () => SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_FIRST_INSTRUCTION_MUST_BE_ADVANCE_NONCE,
  SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING: () => SOLANA_ERROR__TRANSACTION__INVALID_NONCE_TRANSACTION_INSTRUCTIONS_MISSING,
  SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES: () => SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_CANNOT_PAY_FEES,
  SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE: () => SOLANA_ERROR__TRANSACTION__INVOKED_PROGRAMS_MUST_NOT_BE_WRITABLE,
  SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH: () => SOLANA_ERROR__TRANSACTION__MESSAGE_SIGNATURES_MISMATCH,
  SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE: () => SOLANA_ERROR__TRANSACTION__NONCE_ACCOUNT_CANNOT_BE_IN_LOOKUP_TABLE,
  SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING: () => SOLANA_ERROR__TRANSACTION__SIGNATURES_MISSING,
  SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED: () => SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_NOT_SUPPORTED,
  SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE: () => SOLANA_ERROR__TRANSACTION__VERSION_NUMBER_OUT_OF_RANGE,
  SolanaError: () => SolanaError,
  TRANSACTION_PACKET_HEADER: () => TRANSACTION_PACKET_HEADER,
  TRANSACTION_PACKET_SIZE: () => TRANSACTION_PACKET_SIZE,
  TRANSACTION_SIZE_LIMIT: () => TRANSACTION_SIZE_LIMIT,
  addCodecSentinel: () => addCodecSentinel,
  addCodecSizePrefix: () => addCodecSizePrefix,
  addDecoderSentinel: () => addDecoderSentinel,
  addDecoderSizePrefix: () => addDecoderSizePrefix,
  addEncoderSentinel: () => addEncoderSentinel,
  addEncoderSizePrefix: () => addEncoderSizePrefix,
  addSignersToInstruction: () => addSignersToInstruction,
  addSignersToTransactionMessage: () => addSignersToTransactionMessage,
  address: () => address,
  airdropFactory: () => airdropFactory,
  appendTransactionMessageInstruction: () => appendTransactionMessageInstruction,
  appendTransactionMessageInstructionPlan: () => appendTransactionMessageInstructionPlan,
  appendTransactionMessageInstructions: () => appendTransactionMessageInstructions,
  assertAccountDecoded: () => assertAccountDecoded,
  assertAccountExists: () => assertAccountExists,
  assertAccountsDecoded: () => assertAccountsDecoded,
  assertAccountsExist: () => assertAccountsExist,
  assertByteArrayHasEnoughBytesForCodec: () => assertByteArrayHasEnoughBytesForCodec,
  assertByteArrayIsNotEmptyForCodec: () => assertByteArrayIsNotEmptyForCodec,
  assertByteArrayOffsetIsNotOutOfRange: () => assertByteArrayOffsetIsNotOutOfRange,
  assertIsAddress: () => assertIsAddress,
  assertIsBlockhash: () => assertIsBlockhash,
  assertIsCanceledSingleTransactionPlanResult: () => assertIsCanceledSingleTransactionPlanResult,
  assertIsFailedSingleTransactionPlanResult: () => assertIsFailedSingleTransactionPlanResult,
  assertIsFixedSize: () => assertIsFixedSize,
  assertIsFullySignedOffchainMessageEnvelope: () => assertIsFullySignedOffchainMessageEnvelope,
  assertIsFullySignedTransaction: () => assertIsFullySignedTransaction,
  assertIsInstructionForProgram: () => assertIsInstructionForProgram,
  assertIsInstructionWithAccounts: () => assertIsInstructionWithAccounts,
  assertIsInstructionWithData: () => assertIsInstructionWithData,
  assertIsKeyPairSigner: () => assertIsKeyPairSigner,
  assertIsLamports: () => assertIsLamports,
  assertIsMessageModifyingSigner: () => assertIsMessageModifyingSigner,
  assertIsMessagePackerInstructionPlan: () => assertIsMessagePackerInstructionPlan,
  assertIsMessagePartialSigner: () => assertIsMessagePartialSigner,
  assertIsMessageSigner: () => assertIsMessageSigner,
  assertIsNonDivisibleSequentialInstructionPlan: () => assertIsNonDivisibleSequentialInstructionPlan,
  assertIsNonDivisibleSequentialTransactionPlan: () => assertIsNonDivisibleSequentialTransactionPlan,
  assertIsNonDivisibleSequentialTransactionPlanResult: () => assertIsNonDivisibleSequentialTransactionPlanResult,
  assertIsOffCurveAddress: () => assertIsOffCurveAddress,
  assertIsOffchainMessageApplicationDomain: () => assertIsOffchainMessageApplicationDomain,
  assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax: () => assertIsOffchainMessageContentRestrictedAsciiOf1232BytesMax,
  assertIsOffchainMessageContentUtf8Of1232BytesMax: () => assertIsOffchainMessageContentUtf8Of1232BytesMax,
  assertIsOffchainMessageContentUtf8Of65535BytesMax: () => assertIsOffchainMessageContentUtf8Of65535BytesMax,
  assertIsOffchainMessageRestrictedAsciiOf1232BytesMax: () => assertIsOffchainMessageRestrictedAsciiOf1232BytesMax,
  assertIsOffchainMessageUtf8Of1232BytesMax: () => assertIsOffchainMessageUtf8Of1232BytesMax,
  assertIsOffchainMessageUtf8Of65535BytesMax: () => assertIsOffchainMessageUtf8Of65535BytesMax,
  assertIsParallelInstructionPlan: () => assertIsParallelInstructionPlan,
  assertIsParallelTransactionPlan: () => assertIsParallelTransactionPlan,
  assertIsParallelTransactionPlanResult: () => assertIsParallelTransactionPlanResult,
  assertIsProgramDerivedAddress: () => assertIsProgramDerivedAddress,
  assertIsSendableTransaction: () => assertIsSendableTransaction,
  assertIsSequentialInstructionPlan: () => assertIsSequentialInstructionPlan,
  assertIsSequentialTransactionPlan: () => assertIsSequentialTransactionPlan,
  assertIsSequentialTransactionPlanResult: () => assertIsSequentialTransactionPlanResult,
  assertIsSignature: () => assertIsSignature,
  assertIsSignatureBytes: () => assertIsSignatureBytes,
  assertIsSingleInstructionPlan: () => assertIsSingleInstructionPlan,
  assertIsSingleTransactionPlan: () => assertIsSingleTransactionPlan,
  assertIsSingleTransactionPlanResult: () => assertIsSingleTransactionPlanResult,
  assertIsStringifiedBigInt: () => assertIsStringifiedBigInt,
  assertIsStringifiedNumber: () => assertIsStringifiedNumber,
  assertIsSuccessfulSingleTransactionPlanResult: () => assertIsSuccessfulSingleTransactionPlanResult,
  assertIsSuccessfulTransactionPlanResult: () => assertIsSuccessfulTransactionPlanResult,
  assertIsTransactionMessageWithBlockhashLifetime: () => assertIsTransactionMessageWithBlockhashLifetime,
  assertIsTransactionMessageWithDurableNonceLifetime: () => assertIsTransactionMessageWithDurableNonceLifetime,
  assertIsTransactionMessageWithSingleSendingSigner: () => assertIsTransactionMessageWithSingleSendingSigner,
  assertIsTransactionMessageWithinSizeLimit: () => assertIsTransactionMessageWithinSizeLimit,
  assertIsTransactionModifyingSigner: () => assertIsTransactionModifyingSigner,
  assertIsTransactionPartialSigner: () => assertIsTransactionPartialSigner,
  assertIsTransactionSendingSigner: () => assertIsTransactionSendingSigner,
  assertIsTransactionSigner: () => assertIsTransactionSigner,
  assertIsTransactionWithBlockhashLifetime: () => assertIsTransactionWithBlockhashLifetime,
  assertIsTransactionWithDurableNonceLifetime: () => assertIsTransactionWithDurableNonceLifetime,
  assertIsTransactionWithinSizeLimit: () => assertIsTransactionWithinSizeLimit,
  assertIsUnixTimestamp: () => assertIsUnixTimestamp,
  assertIsVariableSize: () => assertIsVariableSize,
  assertNumberIsBetweenForCodec: () => assertNumberIsBetweenForCodec,
  assertValidBaseString: () => assertValidBaseString,
  assertValidNumberOfItemsForCodec: () => assertValidNumberOfItemsForCodec,
  blockhash: () => blockhash,
  bytesEqual: () => bytesEqual,
  canceledSingleTransactionPlanResult: () => canceledSingleTransactionPlanResult,
  combineCodec: () => combineCodec,
  commitmentComparator: () => commitmentComparator,
  compileOffchainMessageEnvelope: () => compileOffchainMessageEnvelope,
  compileOffchainMessageV0Envelope: () => compileOffchainMessageV0Envelope,
  compileOffchainMessageV1Envelope: () => compileOffchainMessageV1Envelope,
  compileTransaction: () => compileTransaction,
  compileTransactionMessage: () => compileTransactionMessage,
  compressTransactionMessageUsingAddressLookupTables: () => compressTransactionMessageUsingAddressLookupTables,
  containsBytes: () => containsBytes,
  createAddressWithSeed: () => createAddressWithSeed,
  createCodec: () => createCodec,
  createDecoder: () => createDecoder,
  createDecoderThatConsumesEntireByteArray: () => createDecoderThatConsumesEntireByteArray,
  createDefaultRpcSubscriptionsChannelCreator: () => createDefaultRpcSubscriptionsChannelCreator,
  createDefaultRpcSubscriptionsTransport: () => createDefaultRpcSubscriptionsTransport,
  createDefaultRpcTransport: () => createDefaultRpcTransport,
  createDefaultSolanaRpcSubscriptionsChannelCreator: () => createDefaultSolanaRpcSubscriptionsChannelCreator,
  createEmptyClient: () => createEmptyClient,
  createEncoder: () => createEncoder,
  createJsonRpcApi: () => createJsonRpcApi,
  createKeyPairFromBytes: () => createKeyPairFromBytes,
  createKeyPairFromPrivateKeyBytes: () => createKeyPairFromPrivateKeyBytes,
  createKeyPairSignerFromBytes: () => createKeyPairSignerFromBytes,
  createKeyPairSignerFromPrivateKeyBytes: () => createKeyPairSignerFromPrivateKeyBytes,
  createNoopSigner: () => createNoopSigner,
  createPrivateKeyFromBytes: () => createPrivateKeyFromBytes,
  createRpc: () => createRpc,
  createRpcMessage: () => createRpcMessage,
  createRpcSubscriptionsApi: () => createRpcSubscriptionsApi,
  createRpcSubscriptionsTransportFromChannelCreator: () => createRpcSubscriptionsTransportFromChannelCreator,
  createSignableMessage: () => createSignableMessage,
  createSignerFromKeyPair: () => createSignerFromKeyPair,
  createSolanaRpc: () => createSolanaRpc,
  createSolanaRpcApi: () => createSolanaRpcApi,
  createSolanaRpcFromTransport: () => createSolanaRpcFromTransport,
  createSolanaRpcSubscriptions: () => createSolanaRpcSubscriptions,
  createSolanaRpcSubscriptionsApi: () => createSolanaRpcSubscriptionsApi,
  createSolanaRpcSubscriptionsApi_UNSTABLE: () => createSolanaRpcSubscriptionsApi_UNSTABLE,
  createSolanaRpcSubscriptionsFromTransport: () => createSolanaRpcSubscriptionsFromTransport,
  createSolanaRpcSubscriptions_UNSTABLE: () => createSolanaRpcSubscriptions_UNSTABLE,
  createSubscriptionRpc: () => createSubscriptionRpc,
  createTransactionMessage: () => createTransactionMessage,
  createTransactionPlanExecutor: () => createTransactionPlanExecutor,
  createTransactionPlanner: () => createTransactionPlanner,
  decodeAccount: () => decodeAccount,
  decompileTransactionMessage: () => decompileTransactionMessage,
  decompileTransactionMessageFetchingLookupTables: () => decompileTransactionMessageFetchingLookupTables,
  devnet: () => devnet,
  downgradeRoleToNonSigner: () => downgradeRoleToNonSigner,
  downgradeRoleToReadonly: () => downgradeRoleToReadonly,
  everyInstructionPlan: () => everyInstructionPlan,
  everyTransactionPlan: () => everyTransactionPlan,
  everyTransactionPlanResult: () => everyTransactionPlanResult,
  executeRpcPubSubSubscriptionPlan: () => executeRpcPubSubSubscriptionPlan,
  failedSingleTransactionPlanResult: () => failedSingleTransactionPlanResult,
  fetchAddressesForLookupTables: () => fetchAddressesForLookupTables,
  fetchEncodedAccount: () => fetchEncodedAccount,
  fetchEncodedAccounts: () => fetchEncodedAccounts,
  fetchJsonParsedAccount: () => fetchJsonParsedAccount,
  fetchJsonParsedAccounts: () => fetchJsonParsedAccounts,
  findInstructionPlan: () => findInstructionPlan,
  findTransactionPlan: () => findTransactionPlan,
  findTransactionPlanResult: () => findTransactionPlanResult,
  fixBytes: () => fixBytes,
  fixCodecSize: () => fixCodecSize,
  fixDecoderSize: () => fixDecoderSize,
  fixEncoderSize: () => fixEncoderSize,
  flattenInstructionPlan: () => flattenInstructionPlan,
  flattenTransactionPlan: () => flattenTransactionPlan,
  flattenTransactionPlanResult: () => flattenTransactionPlanResult,
  generateKeyPair: () => generateKeyPair,
  generateKeyPairSigner: () => generateKeyPairSigner,
  getAddressCodec: () => getAddressCodec,
  getAddressComparator: () => getAddressComparator,
  getAddressDecoder: () => getAddressDecoder,
  getAddressEncoder: () => getAddressEncoder,
  getAddressFromPublicKey: () => getAddressFromPublicKey,
  getAllSingleTransactionPlans: () => getAllSingleTransactionPlans,
  getArrayCodec: () => getArrayCodec,
  getArrayDecoder: () => getArrayDecoder,
  getArrayEncoder: () => getArrayEncoder,
  getBase10Codec: () => getBase10Codec,
  getBase10Decoder: () => getBase10Decoder,
  getBase10Encoder: () => getBase10Encoder,
  getBase16Codec: () => getBase16Codec,
  getBase16Decoder: () => getBase16Decoder,
  getBase16Encoder: () => getBase16Encoder,
  getBase58Codec: () => getBase58Codec,
  getBase58Decoder: () => getBase58Decoder,
  getBase58Encoder: () => getBase58Encoder,
  getBase64Codec: () => getBase64Codec,
  getBase64Decoder: () => getBase64Decoder,
  getBase64EncodedWireTransaction: () => getBase64EncodedWireTransaction,
  getBase64Encoder: () => getBase64Encoder,
  getBaseXCodec: () => getBaseXCodec,
  getBaseXDecoder: () => getBaseXDecoder,
  getBaseXEncoder: () => getBaseXEncoder,
  getBaseXResliceCodec: () => getBaseXResliceCodec,
  getBaseXResliceDecoder: () => getBaseXResliceDecoder,
  getBaseXResliceEncoder: () => getBaseXResliceEncoder,
  getBitArrayCodec: () => getBitArrayCodec,
  getBitArrayDecoder: () => getBitArrayDecoder,
  getBitArrayEncoder: () => getBitArrayEncoder,
  getBlockhashCodec: () => getBlockhashCodec,
  getBlockhashComparator: () => getBlockhashComparator,
  getBlockhashDecoder: () => getBlockhashDecoder,
  getBlockhashEncoder: () => getBlockhashEncoder,
  getBooleanCodec: () => getBooleanCodec,
  getBooleanDecoder: () => getBooleanDecoder,
  getBooleanEncoder: () => getBooleanEncoder,
  getBytesCodec: () => getBytesCodec,
  getBytesDecoder: () => getBytesDecoder,
  getBytesEncoder: () => getBytesEncoder,
  getChannelPoolingChannelCreator: () => getChannelPoolingChannelCreator,
  getCompiledTransactionMessageCodec: () => getCompiledTransactionMessageCodec,
  getCompiledTransactionMessageDecoder: () => getCompiledTransactionMessageDecoder,
  getCompiledTransactionMessageEncoder: () => getCompiledTransactionMessageEncoder,
  getConstantCodec: () => getConstantCodec,
  getConstantDecoder: () => getConstantDecoder,
  getConstantEncoder: () => getConstantEncoder,
  getDefaultLamportsCodec: () => getDefaultLamportsCodec,
  getDefaultLamportsDecoder: () => getDefaultLamportsDecoder,
  getDefaultLamportsEncoder: () => getDefaultLamportsEncoder,
  getDiscriminatedUnionCodec: () => getDiscriminatedUnionCodec,
  getDiscriminatedUnionDecoder: () => getDiscriminatedUnionDecoder,
  getDiscriminatedUnionEncoder: () => getDiscriminatedUnionEncoder,
  getEncodedSize: () => getEncodedSize,
  getEnumCodec: () => getEnumCodec,
  getEnumDecoder: () => getEnumDecoder,
  getEnumEncoder: () => getEnumEncoder,
  getF32Codec: () => getF32Codec,
  getF32Decoder: () => getF32Decoder,
  getF32Encoder: () => getF32Encoder,
  getF64Codec: () => getF64Codec,
  getF64Decoder: () => getF64Decoder,
  getF64Encoder: () => getF64Encoder,
  getFirstFailedSingleTransactionPlanResult: () => getFirstFailedSingleTransactionPlanResult,
  getHiddenPrefixCodec: () => getHiddenPrefixCodec,
  getHiddenPrefixDecoder: () => getHiddenPrefixDecoder,
  getHiddenPrefixEncoder: () => getHiddenPrefixEncoder,
  getHiddenSuffixCodec: () => getHiddenSuffixCodec,
  getHiddenSuffixDecoder: () => getHiddenSuffixDecoder,
  getHiddenSuffixEncoder: () => getHiddenSuffixEncoder,
  getI128Codec: () => getI128Codec,
  getI128Decoder: () => getI128Decoder,
  getI128Encoder: () => getI128Encoder,
  getI16Codec: () => getI16Codec,
  getI16Decoder: () => getI16Decoder,
  getI16Encoder: () => getI16Encoder,
  getI32Codec: () => getI32Codec,
  getI32Decoder: () => getI32Decoder,
  getI32Encoder: () => getI32Encoder,
  getI64Codec: () => getI64Codec,
  getI64Decoder: () => getI64Decoder,
  getI64Encoder: () => getI64Encoder,
  getI8Codec: () => getI8Codec,
  getI8Decoder: () => getI8Decoder,
  getI8Encoder: () => getI8Encoder,
  getLamportsCodec: () => getLamportsCodec,
  getLamportsDecoder: () => getLamportsDecoder,
  getLamportsEncoder: () => getLamportsEncoder,
  getLinearMessagePackerInstructionPlan: () => getLinearMessagePackerInstructionPlan,
  getLiteralUnionCodec: () => getLiteralUnionCodec,
  getLiteralUnionDecoder: () => getLiteralUnionDecoder,
  getLiteralUnionEncoder: () => getLiteralUnionEncoder,
  getMapCodec: () => getMapCodec,
  getMapDecoder: () => getMapDecoder,
  getMapEncoder: () => getMapEncoder,
  getMessagePackerInstructionPlanFromInstructions: () => getMessagePackerInstructionPlanFromInstructions,
  getMinimumBalanceForRentExemption: () => getMinimumBalanceForRentExemption,
  getNullableCodec: () => getNullableCodec,
  getNullableDecoder: () => getNullableDecoder,
  getNullableEncoder: () => getNullableEncoder,
  getOffchainMessageApplicationDomainCodec: () => getOffchainMessageApplicationDomainCodec,
  getOffchainMessageApplicationDomainDecoder: () => getOffchainMessageApplicationDomainDecoder,
  getOffchainMessageApplicationDomainEncoder: () => getOffchainMessageApplicationDomainEncoder,
  getOffchainMessageCodec: () => getOffchainMessageCodec,
  getOffchainMessageDecoder: () => getOffchainMessageDecoder,
  getOffchainMessageEncoder: () => getOffchainMessageEncoder,
  getOffchainMessageEnvelopeCodec: () => getOffchainMessageEnvelopeCodec,
  getOffchainMessageEnvelopeDecoder: () => getOffchainMessageEnvelopeDecoder,
  getOffchainMessageEnvelopeEncoder: () => getOffchainMessageEnvelopeEncoder,
  getOffchainMessageV0Codec: () => getOffchainMessageV0Codec,
  getOffchainMessageV0Decoder: () => getOffchainMessageV0Decoder,
  getOffchainMessageV0Encoder: () => getOffchainMessageV0Encoder,
  getOffchainMessageV1Codec: () => getOffchainMessageV1Codec,
  getOffchainMessageV1Decoder: () => getOffchainMessageV1Decoder,
  getOffchainMessageV1Encoder: () => getOffchainMessageV1Encoder,
  getOptionCodec: () => getOptionCodec,
  getOptionDecoder: () => getOptionDecoder,
  getOptionEncoder: () => getOptionEncoder,
  getProgramDerivedAddress: () => getProgramDerivedAddress,
  getPublicKeyFromAddress: () => getPublicKeyFromAddress,
  getPublicKeyFromPrivateKey: () => getPublicKeyFromPrivateKey,
  getReallocMessagePackerInstructionPlan: () => getReallocMessagePackerInstructionPlan,
  getRpcSubscriptionsChannelWithAutoping: () => getRpcSubscriptionsChannelWithAutoping,
  getRpcSubscriptionsChannelWithBigIntJSONSerialization: () => getRpcSubscriptionsChannelWithBigIntJSONSerialization,
  getRpcSubscriptionsChannelWithJSONSerialization: () => getRpcSubscriptionsChannelWithJSONSerialization,
  getRpcSubscriptionsTransportWithSubscriptionCoalescing: () => getRpcSubscriptionsTransportWithSubscriptionCoalescing,
  getSetCodec: () => getSetCodec,
  getSetDecoder: () => getSetDecoder,
  getSetEncoder: () => getSetEncoder,
  getShortU16Codec: () => getShortU16Codec,
  getShortU16Decoder: () => getShortU16Decoder,
  getShortU16Encoder: () => getShortU16Encoder,
  getSignatureFromTransaction: () => getSignatureFromTransaction,
  getSignersFromInstruction: () => getSignersFromInstruction,
  getSignersFromOffchainMessage: () => getSignersFromOffchainMessage,
  getSignersFromTransactionMessage: () => getSignersFromTransactionMessage,
  getSolanaErrorFromInstructionError: () => getSolanaErrorFromInstructionError,
  getSolanaErrorFromJsonRpcError: () => getSolanaErrorFromJsonRpcError,
  getSolanaErrorFromTransactionError: () => getSolanaErrorFromTransactionError,
  getStructCodec: () => getStructCodec,
  getStructDecoder: () => getStructDecoder,
  getStructEncoder: () => getStructEncoder,
  getTransactionCodec: () => getTransactionCodec,
  getTransactionDecoder: () => getTransactionDecoder,
  getTransactionEncoder: () => getTransactionEncoder,
  getTransactionLifetimeConstraintFromCompiledTransactionMessage: () => getTransactionLifetimeConstraintFromCompiledTransactionMessage,
  getTransactionMessageSize: () => getTransactionMessageSize,
  getTransactionSize: () => getTransactionSize,
  getTransactionVersionCodec: () => getTransactionVersionCodec,
  getTransactionVersionDecoder: () => getTransactionVersionDecoder,
  getTransactionVersionEncoder: () => getTransactionVersionEncoder,
  getTupleCodec: () => getTupleCodec,
  getTupleDecoder: () => getTupleDecoder,
  getTupleEncoder: () => getTupleEncoder,
  getU128Codec: () => getU128Codec,
  getU128Decoder: () => getU128Decoder,
  getU128Encoder: () => getU128Encoder,
  getU16Codec: () => getU16Codec,
  getU16Decoder: () => getU16Decoder,
  getU16Encoder: () => getU16Encoder,
  getU32Codec: () => getU32Codec,
  getU32Decoder: () => getU32Decoder,
  getU32Encoder: () => getU32Encoder,
  getU64Codec: () => getU64Codec,
  getU64Decoder: () => getU64Decoder,
  getU64Encoder: () => getU64Encoder,
  getU8Codec: () => getU8Codec,
  getU8Decoder: () => getU8Decoder,
  getU8Encoder: () => getU8Encoder,
  getUnionCodec: () => getUnionCodec,
  getUnionDecoder: () => getUnionDecoder,
  getUnionEncoder: () => getUnionEncoder,
  getUnitCodec: () => getUnitCodec,
  getUnitDecoder: () => getUnitDecoder,
  getUnitEncoder: () => getUnitEncoder,
  getUtf8Codec: () => getUtf8Codec,
  getUtf8Decoder: () => getUtf8Decoder,
  getUtf8Encoder: () => getUtf8Encoder,
  isAddress: () => isAddress2,
  isAdvanceNonceAccountInstruction: () => isAdvanceNonceAccountInstruction,
  isBlockhash: () => isBlockhash,
  isCanceledSingleTransactionPlanResult: () => isCanceledSingleTransactionPlanResult,
  isFailedSingleTransactionPlanResult: () => isFailedSingleTransactionPlanResult,
  isFixedSize: () => isFixedSize,
  isFullySignedOffchainMessageEnvelope: () => isFullySignedOffchainMessageEnvelope,
  isFullySignedTransaction: () => isFullySignedTransaction,
  isInstructionForProgram: () => isInstructionForProgram,
  isInstructionWithAccounts: () => isInstructionWithAccounts,
  isInstructionWithData: () => isInstructionWithData,
  isJsonRpcPayload: () => isJsonRpcPayload,
  isKeyPairSigner: () => isKeyPairSigner,
  isLamports: () => isLamports,
  isMessageModifyingSigner: () => isMessageModifyingSigner,
  isMessagePackerInstructionPlan: () => isMessagePackerInstructionPlan,
  isMessagePartialSigner: () => isMessagePartialSigner,
  isMessageSigner: () => isMessageSigner,
  isNonDivisibleSequentialInstructionPlan: () => isNonDivisibleSequentialInstructionPlan,
  isNonDivisibleSequentialTransactionPlan: () => isNonDivisibleSequentialTransactionPlan,
  isNonDivisibleSequentialTransactionPlanResult: () => isNonDivisibleSequentialTransactionPlanResult,
  isNone: () => isNone,
  isOffCurveAddress: () => isOffCurveAddress,
  isOffchainMessageApplicationDomain: () => isOffchainMessageApplicationDomain,
  isOffchainMessageContentRestrictedAsciiOf1232BytesMax: () => isOffchainMessageContentRestrictedAsciiOf1232BytesMax,
  isOffchainMessageContentUtf8Of1232BytesMax: () => isOffchainMessageContentUtf8Of1232BytesMax,
  isOffchainMessageContentUtf8Of65535BytesMax: () => isOffchainMessageContentUtf8Of65535BytesMax,
  isOption: () => isOption,
  isParallelInstructionPlan: () => isParallelInstructionPlan,
  isParallelTransactionPlan: () => isParallelTransactionPlan,
  isParallelTransactionPlanResult: () => isParallelTransactionPlanResult,
  isProgramDerivedAddress: () => isProgramDerivedAddress,
  isProgramError: () => isProgramError,
  isSendableTransaction: () => isSendableTransaction,
  isSequentialInstructionPlan: () => isSequentialInstructionPlan,
  isSequentialTransactionPlan: () => isSequentialTransactionPlan,
  isSequentialTransactionPlanResult: () => isSequentialTransactionPlanResult,
  isSignature: () => isSignature,
  isSignatureBytes: () => isSignatureBytes,
  isSignerRole: () => isSignerRole,
  isSingleInstructionPlan: () => isSingleInstructionPlan,
  isSingleTransactionPlan: () => isSingleTransactionPlan,
  isSingleTransactionPlanResult: () => isSingleTransactionPlanResult,
  isSolanaError: () => isSolanaError,
  isSome: () => isSome,
  isStringifiedBigInt: () => isStringifiedBigInt,
  isStringifiedNumber: () => isStringifiedNumber,
  isSuccessfulSingleTransactionPlanResult: () => isSuccessfulSingleTransactionPlanResult,
  isSuccessfulTransactionPlanResult: () => isSuccessfulTransactionPlanResult,
  isTransactionMessageWithBlockhashLifetime: () => isTransactionMessageWithBlockhashLifetime,
  isTransactionMessageWithDurableNonceLifetime: () => isTransactionMessageWithDurableNonceLifetime,
  isTransactionMessageWithSingleSendingSigner: () => isTransactionMessageWithSingleSendingSigner,
  isTransactionMessageWithinSizeLimit: () => isTransactionMessageWithinSizeLimit,
  isTransactionModifyingSigner: () => isTransactionModifyingSigner,
  isTransactionPartialSigner: () => isTransactionPartialSigner,
  isTransactionSendingSigner: () => isTransactionSendingSigner,
  isTransactionSigner: () => isTransactionSigner,
  isTransactionWithBlockhashLifetime: () => isTransactionWithBlockhashLifetime,
  isTransactionWithDurableNonceLifetime: () => isTransactionWithDurableNonceLifetime,
  isTransactionWithinSizeLimit: () => isTransactionWithinSizeLimit,
  isUnixTimestamp: () => isUnixTimestamp,
  isVariableSize: () => isVariableSize,
  isWritableRole: () => isWritableRole,
  lamports: () => lamports,
  mainnet: () => mainnet,
  mergeBytes: () => mergeBytes,
  mergeRoles: () => mergeRoles,
  nonDivisibleSequentialInstructionPlan: () => nonDivisibleSequentialInstructionPlan,
  nonDivisibleSequentialTransactionPlan: () => nonDivisibleSequentialTransactionPlan,
  nonDivisibleSequentialTransactionPlanResult: () => nonDivisibleSequentialTransactionPlanResult,
  none: () => none,
  offCurveAddress: () => offCurveAddress,
  offchainMessageApplicationDomain: () => offchainMessageApplicationDomain,
  offchainMessageContentRestrictedAsciiOf1232BytesMax: () => offchainMessageContentRestrictedAsciiOf1232BytesMax,
  offchainMessageContentUtf8Of1232BytesMax: () => offchainMessageContentUtf8Of1232BytesMax,
  offchainMessageContentUtf8Of65535BytesMax: () => offchainMessageContentUtf8Of65535BytesMax,
  offsetCodec: () => offsetCodec,
  offsetDecoder: () => offsetDecoder,
  offsetEncoder: () => offsetEncoder,
  padBytes: () => padBytes2,
  padLeftCodec: () => padLeftCodec,
  padLeftDecoder: () => padLeftDecoder,
  padLeftEncoder: () => padLeftEncoder,
  padNullCharacters: () => padNullCharacters,
  padRightCodec: () => padRightCodec,
  padRightDecoder: () => padRightDecoder,
  padRightEncoder: () => padRightEncoder,
  parallelInstructionPlan: () => parallelInstructionPlan,
  parallelTransactionPlan: () => parallelTransactionPlan,
  parallelTransactionPlanResult: () => parallelTransactionPlanResult,
  parseBase58RpcAccount: () => parseBase58RpcAccount,
  parseBase64RpcAccount: () => parseBase64RpcAccount,
  parseJsonRpcAccount: () => parseJsonRpcAccount,
  partiallySignOffchainMessageEnvelope: () => partiallySignOffchainMessageEnvelope,
  partiallySignOffchainMessageWithSigners: () => partiallySignOffchainMessageWithSigners,
  partiallySignTransaction: () => partiallySignTransaction,
  partiallySignTransactionMessageWithSigners: () => partiallySignTransactionMessageWithSigners,
  passthroughFailedTransactionPlanExecution: () => passthroughFailedTransactionPlanExecution,
  pipe: () => pipe,
  prependTransactionMessageInstruction: () => prependTransactionMessageInstruction,
  prependTransactionMessageInstructions: () => prependTransactionMessageInstructions,
  removeNullCharacters: () => removeNullCharacters,
  resizeCodec: () => resizeCodec,
  resizeDecoder: () => resizeDecoder,
  resizeEncoder: () => resizeEncoder,
  reverseCodec: () => reverseCodec,
  reverseDecoder: () => reverseDecoder,
  reverseEncoder: () => reverseEncoder,
  safeCaptureStackTrace: () => safeCaptureStackTrace,
  sendAndConfirmDurableNonceTransactionFactory: () => sendAndConfirmDurableNonceTransactionFactory,
  sendAndConfirmTransactionFactory: () => sendAndConfirmTransactionFactory,
  sendTransactionWithoutConfirmingFactory: () => sendTransactionWithoutConfirmingFactory,
  sequentialInstructionPlan: () => sequentialInstructionPlan,
  sequentialTransactionPlan: () => sequentialTransactionPlan,
  sequentialTransactionPlanResult: () => sequentialTransactionPlanResult,
  setTransactionMessageFeePayer: () => setTransactionMessageFeePayer,
  setTransactionMessageFeePayerSigner: () => setTransactionMessageFeePayerSigner,
  setTransactionMessageLifetimeUsingBlockhash: () => setTransactionMessageLifetimeUsingBlockhash,
  setTransactionMessageLifetimeUsingDurableNonce: () => setTransactionMessageLifetimeUsingDurableNonce,
  signAndSendTransactionMessageWithSigners: () => signAndSendTransactionMessageWithSigners,
  signBytes: () => signBytes,
  signOffchainMessageEnvelope: () => signOffchainMessageEnvelope,
  signOffchainMessageWithSigners: () => signOffchainMessageWithSigners,
  signTransaction: () => signTransaction2,
  signTransactionMessageWithSigners: () => signTransactionMessageWithSigners,
  signature: () => signature,
  signatureBytes: () => signatureBytes,
  singleInstructionPlan: () => singleInstructionPlan,
  singleTransactionPlan: () => singleTransactionPlan,
  some: () => some,
  stringifiedBigInt: () => stringifiedBigInt,
  stringifiedNumber: () => stringifiedNumber,
  successfulSingleTransactionPlanResult: () => successfulSingleTransactionPlanResult,
  successfulSingleTransactionPlanResultFromSignature: () => successfulSingleTransactionPlanResultFromSignature,
  summarizeTransactionPlanResult: () => summarizeTransactionPlanResult,
  testnet: () => testnet,
  toArrayBuffer: () => toArrayBuffer,
  transformChannelInboundMessages: () => transformChannelInboundMessages,
  transformChannelOutboundMessages: () => transformChannelOutboundMessages,
  transformCodec: () => transformCodec,
  transformDecoder: () => transformDecoder,
  transformEncoder: () => transformEncoder,
  transformInstructionPlan: () => transformInstructionPlan,
  transformTransactionPlan: () => transformTransactionPlan,
  transformTransactionPlanResult: () => transformTransactionPlanResult,
  unixTimestamp: () => unixTimestamp,
  unwrapOption: () => unwrapOption,
  unwrapOptionRecursively: () => unwrapOptionRecursively,
  unwrapSimulationError: () => unwrapSimulationError,
  upgradeRoleToSigner: () => upgradeRoleToSigner,
  upgradeRoleToWritable: () => upgradeRoleToWritable,
  verifyOffchainMessageEnvelope: () => verifyOffchainMessageEnvelope,
  verifySignature: () => verifySignature,
  wrapNullable: () => wrapNullable
});
async function requestAndConfirmAirdrop_INTERNAL_ONLY_DO_NOT_EXPORT({
  abortSignal,
  commitment,
  confirmSignatureOnlyTransaction,
  lamports: lamports2,
  recipientAddress,
  rpc
}) {
  const airdropTransactionSignature = await rpc.requestAirdrop(recipientAddress, lamports2, { commitment }).send({ abortSignal });
  await confirmSignatureOnlyTransaction({
    abortSignal,
    commitment,
    signature: airdropTransactionSignature
  });
  return airdropTransactionSignature;
}
function airdropFactory({
  rpc,
  rpcSubscriptions
}) {
  const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({
    rpc,
    rpcSubscriptions
  });
  async function confirmSignatureOnlyTransaction(config) {
    await waitForRecentTransactionConfirmationUntilTimeout({
      ...config,
      getRecentSignatureConfirmationPromise,
      getTimeoutPromise
    });
  }
  return async function airdrop(config) {
    return await requestAndConfirmAirdrop_INTERNAL_ONLY_DO_NOT_EXPORT({
      ...config,
      confirmSignatureOnlyTransaction,
      rpc
    });
  };
}
async function fetchAddressesForLookupTables(lookupTableAddresses, rpc, config) {
  if (lookupTableAddresses.length === 0) {
    return {};
  }
  const fetchedLookupTables = await fetchJsonParsedAccounts(
    rpc,
    lookupTableAddresses,
    config
  );
  assertAccountsDecoded(fetchedLookupTables);
  assertAccountsExist(fetchedLookupTables);
  return fetchedLookupTables.reduce((acc, lookup) => {
    return {
      ...acc,
      [lookup.address]: lookup.data.addresses
    };
  }, {});
}
async function decompileTransactionMessageFetchingLookupTables(compiledTransactionMessage, rpc, config) {
  const lookupTables = "addressTableLookups" in compiledTransactionMessage && compiledTransactionMessage.addressTableLookups !== void 0 && compiledTransactionMessage.addressTableLookups.length > 0 ? compiledTransactionMessage.addressTableLookups : [];
  const lookupTableAddresses = lookupTables.map((l2) => l2.lookupTableAddress);
  const { lastValidBlockHeight, ...fetchAccountsConfig } = config ?? {};
  const addressesByLookupTableAddress = lookupTableAddresses.length > 0 ? await fetchAddressesForLookupTables(lookupTableAddresses, rpc, fetchAccountsConfig) : {};
  return decompileTransactionMessage(compiledTransactionMessage, {
    addressesByLookupTableAddress,
    lastValidBlockHeight
  });
}
function getMinimumBalanceForRentExemption(space) {
  const RENT = {
    ACCOUNT_STORAGE_OVERHEAD: 128n,
    DEFAULT_EXEMPTION_THRESHOLD: 2n,
    DEFAULT_LAMPORTS_PER_BYTE_YEAR: 3480n
  };
  const requiredLamports = (RENT.ACCOUNT_STORAGE_OVERHEAD + space) * RENT.DEFAULT_LAMPORTS_PER_BYTE_YEAR * RENT.DEFAULT_EXEMPTION_THRESHOLD;
  return requiredLamports;
}
function getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, config) {
  if (
    // The developer has supplied no value for `preflightCommitment`.
    !config?.preflightCommitment && // The value of `commitment` is lower than the server default of `preflightCommitment`.
    commitmentComparator(
      commitment,
      "finalized"
      /* default value of `preflightCommitment` */
    ) < 0
  ) {
    return {
      ...config,
      // In the common case, it is unlikely that you want to simulate a transaction at
      // `finalized` commitment when your standard of commitment for confirming the
      // transaction is lower. Cap the simulation commitment level to the level of the
      // confirmation commitment.
      preflightCommitment: commitment
    };
  }
  return config;
}
async function sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({
  abortSignal,
  commitment,
  rpc,
  transaction,
  ...sendTransactionConfig
}) {
  const base64EncodedWireTransaction = getBase64EncodedWireTransaction(transaction);
  return await rpc.sendTransaction(base64EncodedWireTransaction, {
    ...getSendTransactionConfigWithAdjustedPreflightCommitment(commitment, sendTransactionConfig),
    encoding: "base64"
  }).send({ abortSignal });
}
async function sendAndConfirmDurableNonceTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({
  abortSignal,
  commitment,
  confirmDurableNonceTransaction,
  rpc,
  transaction,
  ...sendTransactionConfig
}) {
  const transactionSignature = await sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({
    ...sendTransactionConfig,
    abortSignal,
    commitment,
    rpc,
    transaction
  });
  await confirmDurableNonceTransaction({
    abortSignal,
    commitment,
    transaction
  });
  return transactionSignature;
}
async function sendAndConfirmTransactionWithBlockhashLifetime_INTERNAL_ONLY_DO_NOT_EXPORT({
  abortSignal,
  commitment,
  confirmRecentTransaction,
  rpc,
  transaction,
  ...sendTransactionConfig
}) {
  const transactionSignature = await sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({
    ...sendTransactionConfig,
    abortSignal,
    commitment,
    rpc,
    transaction
  });
  await confirmRecentTransaction({
    abortSignal,
    commitment,
    transaction
  });
  return transactionSignature;
}
function sendAndConfirmDurableNonceTransactionFactory({
  rpc,
  rpcSubscriptions
}) {
  const getNonceInvalidationPromise = createNonceInvalidationPromiseFactory({ rpc, rpcSubscriptions });
  const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({
    rpc,
    rpcSubscriptions
  });
  function createNonceInvalidationPromiseHandlingRaceCondition(signature2) {
    return async function wrappedGetNonceInvalidationPromise(config) {
      try {
        return await getNonceInvalidationPromise(config);
      } catch (e7) {
        if (isSolanaError(e7, SOLANA_ERROR__INVALID_NONCE)) {
          let status;
          try {
            const { value: statuses } = await rpc.getSignatureStatuses([signature2]).send({ abortSignal: config.abortSignal });
            status = statuses[0];
          } catch {
            throw e7;
          }
          if (status === null || status === void 0) {
            throw e7;
          }
          if (status.confirmationStatus !== null && commitmentComparator(status.confirmationStatus, config.commitment) >= 0) {
            if (status.err !== null) {
              throw getSolanaErrorFromTransactionError(status.err);
            }
            return;
          }
          return await new Promise(() => {
          });
        }
        throw e7;
      }
    };
  }
  async function confirmDurableNonceTransaction(config) {
    const wrappedGetNonceInvalidationPromise = createNonceInvalidationPromiseHandlingRaceCondition(
      getSignatureFromTransaction(config.transaction)
    );
    await waitForDurableNonceTransactionConfirmation({
      ...config,
      getNonceInvalidationPromise: wrappedGetNonceInvalidationPromise,
      getRecentSignatureConfirmationPromise
    });
  }
  return async function sendAndConfirmDurableNonceTransaction(transaction, config) {
    await sendAndConfirmDurableNonceTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({
      ...config,
      confirmDurableNonceTransaction,
      rpc,
      transaction
    });
  };
}
function sendAndConfirmTransactionFactory({
  rpc,
  rpcSubscriptions
}) {
  const getBlockHeightExceedencePromise = createBlockHeightExceedencePromiseFactory({
    rpc,
    rpcSubscriptions
  });
  const getRecentSignatureConfirmationPromise = createRecentSignatureConfirmationPromiseFactory({
    rpc,
    rpcSubscriptions
  });
  async function confirmRecentTransaction(config) {
    await waitForRecentTransactionConfirmation({
      ...config,
      getBlockHeightExceedencePromise,
      getRecentSignatureConfirmationPromise
    });
  }
  return async function sendAndConfirmTransaction(transaction, config) {
    await sendAndConfirmTransactionWithBlockhashLifetime_INTERNAL_ONLY_DO_NOT_EXPORT({
      ...config,
      confirmRecentTransaction,
      rpc,
      transaction
    });
  };
}
function sendTransactionWithoutConfirmingFactory({
  rpc
}) {
  return async function sendTransactionWithoutConfirming(transaction, config) {
    await sendTransaction_INTERNAL_ONLY_DO_NOT_EXPORT({
      ...config,
      rpc,
      transaction
    });
  };
}
var init_index_node37 = __esm({
  "node_modules/@solana/kit/dist/index.node.mjs"() {
    "use strict";
    init_index_node4();
    init_index_node4();
    init_index_node6();
    init_index_node10();
    init_index_node();
    init_index_node();
    init_index_node11();
    init_index_node12();
    init_index_node18();
    init_index_node15();
    init_index_node19();
    init_index_node20();
    init_index_node21();
    init_index_node28();
    init_index_node29();
    init_index_node34();
    init_index_node13();
    init_index_node13();
    init_index_node35();
    init_index_node14();
    init_index_node14();
    init_index_node16();
    init_index_node16();
    init_index_node36();
    init_index_node22();
  }
});

// src/wallet.ts
var wallet_exports = {};
__export(wallet_exports, {
  deriveAllKeys: () => deriveAllKeys,
  deriveEvmKey: () => deriveEvmKey,
  deriveSolanaKeyBytes: () => deriveSolanaKeyBytes,
  generateWalletMnemonic: () => generateWalletMnemonic,
  getSolanaAddress: () => getSolanaAddress,
  isValidMnemonic: () => isValidMnemonic
});
function generateWalletMnemonic() {
  return generateMnemonic(wordlist, 256);
}
function isValidMnemonic(mnemonic) {
  return validateMnemonic(mnemonic, wordlist);
}
function deriveEvmKey(mnemonic) {
  const seed = mnemonicToSeedSync(mnemonic);
  const hdKey = HDKey.fromMasterSeed(seed);
  const derived = hdKey.derive(ETH_DERIVATION_PATH);
  if (!derived.privateKey) throw new Error("Failed to derive EVM private key");
  const hex = `0x${Buffer.from(derived.privateKey).toString("hex")}`;
  const account = privateKeyToAccount(hex);
  return { privateKey: hex, address: account.address };
}
function deriveSolanaKeyBytes(mnemonic) {
  const seed = mnemonicToSeedSync(mnemonic);
  let I = hmac4(sha5122, new TextEncoder().encode("ed25519 seed"), seed);
  let key = I.slice(0, 32);
  let chainCode = I.slice(32);
  for (const index2 of SOLANA_HARDENED_INDICES) {
    const data = new Uint8Array(37);
    data[0] = 0;
    data.set(key, 1);
    data[33] = index2 >>> 24 & 255;
    data[34] = index2 >>> 16 & 255;
    data[35] = index2 >>> 8 & 255;
    data[36] = index2 & 255;
    I = hmac4(sha5122, chainCode, data);
    key = I.slice(0, 32);
    chainCode = I.slice(32);
  }
  return new Uint8Array(key);
}
function deriveAllKeys(mnemonic) {
  const { privateKey: evmPrivateKey, address: evmAddress } = deriveEvmKey(mnemonic);
  const solanaPrivateKeyBytes = deriveSolanaKeyBytes(mnemonic);
  return { mnemonic, evmPrivateKey, evmAddress, solanaPrivateKeyBytes };
}
async function getSolanaAddress(privateKeyBytes) {
  const { createKeyPairSignerFromPrivateKeyBytes: createKeyPairSignerFromPrivateKeyBytes2 } = await Promise.resolve().then(() => (init_index_node37(), index_node_exports));
  const signer = await createKeyPairSignerFromPrivateKeyBytes2(privateKeyBytes);
  return signer.address;
}
var ETH_DERIVATION_PATH, SOLANA_HARDENED_INDICES;
var init_wallet = __esm({
  "src/wallet.ts"() {
    "use strict";
    init_bip32();
    init_esm3();
    init_english();
    init_hmac4();
    init_sha24();
    init_accounts();
    ETH_DERIVATION_PATH = "m/44'/60'/0'/0/0";
    SOLANA_HARDENED_INDICES = [44 + 2147483648, 501 + 2147483648, 0 + 2147483648, 0 + 2147483648];
  }
});

// src/auth.ts
var auth_exports = {};
__export(auth_exports, {
  CHAIN_FILE: () => CHAIN_FILE,
  MNEMONIC_FILE: () => MNEMONIC_FILE,
  WALLET_FILE: () => WALLET_FILE,
  envKeyAuth: () => envKeyAuth,
  loadPaymentChain: () => loadPaymentChain,
  recoverWalletFromMnemonic: () => recoverWalletFromMnemonic,
  resolveOrGenerateWalletKey: () => resolveOrGenerateWalletKey,
  resolvePaymentChain: () => resolvePaymentChain,
  savePaymentChain: () => savePaymentChain,
  setupSolana: () => setupSolana,
  walletKeyAuth: () => walletKeyAuth
});
import { writeFile, mkdir as mkdir2 } from "fs/promises";
import { join as join6 } from "path";
import { homedir as homedir3 } from "os";
async function loadSavedWallet() {
  try {
    const key = (await readTextFile(WALLET_FILE)).trim();
    if (key.startsWith("0x") && key.length === 66) {
      console.log(`[ClawRouter] \u2713 Loaded existing wallet from ${WALLET_FILE}`);
      return key;
    }
    console.error(`[ClawRouter] \u2717 CRITICAL: Wallet file exists but has invalid format!`);
    console.error(`[ClawRouter]   File: ${WALLET_FILE}`);
    console.error(`[ClawRouter]   Expected: 0x followed by 64 hex characters (66 chars total)`);
    console.error(
      `[ClawRouter]   To fix: restore your backup key or set BLOCKRUN_WALLET_KEY env var`
    );
    throw new Error(
      `Wallet file at ${WALLET_FILE} is corrupted or has wrong format. Refusing to auto-generate new wallet to protect existing funds. Restore your backup key or set BLOCKRUN_WALLET_KEY environment variable.`
    );
  } catch (err) {
    if (err.code !== "ENOENT") {
      if (err instanceof Error && err.message.includes("Refusing to auto-generate")) {
        throw err;
      }
      console.error(
        `[ClawRouter] \u2717 Failed to read wallet file: ${err instanceof Error ? err.message : String(err)}`
      );
      throw new Error(
        `Cannot read wallet file at ${WALLET_FILE}: ${err instanceof Error ? err.message : String(err)}. Refusing to auto-generate new wallet to protect existing funds. Fix file permissions or set BLOCKRUN_WALLET_KEY environment variable.`,
        { cause: err }
      );
    }
  }
  return void 0;
}
async function loadMnemonic() {
  try {
    const mnemonic = (await readTextFile(MNEMONIC_FILE)).trim();
    if (mnemonic && isValidMnemonic(mnemonic)) {
      return mnemonic;
    }
    console.warn(`[ClawRouter] \u26A0 Mnemonic file exists but has invalid format \u2014 ignoring`);
    return void 0;
  } catch (err) {
    if (err.code !== "ENOENT") {
      console.warn(`[ClawRouter] \u26A0 Cannot read mnemonic file \u2014 ignoring`);
    }
  }
  return void 0;
}
async function saveMnemonic(mnemonic) {
  await mkdir2(WALLET_DIR, { recursive: true });
  await writeFile(MNEMONIC_FILE, mnemonic + "\n", { mode: 384 });
}
async function generateAndSaveWallet() {
  const existingMnemonic = await loadMnemonic();
  if (existingMnemonic) {
    throw new Error(
      `Mnemonic file exists at ${MNEMONIC_FILE} but wallet.key is missing.
Refusing to generate a new wallet to protect existing funds.

Restore your EVM private key using one of:
  Windows:   set BLOCKRUN_WALLET_KEY=0x<your_key>
  Mac/Linux: export BLOCKRUN_WALLET_KEY=0x<your_key>

Then run: npx @blockrun/clawrouter`
    );
  }
  const mnemonic = generateWalletMnemonic();
  const derived = deriveAllKeys(mnemonic);
  await mkdir2(WALLET_DIR, { recursive: true });
  await writeFile(WALLET_FILE, derived.evmPrivateKey + "\n", { mode: 384 });
  await writeFile(MNEMONIC_FILE, mnemonic + "\n", { mode: 384 });
  try {
    const verification = (await readTextFile(WALLET_FILE)).trim();
    if (verification !== derived.evmPrivateKey) {
      throw new Error("Wallet file verification failed - content mismatch");
    }
    console.log(`[ClawRouter] Wallet saved and verified at ${WALLET_FILE}`);
  } catch (err) {
    throw new Error(
      `Failed to verify wallet file after creation: ${err instanceof Error ? err.message : String(err)}`,
      { cause: err }
    );
  }
  let solanaAddress;
  try {
    solanaAddress = await getSolanaAddress(derived.solanaPrivateKeyBytes);
  } catch {
  }
  console.log(`[ClawRouter]`);
  console.log(`[ClawRouter] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`);
  console.log(`[ClawRouter]   NEW WALLET GENERATED \u2014 BACK UP YOUR KEY NOW`);
  console.log(`[ClawRouter] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`);
  console.log(`[ClawRouter]   EVM Address    : ${derived.evmAddress}`);
  if (solanaAddress) {
    console.log(`[ClawRouter]   Solana Address : ${solanaAddress}`);
  }
  console.log(`[ClawRouter]   Key file       : ${WALLET_FILE}`);
  console.log(`[ClawRouter]   Mnemonic       : ${MNEMONIC_FILE}`);
  console.log(`[ClawRouter]`);
  console.log(`[ClawRouter]   Both EVM (Base) and Solana wallets are ready.`);
  console.log(`[ClawRouter]   To back up, run in OpenClaw:`);
  console.log(`[ClawRouter]     /wallet export`);
  console.log(`[ClawRouter]`);
  console.log(`[ClawRouter]   To restore on another machine:`);
  console.log(`[ClawRouter]     export BLOCKRUN_WALLET_KEY=<your_key>`);
  console.log(`[ClawRouter] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`);
  console.log(`[ClawRouter]`);
  return {
    key: derived.evmPrivateKey,
    address: derived.evmAddress,
    mnemonic,
    solanaPrivateKeyBytes: derived.solanaPrivateKeyBytes
  };
}
async function resolveOrGenerateWalletKey() {
  const saved = await loadSavedWallet();
  if (saved) {
    const account = privateKeyToAccount(saved);
    const mnemonic = await loadMnemonic();
    if (mnemonic) {
      const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);
      return {
        key: saved,
        address: account.address,
        source: "saved",
        mnemonic,
        solanaPrivateKeyBytes: solanaKeyBytes
      };
    }
    return { key: saved, address: account.address, source: "saved" };
  }
  const envKey = process["env"].BLOCKRUN_WALLET_KEY;
  if (typeof envKey === "string" && envKey.startsWith("0x") && envKey.length === 66) {
    const account = privateKeyToAccount(envKey);
    const mnemonic = await loadMnemonic();
    if (mnemonic) {
      const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);
      return {
        key: envKey,
        address: account.address,
        source: "env",
        mnemonic,
        solanaPrivateKeyBytes: solanaKeyBytes
      };
    }
    return { key: envKey, address: account.address, source: "env" };
  }
  const result = await generateAndSaveWallet();
  return {
    key: result.key,
    address: result.address,
    source: "generated",
    mnemonic: result.mnemonic,
    solanaPrivateKeyBytes: result.solanaPrivateKeyBytes
  };
}
async function recoverWalletFromMnemonic() {
  const mnemonic = await loadMnemonic();
  if (!mnemonic) {
    console.error(`[ClawRouter] No mnemonic found at ${MNEMONIC_FILE}`);
    console.error(`[ClawRouter] Cannot recover \u2014 no mnemonic to derive from.`);
    process.exit(1);
  }
  const existing = await loadSavedWallet().catch(() => void 0);
  if (existing) {
    console.error(`[ClawRouter] wallet.key already exists at ${WALLET_FILE}`);
    console.error(`[ClawRouter] Recovery not needed.`);
    process.exit(1);
  }
  const derived = deriveAllKeys(mnemonic);
  const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);
  const solanaAddress = await getSolanaAddress(solanaKeyBytes).catch(() => void 0);
  console.log(`[ClawRouter]`);
  console.log(`[ClawRouter] \u26A0  WALLET RECOVERY FROM MNEMONIC`);
  console.log(`[ClawRouter] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`);
  console.log(`[ClawRouter]   This only works if your mnemonic was originally`);
  console.log(`[ClawRouter]   generated by ClawRouter (not set manually).`);
  console.log(`[ClawRouter]`);
  console.log(`[ClawRouter]   Derived EVM Address    : ${derived.evmAddress}`);
  if (solanaAddress) {
    console.log(`[ClawRouter]   Derived Solana Address : ${solanaAddress}`);
  }
  console.log(`[ClawRouter]`);
  console.log(`[ClawRouter]   If the Solana address above matches your funded`);
  console.log(`[ClawRouter]   wallet, recovery is safe to proceed.`);
  console.log(`[ClawRouter] \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`);
  console.log(`[ClawRouter]`);
  await mkdir2(WALLET_DIR, { recursive: true });
  await writeFile(WALLET_FILE, derived.evmPrivateKey + "\n", { mode: 384 });
  console.log(`[ClawRouter] \u2713 wallet.key restored at ${WALLET_FILE}`);
  console.log(`[ClawRouter]   Run: npx @blockrun/clawrouter`);
  console.log(`[ClawRouter]`);
}
async function setupSolana() {
  const existing = await loadMnemonic();
  if (existing) {
    throw new Error("Solana wallet already set up. Mnemonic file exists at " + MNEMONIC_FILE);
  }
  const savedKey = await loadSavedWallet();
  if (!savedKey) {
    throw new Error(
      "No EVM wallet found. Run ClawRouter first to generate a wallet before setting up Solana."
    );
  }
  const mnemonic = generateWalletMnemonic();
  const solanaKeyBytes = deriveSolanaKeyBytes(mnemonic);
  await saveMnemonic(mnemonic);
  console.log(`[ClawRouter] Solana wallet set up successfully.`);
  console.log(`[ClawRouter] Mnemonic saved to ${MNEMONIC_FILE}`);
  console.log(`[ClawRouter] Existing EVM wallet unchanged.`);
  return { mnemonic, solanaPrivateKeyBytes: solanaKeyBytes };
}
async function savePaymentChain(chain3) {
  await mkdir2(WALLET_DIR, { recursive: true });
  await writeFile(CHAIN_FILE, chain3 + "\n", { mode: 384 });
}
async function loadPaymentChain() {
  try {
    const content = (await readTextFile(CHAIN_FILE)).trim();
    if (content === "solana") return "solana";
    return "base";
  } catch {
    return "base";
  }
}
async function resolvePaymentChain() {
  if (process["env"].CLAWROUTER_PAYMENT_CHAIN === "solana") return "solana";
  if (process["env"].CLAWROUTER_PAYMENT_CHAIN === "base") return "base";
  return loadPaymentChain();
}
var WALLET_DIR, WALLET_FILE, MNEMONIC_FILE, CHAIN_FILE, walletKeyAuth, envKeyAuth;
var init_auth = __esm({
  "src/auth.ts"() {
    "use strict";
    init_fs_read();
    init_accounts();
    init_wallet();
    WALLET_DIR = join6(homedir3(), ".openclaw", "blockrun");
    WALLET_FILE = join6(WALLET_DIR, "wallet.key");
    MNEMONIC_FILE = join6(WALLET_DIR, "mnemonic");
    CHAIN_FILE = join6(WALLET_DIR, "payment-chain");
    walletKeyAuth = {
      id: "wallet-key",
      label: "Wallet Private Key",
      hint: "Enter your EVM wallet private key (0x...) for x402 payments to BlockRun",
      kind: "api_key",
      run: async (ctx) => {
        const key = await ctx.prompter.text({
          message: "Enter your wallet private key (0x...)",
          validate: (value) => {
            const trimmed = value.trim();
            if (!trimmed.startsWith("0x")) return "Key must start with 0x";
            if (trimmed.length !== 66) return "Key must be 66 characters (0x + 64 hex)";
            if (!/^0x[0-9a-fA-F]{64}$/.test(trimmed)) return "Key must be valid hex";
            return void 0;
          }
        });
        if (!key || typeof key !== "string") {
          throw new Error("Wallet key is required");
        }
        return {
          profiles: [
            {
              profileId: "default",
              credential: { apiKey: key.trim() }
            }
          ],
          notes: [
            "Wallet key stored securely in OpenClaw credentials.",
            "Your wallet signs x402 USDC payments on Base for each LLM call.",
            "Fund your wallet with USDC on Base to start using BlockRun models."
          ]
        };
      }
    };
    envKeyAuth = {
      id: "env-key",
      label: "Environment Variable",
      hint: "Use BLOCKRUN_WALLET_KEY environment variable",
      kind: "api_key",
      run: async () => {
        const key = process["env"].BLOCKRUN_WALLET_KEY;
        if (!key) {
          throw new Error(
            "BLOCKRUN_WALLET_KEY environment variable is not set. Set it to your EVM wallet private key (0x...)."
          );
        }
        return {
          profiles: [
            {
              profileId: "default",
              credential: { apiKey: key.trim() }
            }
          ],
          notes: ["Using wallet key from BLOCKRUN_WALLET_KEY environment variable."]
        };
      }
    };
  }
});

// src/compression/types.ts
var DEFAULT_COMPRESSION_CONFIG;
var init_types2 = __esm({
  "src/compression/types.ts"() {
    "use strict";
    DEFAULT_COMPRESSION_CONFIG = {
      enabled: true,
      preserveRaw: true,
      layers: {
        deduplication: true,
        // Safe: removes duplicate messages
        whitespace: true,
        // Safe: normalizes whitespace
        dictionary: false,
        // DISABLED: requires model to understand codebook
        paths: false,
        // DISABLED: requires model to understand path codes
        jsonCompact: true,
        // Safe: just removes JSON whitespace
        observation: false,
        // DISABLED: may lose important context
        dynamicCodebook: false
        // DISABLED: requires model to understand codes
      },
      dictionary: {
        maxEntries: 50,
        minPhraseLength: 15,
        includeCodebookHeader: false
        // No codebook header needed
      }
    };
  }
});

// src/compression/layers/deduplication.ts
import crypto5 from "crypto";
function hashMessage2(message) {
  let contentStr = "";
  if (typeof message.content === "string") {
    contentStr = message.content;
  } else if (Array.isArray(message.content)) {
    contentStr = JSON.stringify(message.content);
  }
  const parts = [message.role, contentStr, message.tool_call_id || "", message.name || ""];
  if (message.tool_calls) {
    parts.push(
      JSON.stringify(
        message.tool_calls.map((tc) => ({
          name: tc.function.name,
          args: tc.function.arguments
        }))
      )
    );
  }
  const content = parts.join("|");
  return crypto5.createHash("md5").update(content).digest("hex");
}
function deduplicateMessages(messages) {
  const seen = /* @__PURE__ */ new Set();
  const result = [];
  let duplicatesRemoved = 0;
  const referencedToolCallIds = /* @__PURE__ */ new Set();
  for (const message of messages) {
    if (message.role === "tool" && message.tool_call_id) {
      referencedToolCallIds.add(message.tool_call_id);
    }
  }
  for (const message of messages) {
    if (message.role === "system") {
      result.push(message);
      continue;
    }
    if (message.role === "user") {
      result.push(message);
      continue;
    }
    if (message.role === "tool") {
      result.push(message);
      continue;
    }
    if (message.role === "assistant" && message.tool_calls) {
      const hasReferencedToolCall = message.tool_calls.some(
        (tc) => referencedToolCallIds.has(tc.id)
      );
      if (hasReferencedToolCall) {
        result.push(message);
        continue;
      }
    }
    const hash3 = hashMessage2(message);
    if (!seen.has(hash3)) {
      seen.add(hash3);
      result.push(message);
    } else {
      duplicatesRemoved++;
    }
  }
  return {
    messages: result,
    duplicatesRemoved,
    originalCount: messages.length
  };
}
var init_deduplication = __esm({
  "src/compression/layers/deduplication.ts"() {
    "use strict";
  }
});

// src/compression/layers/whitespace.ts
function normalizeWhitespace(content) {
  if (!content || typeof content !== "string") return content;
  return content.replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/\n{3,}/g, "\n\n").replace(/[ \t]+$/gm, "").replace(/([^\n]) {2,}/g, "$1 ").replace(/^[ ]{8,}/gm, (match) => "  ".repeat(Math.ceil(match.length / 4))).replace(/\t/g, "  ").trim();
}
function normalizeMessagesWhitespace(messages) {
  let charsSaved = 0;
  const result = messages.map((message) => {
    if (!message.content || typeof message.content !== "string") return message;
    const originalLength = message.content.length;
    const normalizedContent = normalizeWhitespace(message.content);
    charsSaved += originalLength - normalizedContent.length;
    return {
      ...message,
      content: normalizedContent
    };
  });
  return {
    messages: result,
    charsSaved
  };
}
var init_whitespace = __esm({
  "src/compression/layers/whitespace.ts"() {
    "use strict";
  }
});

// src/compression/codebook.ts
function getInverseCodebook() {
  const inverse = {};
  for (const [code, phrase] of Object.entries(STATIC_CODEBOOK)) {
    inverse[phrase] = code;
  }
  return inverse;
}
function generateCodebookHeader(usedCodes, pathMap = {}) {
  if (usedCodes.size === 0 && Object.keys(pathMap).length === 0) {
    return "";
  }
  const parts = [];
  if (usedCodes.size > 0) {
    const codeEntries = Array.from(usedCodes).map((code) => `${code}=${STATIC_CODEBOOK[code]}`).join(", ");
    parts.push(`[Dict: ${codeEntries}]`);
  }
  if (Object.keys(pathMap).length > 0) {
    const pathEntries = Object.entries(pathMap).map(([code, path2]) => `${code}=${path2}`).join(", ");
    parts.push(`[Paths: ${pathEntries}]`);
  }
  return parts.join("\n");
}
var STATIC_CODEBOOK;
var init_codebook = __esm({
  "src/compression/codebook.ts"() {
    "use strict";
    STATIC_CODEBOOK = {
      // High-impact: OpenClaw/Agent system prompt patterns (very common)
      $OC01: "unbrowse_",
      // Common prefix in tool names
      $OC02: "<location>",
      $OC03: "</location>",
      $OC04: "<name>",
      $OC05: "</name>",
      $OC06: "<description>",
      $OC07: "</description>",
      $OC08: "(may need login)",
      $OC09: "API skill for OpenClaw",
      $OC10: "endpoints",
      // Skill/tool markers
      $SK01: "<available_skills>",
      $SK02: "</available_skills>",
      $SK03: "<skill>",
      $SK04: "</skill>",
      // Schema patterns (very common in tool definitions)
      $T01: 'type: "function"',
      $T02: '"type": "function"',
      $T03: '"type": "string"',
      $T04: '"type": "object"',
      $T05: '"type": "array"',
      $T06: '"type": "boolean"',
      $T07: '"type": "number"',
      // Common descriptions
      $D01: "description:",
      $D02: '"description":',
      // Common instructions
      $I01: "You are a personal assistant",
      $I02: "Tool names are case-sensitive",
      $I03: "Call tools exactly as listed",
      $I04: "Use when",
      $I05: "without asking",
      // Safety phrases
      $S01: "Do not manipulate or persuade",
      $S02: "Prioritize safety and human oversight",
      $S03: "unless explicitly requested",
      // JSON patterns
      $J01: '"required": ["',
      $J02: '"properties": {',
      $J03: '"additionalProperties": false',
      // Heartbeat patterns
      $H01: "HEARTBEAT_OK",
      $H02: "Read HEARTBEAT.md if it exists",
      // Role markers
      $R01: '"role": "system"',
      $R02: '"role": "user"',
      $R03: '"role": "assistant"',
      $R04: '"role": "tool"',
      // Common endings/phrases
      $E01: "would you like to",
      $E02: "Let me know if you",
      $E03: "internal APIs",
      $E04: "session cookies",
      // BlockRun model aliases (common in prompts)
      $M01: "blockrun/",
      $M02: "openai/",
      $M03: "anthropic/",
      $M04: "google/",
      $M05: "xai/"
    };
  }
});

// src/compression/layers/dictionary.ts
function encodeContent(content, inverseCodebook) {
  if (!content || typeof content !== "string") {
    return { encoded: content, substitutions: 0, codes: /* @__PURE__ */ new Set(), charsSaved: 0 };
  }
  let encoded = content;
  let substitutions = 0;
  let charsSaved = 0;
  const codes = /* @__PURE__ */ new Set();
  const phrases = Object.keys(inverseCodebook).sort((a, b) => b.length - a.length);
  for (const phrase of phrases) {
    const code = inverseCodebook[phrase];
    const regex = new RegExp(escapeRegex(phrase), "g");
    const matches = encoded.match(regex);
    if (matches && matches.length > 0) {
      encoded = encoded.replace(regex, code);
      substitutions += matches.length;
      charsSaved += matches.length * (phrase.length - code.length);
      codes.add(code);
    }
  }
  return { encoded, substitutions, codes, charsSaved };
}
function escapeRegex(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function encodeMessages(messages) {
  const inverseCodebook = getInverseCodebook();
  let totalSubstitutions = 0;
  let totalCharsSaved = 0;
  const allUsedCodes = /* @__PURE__ */ new Set();
  const result = messages.map((message) => {
    if (!message.content || typeof message.content !== "string") return message;
    const { encoded, substitutions, codes, charsSaved } = encodeContent(
      message.content,
      inverseCodebook
    );
    totalSubstitutions += substitutions;
    totalCharsSaved += charsSaved;
    codes.forEach((code) => allUsedCodes.add(code));
    return {
      ...message,
      content: encoded
    };
  });
  return {
    messages: result,
    substitutionCount: totalSubstitutions,
    usedCodes: allUsedCodes,
    charsSaved: totalCharsSaved
  };
}
var init_dictionary = __esm({
  "src/compression/layers/dictionary.ts"() {
    "use strict";
    init_codebook();
  }
});

// src/compression/layers/paths.ts
function extractPaths(messages) {
  const paths = [];
  for (const message of messages) {
    if (!message.content || typeof message.content !== "string") continue;
    const matches = message.content.match(PATH_REGEX);
    if (matches) {
      paths.push(...matches);
    }
  }
  return paths;
}
function findFrequentPrefixes(paths) {
  const prefixCounts = /* @__PURE__ */ new Map();
  for (const path2 of paths) {
    const parts = path2.split("/").filter(Boolean);
    for (let i = 2; i < parts.length; i++) {
      const prefix = "/" + parts.slice(0, i).join("/") + "/";
      prefixCounts.set(prefix, (prefixCounts.get(prefix) || 0) + 1);
    }
  }
  return Array.from(prefixCounts.entries()).filter(([, count]) => count >= 3).sort((a, b) => b[0].length - a[0].length).slice(0, 5).map(([prefix]) => prefix);
}
function shortenPaths(messages) {
  const allPaths = extractPaths(messages);
  if (allPaths.length < 5) {
    return {
      messages,
      pathMap: {},
      charsSaved: 0
    };
  }
  const prefixes = findFrequentPrefixes(allPaths);
  if (prefixes.length === 0) {
    return {
      messages,
      pathMap: {},
      charsSaved: 0
    };
  }
  const pathMap = {};
  prefixes.forEach((prefix, i) => {
    pathMap[`$P${i + 1}`] = prefix;
  });
  let charsSaved = 0;
  const result = messages.map((message) => {
    if (!message.content || typeof message.content !== "string") return message;
    let content = message.content;
    const originalLength = content.length;
    for (const [code, prefix] of Object.entries(pathMap)) {
      content = content.split(prefix).join(code + "/");
    }
    charsSaved += originalLength - content.length;
    return {
      ...message,
      content
    };
  });
  return {
    messages: result,
    pathMap,
    charsSaved
  };
}
var PATH_REGEX;
var init_paths = __esm({
  "src/compression/layers/paths.ts"() {
    "use strict";
    PATH_REGEX = /(?:\/[\w.-]+){3,}/g;
  }
});

// src/compression/layers/json-compact.ts
function compactJson(jsonString) {
  try {
    const parsed = JSON.parse(jsonString);
    return JSON.stringify(parsed);
  } catch {
    return jsonString;
  }
}
function looksLikeJson(str) {
  const trimmed = str.trim();
  return trimmed.startsWith("{") && trimmed.endsWith("}") || trimmed.startsWith("[") && trimmed.endsWith("]");
}
function compactToolCalls(toolCalls) {
  return toolCalls.map((tc) => ({
    ...tc,
    function: {
      ...tc.function,
      arguments: compactJson(tc.function.arguments)
    }
  }));
}
function compactMessagesJson(messages) {
  let charsSaved = 0;
  const result = messages.map((message) => {
    const newMessage = { ...message };
    if (message.tool_calls && message.tool_calls.length > 0) {
      const originalLength = JSON.stringify(message.tool_calls).length;
      newMessage.tool_calls = compactToolCalls(message.tool_calls);
      const newLength = JSON.stringify(newMessage.tool_calls).length;
      charsSaved += originalLength - newLength;
    }
    if (message.role === "tool" && message.content && typeof message.content === "string" && looksLikeJson(message.content)) {
      const originalLength = message.content.length;
      const compacted = compactJson(message.content);
      charsSaved += originalLength - compacted.length;
      newMessage.content = compacted;
    }
    return newMessage;
  });
  return {
    messages: result,
    charsSaved
  };
}
var init_json_compact = __esm({
  "src/compression/layers/json-compact.ts"() {
    "use strict";
  }
});

// src/compression/layers/observation.ts
function compressToolResult(content) {
  if (!content || content.length <= TOOL_RESULT_THRESHOLD) {
    return content;
  }
  const lines = content.split("\n").map((l2) => l2.trim()).filter(Boolean);
  const errorLines = lines.filter(
    (l2) => /error|exception|failed|denied|refused|timeout|invalid/i.test(l2) && l2.length < 200
  );
  const statusLines = lines.filter(
    (l2) => /success|complete|created|updated|found|result|status|total|count/i.test(l2) && l2.length < 150
  );
  const jsonMatches = [];
  const jsonPattern = /"(id|name|status|error|message|count|total|url|path)":\s*"?([^",}\n]+)"?/gi;
  let match;
  while ((match = jsonPattern.exec(content)) !== null) {
    jsonMatches.push(`${match[1]}: ${match[2].slice(0, 50)}`);
  }
  const firstLine = lines[0]?.slice(0, 100);
  const lastLine = lines.length > 1 ? lines[lines.length - 1]?.slice(0, 100) : "";
  const parts = [];
  if (errorLines.length > 0) {
    parts.push("[ERR] " + errorLines.slice(0, 3).join(" | "));
  }
  if (statusLines.length > 0) {
    parts.push(statusLines.slice(0, 3).join(" | "));
  }
  if (jsonMatches.length > 0) {
    parts.push(jsonMatches.slice(0, 5).join(", "));
  }
  if (parts.length === 0) {
    parts.push(firstLine || "");
    if (lines.length > 2) {
      parts.push(`[...${lines.length - 2} lines...]`);
    }
    if (lastLine && lastLine !== firstLine) {
      parts.push(lastLine);
    }
  }
  let result = parts.join("\n");
  if (result.length > COMPRESSED_RESULT_MAX) {
    result = result.slice(0, COMPRESSED_RESULT_MAX - 20) + "\n[...truncated]";
  }
  return result;
}
function deduplicateLargeBlocks(messages) {
  const blockHashes = /* @__PURE__ */ new Map();
  let charsSaved = 0;
  const result = messages.map((msg, idx) => {
    if (!msg.content || typeof msg.content !== "string" || msg.content.length < 500) {
      return msg;
    }
    const blockKey = msg.content.slice(0, 200);
    if (blockHashes.has(blockKey)) {
      const firstIdx = blockHashes.get(blockKey);
      const original = msg.content;
      const compressed = `[See message #${firstIdx + 1} - same content]`;
      charsSaved += original.length - compressed.length;
      return { ...msg, content: compressed };
    }
    blockHashes.set(blockKey, idx);
    return msg;
  });
  return { messages: result, charsSaved };
}
function compressObservations(messages) {
  let charsSaved = 0;
  let observationsCompressed = 0;
  let result = messages.map((msg) => {
    if (msg.role !== "tool" || !msg.content || typeof msg.content !== "string") {
      return msg;
    }
    const original = msg.content;
    if (original.length <= TOOL_RESULT_THRESHOLD) {
      return msg;
    }
    const compressed = compressToolResult(original);
    const saved = original.length - compressed.length;
    if (saved > 50) {
      charsSaved += saved;
      observationsCompressed++;
      return { ...msg, content: compressed };
    }
    return msg;
  });
  const dedupResult = deduplicateLargeBlocks(result);
  result = dedupResult.messages;
  charsSaved += dedupResult.charsSaved;
  return {
    messages: result,
    charsSaved,
    observationsCompressed
  };
}
var TOOL_RESULT_THRESHOLD, COMPRESSED_RESULT_MAX;
var init_observation = __esm({
  "src/compression/layers/observation.ts"() {
    "use strict";
    TOOL_RESULT_THRESHOLD = 500;
    COMPRESSED_RESULT_MAX = 300;
  }
});

// src/compression/layers/dynamic-codebook.ts
function findRepeatedPhrases(allContent) {
  const phrases = /* @__PURE__ */ new Map();
  const segments = allContent.split(/(?<=[.!?\n])\s+/);
  for (const segment of segments) {
    const trimmed = segment.trim();
    if (trimmed.length >= MIN_PHRASE_LENGTH && trimmed.length <= MAX_PHRASE_LENGTH) {
      phrases.set(trimmed, (phrases.get(trimmed) || 0) + 1);
    }
  }
  const lines = allContent.split("\n");
  for (const line of lines) {
    const trimmed = line.trim();
    if (trimmed.length >= MIN_PHRASE_LENGTH && trimmed.length <= MAX_PHRASE_LENGTH) {
      phrases.set(trimmed, (phrases.get(trimmed) || 0) + 1);
    }
  }
  return phrases;
}
function buildDynamicCodebook(messages) {
  let allContent = "";
  for (const msg of messages) {
    if (msg.content && typeof msg.content === "string") {
      allContent += msg.content + "\n";
    }
  }
  const phrases = findRepeatedPhrases(allContent);
  const candidates = [];
  for (const [phrase, count] of phrases.entries()) {
    if (count >= MIN_FREQUENCY) {
      const codeLength = 4;
      const savings = (phrase.length - codeLength) * count;
      if (savings > 50) {
        candidates.push({ phrase, count, savings });
      }
    }
  }
  candidates.sort((a, b) => b.savings - a.savings);
  const topCandidates = candidates.slice(0, MAX_ENTRIES);
  const codebook = {};
  topCandidates.forEach((c, i) => {
    const code = `${CODE_PREFIX}${String(i + 1).padStart(2, "0")}`;
    codebook[code] = c.phrase;
  });
  return codebook;
}
function escapeRegex2(str) {
  if (!str || typeof str !== "string") return "";
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function applyDynamicCodebook(messages) {
  const codebook = buildDynamicCodebook(messages);
  if (Object.keys(codebook).length === 0) {
    return {
      messages,
      charsSaved: 0,
      dynamicCodes: {},
      substitutions: 0
    };
  }
  const phraseToCode = {};
  for (const [code, phrase] of Object.entries(codebook)) {
    phraseToCode[phrase] = code;
  }
  const sortedPhrases = Object.keys(phraseToCode).sort((a, b) => b.length - a.length);
  let charsSaved = 0;
  let substitutions = 0;
  const result = messages.map((msg) => {
    if (!msg.content || typeof msg.content !== "string") return msg;
    let content = msg.content;
    for (const phrase of sortedPhrases) {
      const code = phraseToCode[phrase];
      const regex = new RegExp(escapeRegex2(phrase), "g");
      const matches = content.match(regex);
      if (matches) {
        content = content.replace(regex, code);
        charsSaved += (phrase.length - code.length) * matches.length;
        substitutions += matches.length;
      }
    }
    return { ...msg, content };
  });
  return {
    messages: result,
    charsSaved,
    dynamicCodes: codebook,
    substitutions
  };
}
function generateDynamicCodebookHeader(codebook) {
  if (Object.keys(codebook).length === 0) return "";
  const entries = Object.entries(codebook).slice(0, 20).map(([code, phrase]) => {
    const displayPhrase = phrase.length > 40 ? phrase.slice(0, 37) + "..." : phrase;
    return `${code}=${displayPhrase}`;
  }).join(", ");
  return `[DynDict: ${entries}]`;
}
var MIN_PHRASE_LENGTH, MAX_PHRASE_LENGTH, MIN_FREQUENCY, MAX_ENTRIES, CODE_PREFIX;
var init_dynamic_codebook = __esm({
  "src/compression/layers/dynamic-codebook.ts"() {
    "use strict";
    MIN_PHRASE_LENGTH = 20;
    MAX_PHRASE_LENGTH = 200;
    MIN_FREQUENCY = 3;
    MAX_ENTRIES = 100;
    CODE_PREFIX = "$D";
  }
});

// src/compression/index.ts
function calculateTotalChars(messages) {
  return messages.reduce((total, msg) => {
    let chars = 0;
    if (typeof msg.content === "string") {
      chars = msg.content.length;
    } else if (Array.isArray(msg.content)) {
      chars = JSON.stringify(msg.content).length;
    }
    if (msg.tool_calls) {
      chars += JSON.stringify(msg.tool_calls).length;
    }
    return total + chars;
  }, 0);
}
function cloneMessages(messages) {
  return JSON.parse(JSON.stringify(messages));
}
function prependCodebookHeader(messages, usedCodes, pathMap) {
  const header = generateCodebookHeader(usedCodes, pathMap);
  if (!header) return messages;
  const userIndex = messages.findIndex((m) => m.role === "user");
  if (userIndex === -1) {
    return [{ role: "system", content: header }, ...messages];
  }
  return messages.map((msg, i) => {
    if (i === userIndex) {
      if (typeof msg.content === "string") {
        return {
          ...msg,
          content: `${header}

${msg.content}`
        };
      }
    }
    return msg;
  });
}
async function compressContext(messages, config = {}) {
  const fullConfig = {
    ...DEFAULT_COMPRESSION_CONFIG,
    ...config,
    layers: {
      ...DEFAULT_COMPRESSION_CONFIG.layers,
      ...config.layers
    },
    dictionary: {
      ...DEFAULT_COMPRESSION_CONFIG.dictionary,
      ...config.dictionary
    }
  };
  if (!fullConfig.enabled) {
    const originalChars2 = calculateTotalChars(messages);
    return {
      messages,
      originalMessages: messages,
      originalChars: originalChars2,
      compressedChars: originalChars2,
      compressionRatio: 1,
      stats: {
        duplicatesRemoved: 0,
        whitespaceSavedChars: 0,
        dictionarySubstitutions: 0,
        pathsShortened: 0,
        jsonCompactedChars: 0,
        observationsCompressed: 0,
        observationCharsSaved: 0,
        dynamicSubstitutions: 0,
        dynamicCharsSaved: 0
      },
      codebook: {},
      pathMap: {},
      dynamicCodes: {}
    };
  }
  const originalMessages = fullConfig.preserveRaw ? cloneMessages(messages) : messages;
  const originalChars = calculateTotalChars(messages);
  const stats = {
    duplicatesRemoved: 0,
    whitespaceSavedChars: 0,
    dictionarySubstitutions: 0,
    pathsShortened: 0,
    jsonCompactedChars: 0,
    observationsCompressed: 0,
    observationCharsSaved: 0,
    dynamicSubstitutions: 0,
    dynamicCharsSaved: 0
  };
  let result = cloneMessages(messages);
  let usedCodes = /* @__PURE__ */ new Set();
  let pathMap = {};
  let dynamicCodes = {};
  if (fullConfig.layers.deduplication) {
    const dedupResult = deduplicateMessages(result);
    result = dedupResult.messages;
    stats.duplicatesRemoved = dedupResult.duplicatesRemoved;
  }
  if (fullConfig.layers.whitespace) {
    const wsResult = normalizeMessagesWhitespace(result);
    result = wsResult.messages;
    stats.whitespaceSavedChars = wsResult.charsSaved;
  }
  if (fullConfig.layers.dictionary) {
    const dictResult = encodeMessages(result);
    result = dictResult.messages;
    stats.dictionarySubstitutions = dictResult.substitutionCount;
    usedCodes = dictResult.usedCodes;
  }
  if (fullConfig.layers.paths) {
    const pathResult = shortenPaths(result);
    result = pathResult.messages;
    pathMap = pathResult.pathMap;
    stats.pathsShortened = Object.keys(pathMap).length;
  }
  if (fullConfig.layers.jsonCompact) {
    const jsonResult = compactMessagesJson(result);
    result = jsonResult.messages;
    stats.jsonCompactedChars = jsonResult.charsSaved;
  }
  if (fullConfig.layers.observation) {
    const obsResult = compressObservations(result);
    result = obsResult.messages;
    stats.observationsCompressed = obsResult.observationsCompressed;
    stats.observationCharsSaved = obsResult.charsSaved;
  }
  if (fullConfig.layers.dynamicCodebook) {
    const dynResult = applyDynamicCodebook(result);
    result = dynResult.messages;
    stats.dynamicSubstitutions = dynResult.substitutions;
    stats.dynamicCharsSaved = dynResult.charsSaved;
    dynamicCodes = dynResult.dynamicCodes;
  }
  if (fullConfig.dictionary.includeCodebookHeader && (usedCodes.size > 0 || Object.keys(pathMap).length > 0 || Object.keys(dynamicCodes).length > 0)) {
    result = prependCodebookHeader(result, usedCodes, pathMap);
    if (Object.keys(dynamicCodes).length > 0) {
      const dynHeader = generateDynamicCodebookHeader(dynamicCodes);
      if (dynHeader) {
        const systemIndex = result.findIndex((m) => m.role === "system");
        if (systemIndex >= 0 && typeof result[systemIndex].content === "string") {
          result[systemIndex] = {
            ...result[systemIndex],
            content: `${dynHeader}
${result[systemIndex].content}`
          };
        }
      }
    }
  }
  const compressedChars = calculateTotalChars(result);
  const compressionRatio = compressedChars / originalChars;
  const usedCodebook = {};
  usedCodes.forEach((code) => {
    usedCodebook[code] = STATIC_CODEBOOK[code];
  });
  return {
    messages: result,
    originalMessages,
    originalChars,
    compressedChars,
    compressionRatio,
    stats,
    codebook: usedCodebook,
    pathMap,
    dynamicCodes
  };
}
function shouldCompress(messages) {
  const chars = calculateTotalChars(messages);
  return chars > 5e3;
}
var init_compression = __esm({
  "src/compression/index.ts"() {
    "use strict";
    init_types2();
    init_deduplication();
    init_whitespace();
    init_dictionary();
    init_paths();
    init_json_compact();
    init_observation();
    init_dynamic_codebook();
    init_codebook();
    init_types2();
    init_codebook();
  }
});

// src/session.ts
import { createHash as createHash3 } from "crypto";
function getSessionId(headers, headerName = DEFAULT_SESSION_CONFIG.headerName) {
  const value = headers[headerName] || headers[headerName.toLowerCase()];
  if (typeof value === "string" && value.length > 0) {
    return value;
  }
  if (Array.isArray(value) && value.length > 0) {
    return value[0];
  }
  return void 0;
}
function deriveSessionId(messages) {
  const firstUser = messages.find((m) => m.role === "user");
  if (!firstUser) return void 0;
  const content = typeof firstUser.content === "string" ? firstUser.content : JSON.stringify(firstUser.content);
  return createHash3("sha256").update(content).digest("hex").slice(0, 8);
}
function hashRequestContent(lastUserContent, toolCallNames) {
  const normalized = lastUserContent.replace(/\s+/g, " ").trim().slice(0, 500);
  const toolSuffix = toolCallNames?.length ? `|tools:${toolCallNames.sort().join(",")}` : "";
  return createHash3("sha256").update(normalized + toolSuffix).digest("hex").slice(0, 12);
}
var DEFAULT_SESSION_CONFIG, SessionStore;
var init_session = __esm({
  "src/session.ts"() {
    "use strict";
    DEFAULT_SESSION_CONFIG = {
      enabled: true,
      timeoutMs: 30 * 60 * 1e3,
      // 30 minutes
      headerName: "x-session-id"
    };
    SessionStore = class {
      sessions = /* @__PURE__ */ new Map();
      config;
      cleanupInterval = null;
      constructor(config = {}) {
        this.config = { ...DEFAULT_SESSION_CONFIG, ...config };
        if (this.config.enabled) {
          this.cleanupInterval = setInterval(() => this.cleanup(), 5 * 60 * 1e3);
        }
      }
      /**
       * Get the pinned model for a session, if any.
       */
      getSession(sessionId) {
        if (!this.config.enabled || !sessionId) {
          return void 0;
        }
        const entry = this.sessions.get(sessionId);
        if (!entry) {
          return void 0;
        }
        const now = Date.now();
        if (now - entry.lastUsedAt > this.config.timeoutMs) {
          this.sessions.delete(sessionId);
          return void 0;
        }
        return entry;
      }
      /**
       * Pin a model to a session.
       *
       * Pass `userExplicit: true` when the user explicitly chose this model
       * (e.g. via /model command or by sending an explicit non-profile model).
       * Explicit pins are sticky — they survive tier-escalation comparisons so
       * that the user's choice keeps winning even if subsequent requests use a
       * routing profile that would normally re-route.
       */
      setSession(sessionId, model, tier, userExplicit) {
        if (!this.config.enabled || !sessionId) {
          return;
        }
        const existing = this.sessions.get(sessionId);
        const now = Date.now();
        if (existing) {
          existing.lastUsedAt = now;
          existing.requestCount++;
          if (existing.model !== model) {
            existing.model = model;
            existing.tier = tier;
          }
          if (userExplicit) {
            existing.userExplicit = true;
          }
        } else {
          this.sessions.set(sessionId, {
            model,
            tier,
            createdAt: now,
            lastUsedAt: now,
            requestCount: 1,
            userExplicit: userExplicit || void 0,
            recentHashes: [],
            strikes: 0,
            escalated: false,
            sessionCostMicros: 0n
          });
        }
      }
      /**
       * Touch a session to extend its timeout.
       */
      touchSession(sessionId) {
        if (!this.config.enabled || !sessionId) {
          return;
        }
        const entry = this.sessions.get(sessionId);
        if (entry) {
          entry.lastUsedAt = Date.now();
          entry.requestCount++;
        }
      }
      /**
       * Clear a specific session.
       */
      clearSession(sessionId) {
        this.sessions.delete(sessionId);
      }
      /**
       * Clear all sessions.
       */
      clearAll() {
        this.sessions.clear();
      }
      /**
       * Get session stats for debugging.
       */
      getStats() {
        const now = Date.now();
        const sessions = Array.from(this.sessions.entries()).map(([id, entry]) => ({
          id: id.slice(0, 8) + "...",
          model: entry.model,
          age: Math.round((now - entry.createdAt) / 1e3)
        }));
        return { count: this.sessions.size, sessions };
      }
      /**
       * Clean up expired sessions.
       */
      cleanup() {
        const now = Date.now();
        for (const [id, entry] of this.sessions) {
          if (now - entry.lastUsedAt > this.config.timeoutMs) {
            this.sessions.delete(id);
          }
        }
      }
      /**
       * Record a request content hash and detect repetitive patterns.
       * Returns true if escalation should be triggered (3+ consecutive similar requests).
       */
      recordRequestHash(sessionId, hash3) {
        const entry = this.sessions.get(sessionId);
        if (!entry) return false;
        const prev = entry.recentHashes;
        if (prev.length > 0 && prev[prev.length - 1] === hash3) {
          entry.strikes++;
        } else {
          entry.strikes = 0;
        }
        entry.recentHashes.push(hash3);
        if (entry.recentHashes.length > 3) {
          entry.recentHashes.shift();
        }
        return entry.strikes >= 2 && !entry.escalated;
      }
      /**
       * Escalate session to next tier. Returns the new model/tier or null if already at max.
       */
      escalateSession(sessionId, tierConfigs) {
        const entry = this.sessions.get(sessionId);
        if (!entry) return null;
        const TIER_ORDER = ["SIMPLE", "MEDIUM", "COMPLEX", "REASONING"];
        const currentIdx = TIER_ORDER.indexOf(entry.tier);
        if (currentIdx < 0 || currentIdx >= TIER_ORDER.length - 1) return null;
        const nextTier = TIER_ORDER[currentIdx + 1];
        const nextConfig = tierConfigs[nextTier];
        if (!nextConfig) return null;
        entry.model = nextConfig.primary;
        entry.tier = nextTier;
        entry.strikes = 0;
        entry.escalated = true;
        return { model: nextConfig.primary, tier: nextTier };
      }
      /**
       * Add cost to a session's running total for maxCostPerRun tracking.
       * Cost is in USDC 6-decimal units (micros).
       * Creates a cost-tracking-only entry if none exists (e.g., explicit model requests
       * that never go through the routing path).
       */
      addSessionCost(sessionId, additionalMicros) {
        let entry = this.sessions.get(sessionId);
        if (!entry) {
          const now = Date.now();
          entry = {
            model: "",
            tier: "DIRECT",
            createdAt: now,
            lastUsedAt: now,
            requestCount: 0,
            recentHashes: [],
            strikes: 0,
            escalated: false,
            sessionCostMicros: 0n
          };
          this.sessions.set(sessionId, entry);
        }
        entry.sessionCostMicros += additionalMicros;
      }
      /**
       * Get the total accumulated cost for a session in USD.
       */
      getSessionCostUsd(sessionId) {
        const entry = this.sessions.get(sessionId);
        if (!entry) return 0;
        return Number(entry.sessionCostMicros) / 1e6;
      }
      /**
       * Stop the cleanup interval.
       */
      close() {
        if (this.cleanupInterval) {
          clearInterval(this.cleanupInterval);
          this.cleanupInterval = null;
        }
      }
    };
  }
});

// src/updater.ts
function compareSemver(a, b) {
  const pa = a.split(".").map(Number);
  const pb = b.split(".").map(Number);
  for (let i = 0; i < 3; i++) {
    if ((pa[i] || 0) > (pb[i] || 0)) return 1;
    if ((pa[i] || 0) < (pb[i] || 0)) return -1;
  }
  return 0;
}
async function checkForUpdates() {
  try {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), CHECK_TIMEOUT_MS);
    const res = await fetch(NPM_REGISTRY, {
      signal: controller.signal,
      headers: { Accept: "application/json" }
    });
    clearTimeout(timeout);
    if (!res.ok) return;
    const data = await res.json();
    const latest = data.version;
    if (!latest) return;
    if (compareSemver(latest, VERSION) > 0) {
      console.log("");
      console.log(`\x1B[33m\u2B06\uFE0F  ClawRouter ${latest} available (you have ${VERSION})\x1B[0m`);
      console.log(`   Run: \x1B[36mnpx @blockrun/clawrouter@latest\x1B[0m`);
      console.log(`   Docs: \x1B[36mhttps://blockrun.ai/clawrouter.md\x1B[0m`);
      console.log("");
    }
  } catch {
  }
}
var NPM_REGISTRY, CHECK_TIMEOUT_MS;
var init_updater = __esm({
  "src/updater.ts"() {
    "use strict";
    init_version4();
    NPM_REGISTRY = "https://registry.npmjs.org/@blockrun/clawrouter/latest";
    CHECK_TIMEOUT_MS = 5e3;
  }
});

// src/exclude-models.ts
import { readFileSync, writeFileSync, mkdirSync } from "fs";
import { join as join7, dirname as dirname2 } from "path";
import { homedir as homedir4 } from "os";
function loadExcludeList(filePath = DEFAULT_FILE_PATH) {
  try {
    const raw = readFileSync(filePath, "utf-8");
    const arr = JSON.parse(raw);
    if (Array.isArray(arr)) {
      return new Set(arr.filter((x) => typeof x === "string"));
    }
    return /* @__PURE__ */ new Set();
  } catch {
    return /* @__PURE__ */ new Set();
  }
}
function saveExcludeList(set, filePath) {
  const sorted = [...set].sort();
  const dir = dirname2(filePath);
  mkdirSync(dir, { recursive: true });
  writeFileSync(filePath, JSON.stringify(sorted, null, 2) + "\n", "utf-8");
}
function addExclusion(model, filePath = DEFAULT_FILE_PATH) {
  const resolved = resolveModelAlias(model);
  const set = loadExcludeList(filePath);
  set.add(resolved);
  saveExcludeList(set, filePath);
  return resolved;
}
function removeExclusion(model, filePath = DEFAULT_FILE_PATH) {
  const resolved = resolveModelAlias(model);
  const set = loadExcludeList(filePath);
  const had = set.delete(resolved);
  if (had) {
    saveExcludeList(set, filePath);
  }
  return had;
}
function clearExclusions(filePath = DEFAULT_FILE_PATH) {
  saveExcludeList(/* @__PURE__ */ new Set(), filePath);
}
var DEFAULT_FILE_PATH;
var init_exclude_models = __esm({
  "src/exclude-models.ts"() {
    "use strict";
    init_models();
    DEFAULT_FILE_PATH = join7(homedir4(), ".openclaw", "blockrun", "exclude-models.json");
  }
});

// src/config.ts
var DEFAULT_PORT, PROXY_PORT;
var init_config2 = __esm({
  "src/config.ts"() {
    "use strict";
    DEFAULT_PORT = 8402;
    PROXY_PORT = (() => {
      const envPort = process["env"].BLOCKRUN_PROXY_PORT;
      if (envPort) {
        const parsed = parseInt(envPort, 10);
        if (!isNaN(parsed) && parsed > 0 && parsed < 65536) {
          return parsed;
        }
      }
      return DEFAULT_PORT;
    })();
  }
});

// src/journal.ts
var DEFAULT_CONFIG2, SessionJournal;
var init_journal = __esm({
  "src/journal.ts"() {
    "use strict";
    DEFAULT_CONFIG2 = {
      maxEntries: 100,
      maxAgeMs: 24 * 60 * 60 * 1e3,
      // 24 hours
      maxEventsPerResponse: 5
    };
    SessionJournal = class {
      journals = /* @__PURE__ */ new Map();
      config;
      constructor(config) {
        this.config = { ...DEFAULT_CONFIG2, ...config };
      }
      /**
       * Extract key events from assistant response content.
       * Looks for patterns like "I created...", "I fixed...", "Successfully..."
       */
      extractEvents(content) {
        if (!content || typeof content !== "string") {
          return [];
        }
        const events = [];
        const seen = /* @__PURE__ */ new Set();
        const patterns = [
          // Creation patterns
          /I (?:also |then |have |)?(?:created|implemented|added|wrote|built|generated|set up|initialized) ([^.!?\n]{10,150})/gi,
          // Fix patterns
          /I (?:also |then |have |)?(?:fixed|resolved|solved|patched|corrected|addressed|debugged) ([^.!?\n]{10,150})/gi,
          // Completion patterns
          /I (?:also |then |have |)?(?:completed|finished|done with|wrapped up) ([^.!?\n]{10,150})/gi,
          // Update patterns
          /I (?:also |then |have |)?(?:updated|modified|changed|refactored|improved|enhanced|optimized) ([^.!?\n]{10,150})/gi,
          // Success patterns
          /Successfully ([^.!?\n]{10,150})/gi,
          // Tool usage patterns (when agent uses tools)
          /I (?:also |then |have |)?(?:ran|executed|called|invoked) ([^.!?\n]{10,100})/gi
        ];
        for (const pattern of patterns) {
          pattern.lastIndex = 0;
          let match;
          while ((match = pattern.exec(content)) !== null) {
            const action = match[0].trim();
            const normalized = action.toLowerCase();
            if (seen.has(normalized)) {
              continue;
            }
            if (action.length >= 15 && action.length <= 200) {
              events.push(action);
              seen.add(normalized);
            }
            if (events.length >= this.config.maxEventsPerResponse) {
              break;
            }
          }
          if (events.length >= this.config.maxEventsPerResponse) {
            break;
          }
        }
        return events;
      }
      /**
       * Record events to the session journal.
       */
      record(sessionId, events, model) {
        if (!sessionId || !events.length) {
          return;
        }
        const journal = this.journals.get(sessionId) || [];
        const now = Date.now();
        for (const action of events) {
          journal.push({
            timestamp: now,
            action,
            model
          });
        }
        const cutoff = now - this.config.maxAgeMs;
        const trimmed = journal.filter((e7) => e7.timestamp > cutoff).slice(-this.config.maxEntries);
        this.journals.set(sessionId, trimmed);
      }
      /**
       * Check if the user message indicates a need for historical context.
       */
      needsContext(lastUserMessage) {
        if (!lastUserMessage || typeof lastUserMessage !== "string") {
          return false;
        }
        const lower = lastUserMessage.toLowerCase();
        const triggers = [
          // Direct questions about past work
          "what did you do",
          "what have you done",
          "what did we do",
          "what have we done",
          // Temporal references
          "earlier",
          "before",
          "previously",
          "this session",
          "today",
          "so far",
          // Summary requests
          "remind me",
          "summarize",
          "summary of",
          "recap",
          // Progress inquiries
          "your work",
          "your progress",
          "accomplished",
          "achievements",
          "completed tasks"
        ];
        return triggers.some((t) => lower.includes(t));
      }
      /**
       * Format the journal for injection into system message.
       * Returns null if journal is empty.
       */
      format(sessionId) {
        const journal = this.journals.get(sessionId);
        if (!journal?.length) {
          return null;
        }
        const lines = journal.map((e7) => {
          const time = new Date(e7.timestamp).toLocaleTimeString("en-US", {
            hour: "2-digit",
            minute: "2-digit",
            hour12: true
          });
          return `- ${time}: ${e7.action}`;
        });
        return `[Session Memory - Key Actions]
${lines.join("\n")}`;
      }
      /**
       * Get the raw journal entries for a session (for debugging/testing).
       */
      getEntries(sessionId) {
        return this.journals.get(sessionId) || [];
      }
      /**
       * Clear journal for a specific session.
       */
      clear(sessionId) {
        this.journals.delete(sessionId);
      }
      /**
       * Clear all journals.
       */
      clearAll() {
        this.journals.clear();
      }
      /**
       * Get stats about the journal.
       */
      getStats() {
        let totalEntries = 0;
        for (const entries of this.journals.values()) {
          totalEntries += entries.length;
        }
        return {
          sessions: this.journals.size,
          totalEntries
        };
      }
    };
  }
});

// node_modules/undici/lib/core/symbols.js
var require_symbols = __commonJS({
  "node_modules/undici/lib/core/symbols.js"(exports, module) {
    "use strict";
    module.exports = {
      kClose: /* @__PURE__ */ Symbol("close"),
      kDestroy: /* @__PURE__ */ Symbol("destroy"),
      kDispatch: /* @__PURE__ */ Symbol("dispatch"),
      kUrl: /* @__PURE__ */ Symbol("url"),
      kWriting: /* @__PURE__ */ Symbol("writing"),
      kResuming: /* @__PURE__ */ Symbol("resuming"),
      kQueue: /* @__PURE__ */ Symbol("queue"),
      kConnect: /* @__PURE__ */ Symbol("connect"),
      kConnecting: /* @__PURE__ */ Symbol("connecting"),
      kKeepAliveDefaultTimeout: /* @__PURE__ */ Symbol("default keep alive timeout"),
      kKeepAliveMaxTimeout: /* @__PURE__ */ Symbol("max keep alive timeout"),
      kKeepAliveTimeoutThreshold: /* @__PURE__ */ Symbol("keep alive timeout threshold"),
      kKeepAliveTimeoutValue: /* @__PURE__ */ Symbol("keep alive timeout"),
      kKeepAlive: /* @__PURE__ */ Symbol("keep alive"),
      kHeadersTimeout: /* @__PURE__ */ Symbol("headers timeout"),
      kBodyTimeout: /* @__PURE__ */ Symbol("body timeout"),
      kServerName: /* @__PURE__ */ Symbol("server name"),
      kLocalAddress: /* @__PURE__ */ Symbol("local address"),
      kHost: /* @__PURE__ */ Symbol("host"),
      kNoRef: /* @__PURE__ */ Symbol("no ref"),
      kBodyUsed: /* @__PURE__ */ Symbol("used"),
      kBody: /* @__PURE__ */ Symbol("abstracted request body"),
      kRunning: /* @__PURE__ */ Symbol("running"),
      kBlocking: /* @__PURE__ */ Symbol("blocking"),
      kPending: /* @__PURE__ */ Symbol("pending"),
      kSize: /* @__PURE__ */ Symbol("size"),
      kBusy: /* @__PURE__ */ Symbol("busy"),
      kQueued: /* @__PURE__ */ Symbol("queued"),
      kFree: /* @__PURE__ */ Symbol("free"),
      kConnected: /* @__PURE__ */ Symbol("connected"),
      kClosed: /* @__PURE__ */ Symbol("closed"),
      kNeedDrain: /* @__PURE__ */ Symbol("need drain"),
      kReset: /* @__PURE__ */ Symbol("reset"),
      kDestroyed: /* @__PURE__ */ Symbol.for("nodejs.stream.destroyed"),
      kResume: /* @__PURE__ */ Symbol("resume"),
      kOnError: /* @__PURE__ */ Symbol("on error"),
      kMaxHeadersSize: /* @__PURE__ */ Symbol("max headers size"),
      kRunningIdx: /* @__PURE__ */ Symbol("running index"),
      kPendingIdx: /* @__PURE__ */ Symbol("pending index"),
      kError: /* @__PURE__ */ Symbol("error"),
      kClients: /* @__PURE__ */ Symbol("clients"),
      kClient: /* @__PURE__ */ Symbol("client"),
      kParser: /* @__PURE__ */ Symbol("parser"),
      kOnDestroyed: /* @__PURE__ */ Symbol("destroy callbacks"),
      kPipelining: /* @__PURE__ */ Symbol("pipelining"),
      kSocket: /* @__PURE__ */ Symbol("socket"),
      kHostHeader: /* @__PURE__ */ Symbol("host header"),
      kConnector: /* @__PURE__ */ Symbol("connector"),
      kStrictContentLength: /* @__PURE__ */ Symbol("strict content length"),
      kMaxRedirections: /* @__PURE__ */ Symbol("maxRedirections"),
      kMaxRequests: /* @__PURE__ */ Symbol("maxRequestsPerClient"),
      kProxy: /* @__PURE__ */ Symbol("proxy agent options"),
      kCounter: /* @__PURE__ */ Symbol("socket request counter"),
      kMaxResponseSize: /* @__PURE__ */ Symbol("max response size"),
      kHTTP2Session: /* @__PURE__ */ Symbol("http2Session"),
      kHTTP2SessionState: /* @__PURE__ */ Symbol("http2Session state"),
      kRetryHandlerDefaultRetry: /* @__PURE__ */ Symbol("retry agent default retry"),
      kConstruct: /* @__PURE__ */ Symbol("constructable"),
      kListeners: /* @__PURE__ */ Symbol("listeners"),
      kHTTPContext: /* @__PURE__ */ Symbol("http context"),
      kMaxConcurrentStreams: /* @__PURE__ */ Symbol("max concurrent streams"),
      kHTTP2InitialWindowSize: /* @__PURE__ */ Symbol("http2 initial window size"),
      kHTTP2ConnectionWindowSize: /* @__PURE__ */ Symbol("http2 connection window size"),
      kEnableConnectProtocol: /* @__PURE__ */ Symbol("http2session connect protocol"),
      kRemoteSettings: /* @__PURE__ */ Symbol("http2session remote settings"),
      kHTTP2Stream: /* @__PURE__ */ Symbol("http2session client stream"),
      kPingInterval: /* @__PURE__ */ Symbol("ping interval"),
      kNoProxyAgent: /* @__PURE__ */ Symbol("no proxy agent"),
      kHttpProxyAgent: /* @__PURE__ */ Symbol("http proxy agent"),
      kHttpsProxyAgent: /* @__PURE__ */ Symbol("https proxy agent"),
      kSocks5ProxyAgent: /* @__PURE__ */ Symbol("socks5 proxy agent")
    };
  }
});

// node_modules/undici/lib/util/timers.js
var require_timers = __commonJS({
  "node_modules/undici/lib/util/timers.js"(exports, module) {
    "use strict";
    var fastNow = 0;
    var RESOLUTION_MS = 1e3;
    var TICK_MS = (RESOLUTION_MS >> 1) - 1;
    var fastNowTimeout;
    var kFastTimer = /* @__PURE__ */ Symbol("kFastTimer");
    var fastTimers = [];
    var NOT_IN_LIST = -2;
    var TO_BE_CLEARED = -1;
    var PENDING = 0;
    var ACTIVE = 1;
    function onTick() {
      fastNow += TICK_MS;
      let idx = 0;
      let len = fastTimers.length;
      while (idx < len) {
        const timer = fastTimers[idx];
        if (timer._state === PENDING) {
          timer._idleStart = fastNow - TICK_MS;
          timer._state = ACTIVE;
        } else if (timer._state === ACTIVE && fastNow >= timer._idleStart + timer._idleTimeout) {
          timer._state = TO_BE_CLEARED;
          timer._idleStart = -1;
          timer._onTimeout(timer._timerArg);
        }
        if (timer._state === TO_BE_CLEARED) {
          timer._state = NOT_IN_LIST;
          if (--len !== 0) {
            fastTimers[idx] = fastTimers[len];
          }
        } else {
          ++idx;
        }
      }
      fastTimers.length = len;
      if (fastTimers.length !== 0) {
        refreshTimeout();
      }
    }
    function refreshTimeout() {
      if (fastNowTimeout?.refresh) {
        fastNowTimeout.refresh();
      } else {
        clearTimeout(fastNowTimeout);
        fastNowTimeout = setTimeout(onTick, TICK_MS);
        fastNowTimeout?.unref();
      }
    }
    var FastTimer = class {
      [kFastTimer] = true;
      /**
       * The state of the timer, which can be one of the following:
       * - NOT_IN_LIST (-2)
       * - TO_BE_CLEARED (-1)
       * - PENDING (0)
       * - ACTIVE (1)
       *
       * @type {-2|-1|0|1}
       * @private
       */
      _state = NOT_IN_LIST;
      /**
       * The number of milliseconds to wait before calling the callback.
       *
       * @type {number}
       * @private
       */
      _idleTimeout = -1;
      /**
       * The time in milliseconds when the timer was started. This value is used to
       * calculate when the timer should expire.
       *
       * @type {number}
       * @default -1
       * @private
       */
      _idleStart = -1;
      /**
       * The function to be executed when the timer expires.
       * @type {Function}
       * @private
       */
      _onTimeout;
      /**
       * The argument to be passed to the callback when the timer expires.
       *
       * @type {*}
       * @private
       */
      _timerArg;
      /**
       * @constructor
       * @param {Function} callback A function to be executed after the timer
       * expires.
       * @param {number} delay The time, in milliseconds that the timer should wait
       * before the specified function or code is executed.
       * @param {*} arg
       */
      constructor(callback, delay, arg) {
        this._onTimeout = callback;
        this._idleTimeout = delay;
        this._timerArg = arg;
        this.refresh();
      }
      /**
       * Sets the timer's start time to the current time, and reschedules the timer
       * to call its callback at the previously specified duration adjusted to the
       * current time.
       * Using this on a timer that has already called its callback will reactivate
       * the timer.
       *
       * @returns {void}
       */
      refresh() {
        if (this._state === NOT_IN_LIST) {
          fastTimers.push(this);
        }
        if (!fastNowTimeout || fastTimers.length === 1) {
          refreshTimeout();
        }
        this._state = PENDING;
      }
      /**
       * The `clear` method cancels the timer, preventing it from executing.
       *
       * @returns {void}
       * @private
       */
      clear() {
        this._state = TO_BE_CLEARED;
        this._idleStart = -1;
      }
    };
    module.exports = {
      /**
       * The setTimeout() method sets a timer which executes a function once the
       * timer expires.
       * @param {Function} callback A function to be executed after the timer
       * expires.
       * @param {number} delay The time, in milliseconds that the timer should
       * wait before the specified function or code is executed.
       * @param {*} [arg] An optional argument to be passed to the callback function
       * when the timer expires.
       * @returns {NodeJS.Timeout|FastTimer}
       */
      setTimeout(callback, delay, arg) {
        return delay <= RESOLUTION_MS ? setTimeout(callback, delay, arg) : new FastTimer(callback, delay, arg);
      },
      /**
       * The clearTimeout method cancels an instantiated Timer previously created
       * by calling setTimeout.
       *
       * @param {NodeJS.Timeout|FastTimer} timeout
       */
      clearTimeout(timeout) {
        if (timeout[kFastTimer]) {
          timeout.clear();
        } else {
          clearTimeout(timeout);
        }
      },
      /**
       * The setFastTimeout() method sets a fastTimer which executes a function once
       * the timer expires.
       * @param {Function} callback A function to be executed after the timer
       * expires.
       * @param {number} delay The time, in milliseconds that the timer should
       * wait before the specified function or code is executed.
       * @param {*} [arg] An optional argument to be passed to the callback function
       * when the timer expires.
       * @returns {FastTimer}
       */
      setFastTimeout(callback, delay, arg) {
        return new FastTimer(callback, delay, arg);
      },
      /**
       * The clearTimeout method cancels an instantiated FastTimer previously
       * created by calling setFastTimeout.
       *
       * @param {FastTimer} timeout
       */
      clearFastTimeout(timeout) {
        timeout.clear();
      },
      /**
       * The now method returns the value of the internal fast timer clock.
       *
       * @returns {number}
       */
      now() {
        return fastNow;
      },
      /**
       * Trigger the onTick function to process the fastTimers array.
       * Exported for testing purposes only.
       * Marking as deprecated to discourage any use outside of testing.
       * @deprecated
       * @param {number} [delay=0] The delay in milliseconds to add to the now value.
       */
      tick(delay = 0) {
        fastNow += delay - RESOLUTION_MS + 1;
        onTick();
        onTick();
      },
      /**
       * Reset FastTimers.
       * Exported for testing purposes only.
       * Marking as deprecated to discourage any use outside of testing.
       * @deprecated
       */
      reset() {
        fastNow = 0;
        fastTimers.length = 0;
        clearTimeout(fastNowTimeout);
        fastNowTimeout = null;
      },
      /**
       * Exporting for testing purposes only.
       * Marking as deprecated to discourage any use outside of testing.
       * @deprecated
       */
      kFastTimer
    };
  }
});

// node_modules/undici/lib/core/errors.js
var require_errors = __commonJS({
  "node_modules/undici/lib/core/errors.js"(exports, module) {
    "use strict";
    var kUndiciError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR");
    var UndiciError = class extends Error {
      constructor(message, options) {
        super(message, options);
        this.name = "UndiciError";
        this.code = "UND_ERR";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kUndiciError] === true;
      }
      get [kUndiciError]() {
        return true;
      }
    };
    var kConnectTimeoutError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_CONNECT_TIMEOUT");
    var ConnectTimeoutError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "ConnectTimeoutError";
        this.message = message || "Connect Timeout Error";
        this.code = "UND_ERR_CONNECT_TIMEOUT";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kConnectTimeoutError] === true;
      }
      get [kConnectTimeoutError]() {
        return true;
      }
    };
    var kHeadersTimeoutError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_HEADERS_TIMEOUT");
    var HeadersTimeoutError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "HeadersTimeoutError";
        this.message = message || "Headers Timeout Error";
        this.code = "UND_ERR_HEADERS_TIMEOUT";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kHeadersTimeoutError] === true;
      }
      get [kHeadersTimeoutError]() {
        return true;
      }
    };
    var kHeadersOverflowError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_HEADERS_OVERFLOW");
    var HeadersOverflowError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "HeadersOverflowError";
        this.message = message || "Headers Overflow Error";
        this.code = "UND_ERR_HEADERS_OVERFLOW";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kHeadersOverflowError] === true;
      }
      get [kHeadersOverflowError]() {
        return true;
      }
    };
    var kBodyTimeoutError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_BODY_TIMEOUT");
    var BodyTimeoutError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "BodyTimeoutError";
        this.message = message || "Body Timeout Error";
        this.code = "UND_ERR_BODY_TIMEOUT";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kBodyTimeoutError] === true;
      }
      get [kBodyTimeoutError]() {
        return true;
      }
    };
    var kInvalidArgumentError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_INVALID_ARG");
    var InvalidArgumentError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "InvalidArgumentError";
        this.message = message || "Invalid Argument Error";
        this.code = "UND_ERR_INVALID_ARG";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kInvalidArgumentError] === true;
      }
      get [kInvalidArgumentError]() {
        return true;
      }
    };
    var kInvalidReturnValueError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_INVALID_RETURN_VALUE");
    var InvalidReturnValueError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "InvalidReturnValueError";
        this.message = message || "Invalid Return Value Error";
        this.code = "UND_ERR_INVALID_RETURN_VALUE";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kInvalidReturnValueError] === true;
      }
      get [kInvalidReturnValueError]() {
        return true;
      }
    };
    var kAbortError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_ABORT");
    var AbortError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "AbortError";
        this.message = message || "The operation was aborted";
        this.code = "UND_ERR_ABORT";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kAbortError] === true;
      }
      get [kAbortError]() {
        return true;
      }
    };
    var kRequestAbortedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_ABORTED");
    var RequestAbortedError = class extends AbortError {
      constructor(message) {
        super(message);
        this.name = "AbortError";
        this.message = message || "Request aborted";
        this.code = "UND_ERR_ABORTED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kRequestAbortedError] === true;
      }
      get [kRequestAbortedError]() {
        return true;
      }
    };
    var kInformationalError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_INFO");
    var InformationalError = class extends UndiciError {
      constructor(message, options) {
        super(message, options);
        this.name = "InformationalError";
        this.message = message || "Request information";
        this.code = "UND_ERR_INFO";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kInformationalError] === true;
      }
      get [kInformationalError]() {
        return true;
      }
    };
    var kRequestContentLengthMismatchError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH");
    var RequestContentLengthMismatchError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "RequestContentLengthMismatchError";
        this.message = message || "Request body length does not match content-length header";
        this.code = "UND_ERR_REQ_CONTENT_LENGTH_MISMATCH";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kRequestContentLengthMismatchError] === true;
      }
      get [kRequestContentLengthMismatchError]() {
        return true;
      }
    };
    var kResponseContentLengthMismatchError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH");
    var ResponseContentLengthMismatchError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "ResponseContentLengthMismatchError";
        this.message = message || "Response body length does not match content-length header";
        this.code = "UND_ERR_RES_CONTENT_LENGTH_MISMATCH";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kResponseContentLengthMismatchError] === true;
      }
      get [kResponseContentLengthMismatchError]() {
        return true;
      }
    };
    var kClientDestroyedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_DESTROYED");
    var ClientDestroyedError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "ClientDestroyedError";
        this.message = message || "The client is destroyed";
        this.code = "UND_ERR_DESTROYED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kClientDestroyedError] === true;
      }
      get [kClientDestroyedError]() {
        return true;
      }
    };
    var kClientClosedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_CLOSED");
    var ClientClosedError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "ClientClosedError";
        this.message = message || "The client is closed";
        this.code = "UND_ERR_CLOSED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kClientClosedError] === true;
      }
      get [kClientClosedError]() {
        return true;
      }
    };
    var kSocketError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_SOCKET");
    var SocketError = class extends UndiciError {
      constructor(message, socket) {
        super(message);
        this.name = "SocketError";
        this.message = message || "Socket error";
        this.code = "UND_ERR_SOCKET";
        this.socket = socket;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kSocketError] === true;
      }
      get [kSocketError]() {
        return true;
      }
    };
    var kNotSupportedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_NOT_SUPPORTED");
    var NotSupportedError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "NotSupportedError";
        this.message = message || "Not supported error";
        this.code = "UND_ERR_NOT_SUPPORTED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kNotSupportedError] === true;
      }
      get [kNotSupportedError]() {
        return true;
      }
    };
    var kBalancedPoolMissingUpstreamError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_BPL_MISSING_UPSTREAM");
    var BalancedPoolMissingUpstreamError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "MissingUpstreamError";
        this.message = message || "No upstream has been added to the BalancedPool";
        this.code = "UND_ERR_BPL_MISSING_UPSTREAM";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kBalancedPoolMissingUpstreamError] === true;
      }
      get [kBalancedPoolMissingUpstreamError]() {
        return true;
      }
    };
    var kHTTPParserError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_HTTP_PARSER");
    var HTTPParserError = class extends Error {
      constructor(message, code, data) {
        super(message);
        this.name = "HTTPParserError";
        this.code = code ? `HPE_${code}` : void 0;
        this.data = data ? data.toString() : void 0;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kHTTPParserError] === true;
      }
      get [kHTTPParserError]() {
        return true;
      }
    };
    var kResponseExceededMaxSizeError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE");
    var ResponseExceededMaxSizeError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "ResponseExceededMaxSizeError";
        this.message = message || "Response content exceeded max size";
        this.code = "UND_ERR_RES_EXCEEDED_MAX_SIZE";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kResponseExceededMaxSizeError] === true;
      }
      get [kResponseExceededMaxSizeError]() {
        return true;
      }
    };
    var kRequestRetryError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_REQ_RETRY");
    var RequestRetryError = class extends UndiciError {
      constructor(message, code, { headers, data }) {
        super(message);
        this.name = "RequestRetryError";
        this.message = message || "Request retry error";
        this.code = "UND_ERR_REQ_RETRY";
        this.statusCode = code;
        this.data = data;
        this.headers = headers;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kRequestRetryError] === true;
      }
      get [kRequestRetryError]() {
        return true;
      }
    };
    var kResponseError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_RESPONSE");
    var ResponseError = class extends UndiciError {
      constructor(message, code, { headers, body }) {
        super(message);
        this.name = "ResponseError";
        this.message = message || "Response error";
        this.code = "UND_ERR_RESPONSE";
        this.statusCode = code;
        this.body = body;
        this.headers = headers;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kResponseError] === true;
      }
      get [kResponseError]() {
        return true;
      }
    };
    var kSecureProxyConnectionError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_PRX_TLS");
    var SecureProxyConnectionError = class extends UndiciError {
      constructor(cause, message, options = {}) {
        super(message, { cause, ...options });
        this.name = "SecureProxyConnectionError";
        this.message = message || "Secure Proxy Connection failed";
        this.code = "UND_ERR_PRX_TLS";
        this.cause = cause;
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kSecureProxyConnectionError] === true;
      }
      get [kSecureProxyConnectionError]() {
        return true;
      }
    };
    var kMaxOriginsReachedError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_MAX_ORIGINS_REACHED");
    var MaxOriginsReachedError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "MaxOriginsReachedError";
        this.message = message || "Maximum allowed origins reached";
        this.code = "UND_ERR_MAX_ORIGINS_REACHED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kMaxOriginsReachedError] === true;
      }
      get [kMaxOriginsReachedError]() {
        return true;
      }
    };
    var Socks5ProxyError = class extends UndiciError {
      constructor(message, code) {
        super(message);
        this.name = "Socks5ProxyError";
        this.message = message || "SOCKS5 proxy error";
        this.code = code || "UND_ERR_SOCKS5";
      }
    };
    var kMessageSizeExceededError = /* @__PURE__ */ Symbol.for("undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED");
    var MessageSizeExceededError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "MessageSizeExceededError";
        this.message = message || "Max decompressed message size exceeded";
        this.code = "UND_ERR_WS_MESSAGE_SIZE_EXCEEDED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kMessageSizeExceededError] === true;
      }
      get [kMessageSizeExceededError]() {
        return true;
      }
    };
    module.exports = {
      AbortError,
      HTTPParserError,
      UndiciError,
      HeadersTimeoutError,
      HeadersOverflowError,
      BodyTimeoutError,
      RequestContentLengthMismatchError,
      ConnectTimeoutError,
      InvalidArgumentError,
      InvalidReturnValueError,
      RequestAbortedError,
      ClientDestroyedError,
      ClientClosedError,
      InformationalError,
      SocketError,
      NotSupportedError,
      ResponseContentLengthMismatchError,
      BalancedPoolMissingUpstreamError,
      ResponseExceededMaxSizeError,
      RequestRetryError,
      ResponseError,
      SecureProxyConnectionError,
      MaxOriginsReachedError,
      Socks5ProxyError,
      MessageSizeExceededError
    };
  }
});

// node_modules/undici/lib/core/constants.js
var require_constants2 = __commonJS({
  "node_modules/undici/lib/core/constants.js"(exports, module) {
    "use strict";
    var wellknownHeaderNames = (
      /** @type {const} */
      [
        "Accept",
        "Accept-Encoding",
        "Accept-Language",
        "Accept-Ranges",
        "Access-Control-Allow-Credentials",
        "Access-Control-Allow-Headers",
        "Access-Control-Allow-Methods",
        "Access-Control-Allow-Origin",
        "Access-Control-Expose-Headers",
        "Access-Control-Max-Age",
        "Access-Control-Request-Headers",
        "Access-Control-Request-Method",
        "Age",
        "Allow",
        "Alt-Svc",
        "Alt-Used",
        "Authorization",
        "Cache-Control",
        "Clear-Site-Data",
        "Connection",
        "Content-Disposition",
        "Content-Encoding",
        "Content-Language",
        "Content-Length",
        "Content-Location",
        "Content-Range",
        "Content-Security-Policy",
        "Content-Security-Policy-Report-Only",
        "Content-Type",
        "Cookie",
        "Cross-Origin-Embedder-Policy",
        "Cross-Origin-Opener-Policy",
        "Cross-Origin-Resource-Policy",
        "Date",
        "Device-Memory",
        "Downlink",
        "ECT",
        "ETag",
        "Expect",
        "Expect-CT",
        "Expires",
        "Forwarded",
        "From",
        "Host",
        "If-Match",
        "If-Modified-Since",
        "If-None-Match",
        "If-Range",
        "If-Unmodified-Since",
        "Keep-Alive",
        "Last-Modified",
        "Link",
        "Location",
        "Max-Forwards",
        "Origin",
        "Permissions-Policy",
        "Pragma",
        "Proxy-Authenticate",
        "Proxy-Authorization",
        "RTT",
        "Range",
        "Referer",
        "Referrer-Policy",
        "Refresh",
        "Retry-After",
        "Sec-WebSocket-Accept",
        "Sec-WebSocket-Extensions",
        "Sec-WebSocket-Key",
        "Sec-WebSocket-Protocol",
        "Sec-WebSocket-Version",
        "Server",
        "Server-Timing",
        "Service-Worker-Allowed",
        "Service-Worker-Navigation-Preload",
        "Set-Cookie",
        "SourceMap",
        "Strict-Transport-Security",
        "Supports-Loading-Mode",
        "TE",
        "Timing-Allow-Origin",
        "Trailer",
        "Transfer-Encoding",
        "Upgrade",
        "Upgrade-Insecure-Requests",
        "User-Agent",
        "Vary",
        "Via",
        "WWW-Authenticate",
        "X-Content-Type-Options",
        "X-DNS-Prefetch-Control",
        "X-Frame-Options",
        "X-Permitted-Cross-Domain-Policies",
        "X-Powered-By",
        "X-Requested-With",
        "X-XSS-Protection"
      ]
    );
    var headerNameLowerCasedRecord = {};
    Object.setPrototypeOf(headerNameLowerCasedRecord, null);
    for (let i = 0; i < wellknownHeaderNames.length; ++i) {
      const key = wellknownHeaderNames[i];
      const lowerCasedKey = key.toLowerCase();
      headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = lowerCasedKey;
    }
    module.exports = {
      wellknownHeaderNames,
      headerNameLowerCasedRecord
    };
  }
});

// node_modules/undici/lib/core/tree.js
var require_tree = __commonJS({
  "node_modules/undici/lib/core/tree.js"(exports, module) {
    "use strict";
    var {
      wellknownHeaderNames,
      headerNameLowerCasedRecord
    } = require_constants2();
    var TstNode = class _TstNode {
      /** @type {any} */
      value = null;
      /** @type {null | TstNode} */
      left = null;
      /** @type {null | TstNode} */
      middle = null;
      /** @type {null | TstNode} */
      right = null;
      /** @type {number} */
      code;
      /**
       * @param {string} key
       * @param {any} value
       * @param {number} index
       */
      constructor(key, value, index2) {
        if (index2 === void 0 || index2 >= key.length) {
          throw new TypeError("Unreachable");
        }
        const code = this.code = key.charCodeAt(index2);
        if (code > 127) {
          throw new TypeError("key must be ascii string");
        }
        if (key.length !== ++index2) {
          this.middle = new _TstNode(key, value, index2);
        } else {
          this.value = value;
        }
      }
      /**
       * @param {string} key
       * @param {any} value
       * @returns {void}
       */
      add(key, value) {
        const length = key.length;
        if (length === 0) {
          throw new TypeError("Unreachable");
        }
        let index2 = 0;
        let node = this;
        while (true) {
          const code = key.charCodeAt(index2);
          if (code > 127) {
            throw new TypeError("key must be ascii string");
          }
          if (node.code === code) {
            if (length === ++index2) {
              node.value = value;
              break;
            } else if (node.middle !== null) {
              node = node.middle;
            } else {
              node.middle = new _TstNode(key, value, index2);
              break;
            }
          } else if (node.code < code) {
            if (node.left !== null) {
              node = node.left;
            } else {
              node.left = new _TstNode(key, value, index2);
              break;
            }
          } else if (node.right !== null) {
            node = node.right;
          } else {
            node.right = new _TstNode(key, value, index2);
            break;
          }
        }
      }
      /**
       * @param {Uint8Array} key
       * @returns {TstNode | null}
       */
      search(key) {
        const keylength = key.length;
        let index2 = 0;
        let node = this;
        while (node !== null && index2 < keylength) {
          let code = key[index2];
          if (code <= 90 && code >= 65) {
            code |= 32;
          }
          while (node !== null) {
            if (code === node.code) {
              if (keylength === ++index2) {
                return node;
              }
              node = node.middle;
              break;
            }
            node = node.code < code ? node.left : node.right;
          }
        }
        return null;
      }
    };
    var TernarySearchTree = class {
      /** @type {TstNode | null} */
      node = null;
      /**
       * @param {string} key
       * @param {any} value
       * @returns {void}
       * */
      insert(key, value) {
        if (this.node === null) {
          this.node = new TstNode(key, value, 0);
        } else {
          this.node.add(key, value);
        }
      }
      /**
       * @param {Uint8Array} key
       * @returns {any}
       */
      lookup(key) {
        return this.node?.search(key)?.value ?? null;
      }
    };
    var tree = new TernarySearchTree();
    for (let i = 0; i < wellknownHeaderNames.length; ++i) {
      const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]];
      tree.insert(key, key);
    }
    module.exports = {
      TernarySearchTree,
      tree
    };
  }
});

// node_modules/undici/lib/core/util.js
var require_util = __commonJS({
  "node_modules/undici/lib/core/util.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var { kDestroyed, kBodyUsed, kListeners, kBody } = require_symbols();
    var { IncomingMessage } = __require("http");
    var stream = __require("stream");
    var net = __require("net");
    var { stringify: stringify4 } = __require("querystring");
    var { EventEmitter: EE, addAbortListener: addAbortListenerNative } = __require("events");
    var timers = require_timers();
    var { InvalidArgumentError, ConnectTimeoutError } = require_errors();
    var { headerNameLowerCasedRecord } = require_constants2();
    var { tree } = require_tree();
    var BodyAsyncIterable = class {
      constructor(body) {
        this[kBody] = body;
        this[kBodyUsed] = false;
      }
      async *[Symbol.asyncIterator]() {
        assert8(!this[kBodyUsed], "disturbed");
        this[kBodyUsed] = true;
        yield* this[kBody];
      }
    };
    function noop() {
    }
    function wrapRequestBody(body) {
      if (isStream(body)) {
        if (bodyLength(body) === 0) {
          body.on("data", function() {
            assert8(false);
          });
        }
        if (typeof body.readableDidRead !== "boolean") {
          body[kBodyUsed] = false;
          EE.prototype.on.call(body, "data", function() {
            this[kBodyUsed] = true;
          });
        }
        return body;
      } else if (body && typeof body.pipeTo === "function") {
        return new BodyAsyncIterable(body);
      } else if (body && isFormDataLike(body)) {
        return body;
      } else if (body && typeof body !== "string" && !ArrayBuffer.isView(body) && isIterable(body)) {
        return new BodyAsyncIterable(body);
      } else {
        return body;
      }
    }
    function isStream(obj) {
      return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function";
    }
    function isBlobLike(object) {
      return object instanceof Blob;
    }
    function pathHasQueryOrFragment(url) {
      return url.includes("?") || url.includes("#");
    }
    function serializePathWithQuery(url, queryParams) {
      if (pathHasQueryOrFragment(url)) {
        throw new Error('Query params cannot be passed when url already contains "?" or "#".');
      }
      const stringified = stringify4(queryParams);
      if (stringified) {
        url += "?" + stringified;
      }
      return url;
    }
    function isValidPort(port) {
      const value = parseInt(port, 10);
      return value === Number(port) && value >= 0 && value <= 65535;
    }
    function isHttpOrHttpsPrefixed(value) {
      return value != null && value[0] === "h" && value[1] === "t" && value[2] === "t" && value[3] === "p" && (value[4] === ":" || value[4] === "s" && value[5] === ":");
    }
    function parseURL(url) {
      if (typeof url === "string") {
        url = new URL(url);
        if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
          throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
        }
        return url;
      }
      if (!url || typeof url !== "object") {
        throw new InvalidArgumentError("Invalid URL: The URL argument must be a non-null object.");
      }
      if (!(url instanceof URL)) {
        if (url.port != null && url.port !== "" && isValidPort(url.port) === false) {
          throw new InvalidArgumentError("Invalid URL: port must be a valid integer or a string representation of an integer.");
        }
        if (url.path != null && typeof url.path !== "string") {
          throw new InvalidArgumentError("Invalid URL path: the path must be a string or null/undefined.");
        }
        if (url.pathname != null && typeof url.pathname !== "string") {
          throw new InvalidArgumentError("Invalid URL pathname: the pathname must be a string or null/undefined.");
        }
        if (url.hostname != null && typeof url.hostname !== "string") {
          throw new InvalidArgumentError("Invalid URL hostname: the hostname must be a string or null/undefined.");
        }
        if (url.origin != null && typeof url.origin !== "string") {
          throw new InvalidArgumentError("Invalid URL origin: the origin must be a string or null/undefined.");
        }
        if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
          throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
        }
        const port = url.port != null ? url.port : url.protocol === "https:" ? 443 : 80;
        let origin = url.origin != null ? url.origin : `${url.protocol || ""}//${url.hostname || ""}:${port}`;
        let path2 = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`;
        if (origin[origin.length - 1] === "/") {
          origin = origin.slice(0, origin.length - 1);
        }
        if (path2 && path2[0] !== "/") {
          path2 = `/${path2}`;
        }
        return new URL(`${origin}${path2}`);
      }
      if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
        throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
      }
      return url;
    }
    function parseOrigin(url) {
      url = parseURL(url);
      if (url.pathname !== "/" || url.search || url.hash) {
        throw new InvalidArgumentError("invalid url");
      }
      return url;
    }
    function getHostname(host) {
      if (host[0] === "[") {
        const idx2 = host.indexOf("]");
        assert8(idx2 !== -1);
        return host.substring(1, idx2);
      }
      const idx = host.indexOf(":");
      if (idx === -1) return host;
      return host.substring(0, idx);
    }
    function getServerName(host) {
      if (!host) {
        return null;
      }
      assert8(typeof host === "string");
      const servername = getHostname(host);
      if (net.isIP(servername)) {
        return "";
      }
      return servername;
    }
    function deepClone(obj) {
      return JSON.parse(JSON.stringify(obj));
    }
    function isAsyncIterable(obj) {
      return !!(obj != null && typeof obj[Symbol.asyncIterator] === "function");
    }
    function isIterable(obj) {
      return !!(obj != null && (typeof obj[Symbol.iterator] === "function" || typeof obj[Symbol.asyncIterator] === "function"));
    }
    function hasSafeIterator(obj) {
      const prototype = Object.getPrototypeOf(obj);
      const ownIterator = Object.hasOwn(obj, Symbol.iterator);
      return ownIterator || prototype != null && prototype !== Object.prototype && typeof obj[Symbol.iterator] === "function";
    }
    function bodyLength(body) {
      if (body == null) {
        return 0;
      } else if (isStream(body)) {
        const state = body._readableState;
        return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) ? state.length : null;
      } else if (isBlobLike(body)) {
        return body.size != null ? body.size : null;
      } else if (isBuffer(body)) {
        return body.byteLength;
      }
      return null;
    }
    function isDestroyed(body) {
      return body && !!(body.destroyed || body[kDestroyed] || stream.isDestroyed?.(body));
    }
    function destroy(stream2, err) {
      if (stream2 == null || !isStream(stream2) || isDestroyed(stream2)) {
        return;
      }
      if (typeof stream2.destroy === "function") {
        if (Object.getPrototypeOf(stream2).constructor === IncomingMessage) {
          stream2.socket = null;
        }
        stream2.destroy(err);
      } else if (err) {
        queueMicrotask(() => {
          stream2.emit("error", err);
        });
      }
      if (stream2.destroyed !== true) {
        stream2[kDestroyed] = true;
      }
    }
    var KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/;
    function parseKeepAliveTimeout(val) {
      const m = val.match(KEEPALIVE_TIMEOUT_EXPR);
      return m ? parseInt(m[1], 10) * 1e3 : null;
    }
    function headerNameToString(value) {
      return typeof value === "string" ? headerNameLowerCasedRecord[value] ?? value.toLowerCase() : tree.lookup(value) ?? value.toString("latin1").toLowerCase();
    }
    function bufferToLowerCasedHeaderName(value) {
      return tree.lookup(value) ?? value.toString("latin1").toLowerCase();
    }
    function parseHeaders(headers, obj) {
      if (obj === void 0) obj = {};
      for (let i = 0; i < headers.length; i += 2) {
        const key = headerNameToString(headers[i]);
        let val = obj[key];
        if (val !== void 0) {
          if (!Object.hasOwn(obj, key)) {
            const headersValue = typeof headers[i + 1] === "string" ? headers[i + 1] : Array.isArray(headers[i + 1]) ? headers[i + 1].map((x) => x.toString("latin1")) : headers[i + 1].toString("latin1");
            if (key === "__proto__") {
              Object.defineProperty(obj, key, {
                value: headersValue,
                enumerable: true,
                configurable: true,
                writable: true
              });
            } else {
              obj[key] = headersValue;
            }
          } else {
            if (typeof val === "string") {
              val = [val];
              obj[key] = val;
            }
            val.push(headers[i + 1].toString("latin1"));
          }
        } else {
          const headersValue = typeof headers[i + 1] === "string" ? headers[i + 1] : Array.isArray(headers[i + 1]) ? headers[i + 1].map((x) => x.toString("latin1")) : headers[i + 1].toString("latin1");
          obj[key] = headersValue;
        }
      }
      return obj;
    }
    function parseRawHeaders(headers) {
      if (headers == null) {
        return [];
      }
      if (!Array.isArray(headers)) {
        const rawHeaders = [];
        for (const [name, value] of Object.entries(headers)) {
          if (Array.isArray(value)) {
            for (const entry of value) {
              rawHeaders.push(name, `${entry}`);
            }
          } else {
            rawHeaders.push(name, `${value}`);
          }
        }
        return rawHeaders;
      }
      const headersLength = headers.length;
      const ret = new Array(headersLength);
      let key;
      let val;
      for (let n = 0; n < headersLength; n += 2) {
        key = headers[n];
        val = headers[n + 1];
        typeof key !== "string" && (key = key.toString());
        typeof val !== "string" && (val = val.toString("latin1"));
        ret[n] = key;
        ret[n + 1] = val;
      }
      return ret;
    }
    function toRawHeaders(headers) {
      const rawHeaders = [];
      for (const [name, value] of Object.entries(headers)) {
        if (Array.isArray(value)) {
          for (const entry of value) {
            rawHeaders.push(Buffer.from(name, "latin1"), Buffer.from(`${entry}`, "latin1"));
          }
        } else {
          rawHeaders.push(Buffer.from(name, "latin1"), Buffer.from(`${value}`, "latin1"));
        }
      }
      return rawHeaders;
    }
    function encodeRawHeaders(headers) {
      if (!Array.isArray(headers)) {
        throw new TypeError("expected headers to be an array");
      }
      return headers.map((x) => Buffer.from(x));
    }
    function isBuffer(buffer2) {
      return buffer2 instanceof Uint8Array || Buffer.isBuffer(buffer2);
    }
    function assertRequestHandler(handler, method, upgrade) {
      if (!handler || typeof handler !== "object") {
        throw new InvalidArgumentError("handler must be an object");
      }
      if (typeof handler.onRequestStart !== "function") {
        throw new InvalidArgumentError("invalid onRequestStart method");
      }
      if (typeof handler.onResponseError !== "function") {
        throw new InvalidArgumentError("invalid onResponseError method");
      }
      if (typeof handler.onBodySent !== "function" && handler.onBodySent !== void 0) {
        throw new InvalidArgumentError("invalid onBodySent method");
      }
      if (typeof handler.onRequestSent !== "function" && handler.onRequestSent !== void 0) {
        throw new InvalidArgumentError("invalid onRequestSent method");
      }
      if (upgrade || method === "CONNECT") {
        if (typeof handler.onRequestUpgrade !== "function") {
          throw new InvalidArgumentError("invalid onRequestUpgrade method");
        }
      } else {
        if (typeof handler.onResponseStart !== "function") {
          throw new InvalidArgumentError("invalid onResponseStart method");
        }
        if (typeof handler.onResponseData !== "function") {
          throw new InvalidArgumentError("invalid onResponseData method");
        }
        if (typeof handler.onResponseEnd !== "function") {
          throw new InvalidArgumentError("invalid onResponseEnd method");
        }
      }
    }
    function isDisturbed(body) {
      return !!(body && (stream.isDisturbed(body) || body[kBodyUsed]));
    }
    function getSocketInfo(socket) {
      return {
        localAddress: socket.localAddress,
        localPort: socket.localPort,
        remoteAddress: socket.remoteAddress,
        remotePort: socket.remotePort,
        remoteFamily: socket.remoteFamily,
        timeout: socket.timeout,
        bytesWritten: socket.bytesWritten,
        bytesRead: socket.bytesRead
      };
    }
    function ReadableStreamFrom(iterable) {
      let iterator;
      return new ReadableStream(
        {
          start() {
            iterator = iterable[Symbol.asyncIterator]();
          },
          pull(controller) {
            return iterator.next().then(({ done, value }) => {
              if (done) {
                return queueMicrotask(() => {
                  controller.close();
                  controller.byobRequest?.respond(0);
                });
              } else {
                const buf = Buffer.isBuffer(value) ? value : Buffer.from(value);
                if (buf.byteLength) {
                  return controller.enqueue(new Uint8Array(buf));
                } else {
                  return this.pull(controller);
                }
              }
            });
          },
          cancel() {
            return iterator.return();
          },
          type: "bytes"
        }
      );
    }
    function isFormDataLike(object) {
      return object && typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && object[Symbol.toStringTag] === "FormData";
    }
    function addAbortListener(signal, listener) {
      if (signal instanceof AbortSignal) {
        const disposable = addAbortListenerNative(signal, listener);
        return () => disposable[Symbol.dispose]();
      }
      if (typeof signal.addEventListener === "function") {
        signal.addEventListener("abort", listener, { once: true });
        return () => signal.removeEventListener("abort", listener);
      }
      signal.once("abort", listener);
      return () => signal.removeListener("abort", listener);
    }
    var validTokenChars = new Uint8Array([
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 0-15
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 16-31
      0,
      1,
      0,
      1,
      1,
      1,
      1,
      1,
      0,
      0,
      1,
      1,
      0,
      1,
      1,
      0,
      // 32-47 (!"#$%&'()*+,-./)
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      0,
      0,
      0,
      0,
      0,
      0,
      // 48-63 (0-9:;<=>?)
      0,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      // 64-79 (@A-O)
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      0,
      0,
      0,
      1,
      1,
      // 80-95 (P-Z[\]^_)
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      // 96-111 (`a-o)
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      1,
      0,
      1,
      0,
      1,
      0,
      // 112-127 (p-z{|}~)
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 128-143
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 144-159
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 160-175
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 176-191
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 192-207
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 208-223
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      // 224-239
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0,
      0
      // 240-255
    ]);
    function isTokenCharCode(c) {
      return validTokenChars[c] === 1;
    }
    var tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/;
    function isValidHTTPToken(characters) {
      if (characters.length >= 12) return tokenRegExp.test(characters);
      if (characters.length === 0) return false;
      for (let i = 0; i < characters.length; i++) {
        if (validTokenChars[characters.charCodeAt(i)] !== 1) {
          return false;
        }
      }
      return true;
    }
    var headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
    function isValidHeaderValue(characters) {
      return !headerCharRegex.test(characters);
    }
    var rangeHeaderRegex = /^bytes (\d+)-(\d+)\/(\d+)?$/;
    function parseRangeHeader(range) {
      if (range == null || range === "") return { start: 0, end: null, size: null };
      const m = range ? range.match(rangeHeaderRegex) : null;
      return m ? {
        start: parseInt(m[1]),
        end: m[2] ? parseInt(m[2]) : null,
        size: m[3] ? parseInt(m[3]) : null
      } : null;
    }
    function addListener(obj, name, listener) {
      const listeners = obj[kListeners] ??= [];
      listeners.push([name, listener]);
      obj.on(name, listener);
      return obj;
    }
    function removeAllListeners(obj) {
      if (obj[kListeners] != null) {
        for (const [name, listener] of obj[kListeners]) {
          obj.removeListener(name, listener);
        }
        obj[kListeners] = null;
      }
      return obj;
    }
    function errorRequest(client, request, err) {
      try {
        request.onResponseError(err);
        assert8(request.aborted);
      } catch (err2) {
        client.emit("error", err2);
      }
    }
    var setupConnectTimeout = process.platform === "win32" ? (socketWeakRef, opts) => {
      if (!opts.timeout) {
        return noop;
      }
      let s1 = null;
      let s22 = null;
      const fastTimer = timers.setFastTimeout(() => {
        s1 = setImmediate(() => {
          s22 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts));
        });
      }, opts.timeout);
      return () => {
        timers.clearFastTimeout(fastTimer);
        clearImmediate(s1);
        clearImmediate(s22);
      };
    } : (socketWeakRef, opts) => {
      if (!opts.timeout) {
        return noop;
      }
      let s1 = null;
      const fastTimer = timers.setFastTimeout(() => {
        s1 = setImmediate(() => {
          onConnectTimeout(socketWeakRef.deref(), opts);
        });
      }, opts.timeout);
      return () => {
        timers.clearFastTimeout(fastTimer);
        clearImmediate(s1);
      };
    };
    function onConnectTimeout(socket, opts) {
      if (socket == null) {
        return;
      }
      let message = "Connect Timeout Error";
      if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) {
        message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(", ")},`;
      } else {
        message += ` (attempted address: ${opts.hostname}:${opts.port},`;
      }
      message += ` timeout: ${opts.timeout}ms)`;
      destroy(socket, new ConnectTimeoutError(message));
    }
    function getProtocolFromUrlString(urlString) {
      if (urlString[0] === "h" && urlString[1] === "t" && urlString[2] === "t" && urlString[3] === "p") {
        switch (urlString[4]) {
          case ":":
            return "http:";
          case "s":
            if (urlString[5] === ":") {
              return "https:";
            }
        }
      }
      return urlString.slice(0, urlString.indexOf(":") + 1);
    }
    var kEnumerableProperty = /* @__PURE__ */ Object.create(null);
    kEnumerableProperty.enumerable = true;
    var normalizedMethodRecordsBase = {
      delete: "DELETE",
      DELETE: "DELETE",
      get: "GET",
      GET: "GET",
      head: "HEAD",
      HEAD: "HEAD",
      options: "OPTIONS",
      OPTIONS: "OPTIONS",
      post: "POST",
      POST: "POST",
      put: "PUT",
      PUT: "PUT"
    };
    var normalizedMethodRecords = {
      ...normalizedMethodRecordsBase,
      patch: "patch",
      PATCH: "PATCH"
    };
    Object.setPrototypeOf(normalizedMethodRecordsBase, null);
    Object.setPrototypeOf(normalizedMethodRecords, null);
    module.exports = {
      kEnumerableProperty,
      isDisturbed,
      isBlobLike,
      parseOrigin,
      parseURL,
      getServerName,
      isStream,
      isIterable,
      hasSafeIterator,
      isAsyncIterable,
      isDestroyed,
      headerNameToString,
      bufferToLowerCasedHeaderName,
      addListener,
      removeAllListeners,
      errorRequest,
      parseRawHeaders,
      toRawHeaders,
      encodeRawHeaders,
      parseHeaders,
      parseKeepAliveTimeout,
      destroy,
      bodyLength,
      deepClone,
      ReadableStreamFrom,
      isBuffer,
      assertRequestHandler,
      getSocketInfo,
      isFormDataLike,
      pathHasQueryOrFragment,
      serializePathWithQuery,
      addAbortListener,
      isValidHTTPToken,
      isValidHeaderValue,
      isTokenCharCode,
      parseRangeHeader,
      normalizedMethodRecordsBase,
      normalizedMethodRecords,
      isValidPort,
      isHttpOrHttpsPrefixed,
      safeHTTPMethods: Object.freeze(["GET", "HEAD", "OPTIONS", "TRACE"]),
      wrapRequestBody,
      setupConnectTimeout,
      getProtocolFromUrlString
    };
  }
});

// node_modules/undici/lib/util/stats.js
var require_stats = __commonJS({
  "node_modules/undici/lib/util/stats.js"(exports, module) {
    "use strict";
    var {
      kConnected,
      kPending,
      kRunning,
      kSize,
      kFree,
      kQueued
    } = require_symbols();
    var ClientStats = class {
      constructor(client) {
        this.connected = client[kConnected];
        this.pending = client[kPending];
        this.running = client[kRunning];
        this.size = client[kSize];
      }
    };
    var PoolStats = class {
      constructor(pool) {
        this.connected = pool[kConnected];
        this.free = pool[kFree];
        this.pending = pool[kPending];
        this.queued = pool[kQueued];
        this.running = pool[kRunning];
        this.size = pool[kSize];
      }
    };
    module.exports = { ClientStats, PoolStats };
  }
});

// node_modules/undici/lib/core/diagnostics.js
var require_diagnostics = __commonJS({
  "node_modules/undici/lib/core/diagnostics.js"(exports, module) {
    "use strict";
    var diagnosticsChannel = __require("diagnostics_channel");
    var util2 = __require("util");
    var undiciDebugLog = util2.debuglog("undici");
    var fetchDebuglog = util2.debuglog("fetch");
    var websocketDebuglog = util2.debuglog("websocket");
    var channels = {
      // Client
      beforeConnect: diagnosticsChannel.channel("undici:client:beforeConnect"),
      connected: diagnosticsChannel.channel("undici:client:connected"),
      connectError: diagnosticsChannel.channel("undici:client:connectError"),
      sendHeaders: diagnosticsChannel.channel("undici:client:sendHeaders"),
      // Request
      create: diagnosticsChannel.channel("undici:request:create"),
      bodySent: diagnosticsChannel.channel("undici:request:bodySent"),
      bodyChunkSent: diagnosticsChannel.channel("undici:request:bodyChunkSent"),
      bodyChunkReceived: diagnosticsChannel.channel("undici:request:bodyChunkReceived"),
      headers: diagnosticsChannel.channel("undici:request:headers"),
      trailers: diagnosticsChannel.channel("undici:request:trailers"),
      error: diagnosticsChannel.channel("undici:request:error"),
      // WebSocket
      open: diagnosticsChannel.channel("undici:websocket:open"),
      close: diagnosticsChannel.channel("undici:websocket:close"),
      socketError: diagnosticsChannel.channel("undici:websocket:socket_error"),
      ping: diagnosticsChannel.channel("undici:websocket:ping"),
      pong: diagnosticsChannel.channel("undici:websocket:pong"),
      // ProxyAgent
      proxyConnected: diagnosticsChannel.channel("undici:proxy:connected")
    };
    var isTrackingClientEvents = false;
    function trackClientEvents(debugLog = undiciDebugLog) {
      if (isTrackingClientEvents) {
        return;
      }
      if (channels.beforeConnect.hasSubscribers || channels.connected.hasSubscribers || channels.connectError.hasSubscribers || channels.sendHeaders.hasSubscribers) {
        isTrackingClientEvents = true;
        return;
      }
      isTrackingClientEvents = true;
      diagnosticsChannel.subscribe(
        "undici:client:beforeConnect",
        (evt) => {
          const {
            connectParams: { version: version4, protocol, port, host }
          } = evt;
          debugLog(
            "connecting to %s%s using %s%s",
            host,
            port ? `:${port}` : "",
            protocol,
            version4
          );
        }
      );
      diagnosticsChannel.subscribe(
        "undici:client:connected",
        (evt) => {
          const {
            connectParams: { version: version4, protocol, port, host }
          } = evt;
          debugLog(
            "connected to %s%s using %s%s",
            host,
            port ? `:${port}` : "",
            protocol,
            version4
          );
        }
      );
      diagnosticsChannel.subscribe(
        "undici:client:connectError",
        (evt) => {
          const {
            connectParams: { version: version4, protocol, port, host },
            error
          } = evt;
          debugLog(
            "connection to %s%s using %s%s errored - %s",
            host,
            port ? `:${port}` : "",
            protocol,
            version4,
            error.message
          );
        }
      );
      diagnosticsChannel.subscribe(
        "undici:client:sendHeaders",
        (evt) => {
          const {
            request: { method, path: path2, origin }
          } = evt;
          debugLog("sending request to %s %s%s", method, origin, path2);
        }
      );
    }
    var isTrackingRequestEvents = false;
    function trackRequestEvents(debugLog = undiciDebugLog) {
      if (isTrackingRequestEvents) {
        return;
      }
      if (channels.headers.hasSubscribers || channels.trailers.hasSubscribers || channels.error.hasSubscribers) {
        isTrackingRequestEvents = true;
        return;
      }
      isTrackingRequestEvents = true;
      diagnosticsChannel.subscribe(
        "undici:request:headers",
        (evt) => {
          const {
            request: { method, path: path2, origin },
            response: { statusCode }
          } = evt;
          debugLog(
            "received response to %s %s%s - HTTP %d",
            method,
            origin,
            path2,
            statusCode
          );
        }
      );
      diagnosticsChannel.subscribe(
        "undici:request:trailers",
        (evt) => {
          const {
            request: { method, path: path2, origin }
          } = evt;
          debugLog("trailers received from %s %s%s", method, origin, path2);
        }
      );
      diagnosticsChannel.subscribe(
        "undici:request:error",
        (evt) => {
          const {
            request: { method, path: path2, origin },
            error
          } = evt;
          debugLog(
            "request to %s %s%s errored - %s",
            method,
            origin,
            path2,
            error.message
          );
        }
      );
    }
    var isTrackingWebSocketEvents = false;
    function trackWebSocketEvents(debugLog = websocketDebuglog) {
      if (isTrackingWebSocketEvents) {
        return;
      }
      if (channels.open.hasSubscribers || channels.close.hasSubscribers || channels.socketError.hasSubscribers || channels.ping.hasSubscribers || channels.pong.hasSubscribers) {
        isTrackingWebSocketEvents = true;
        return;
      }
      isTrackingWebSocketEvents = true;
      diagnosticsChannel.subscribe(
        "undici:websocket:open",
        (evt) => {
          if (evt.address != null) {
            const { address: address2, port } = evt.address;
            debugLog("connection opened %s%s", address2, port ? `:${port}` : "");
          } else {
            debugLog("connection opened");
          }
        }
      );
      diagnosticsChannel.subscribe(
        "undici:websocket:close",
        (evt) => {
          const { websocket, code, reason } = evt;
          debugLog(
            "closed connection to %s - %s %s",
            websocket.url,
            code,
            reason
          );
        }
      );
      diagnosticsChannel.subscribe(
        "undici:websocket:socket_error",
        (err) => {
          debugLog("connection errored - %s", err.message);
        }
      );
      diagnosticsChannel.subscribe(
        "undici:websocket:ping",
        (evt) => {
          debugLog("ping received");
        }
      );
      diagnosticsChannel.subscribe(
        "undici:websocket:pong",
        (evt) => {
          debugLog("pong received");
        }
      );
    }
    if (undiciDebugLog.enabled || fetchDebuglog.enabled) {
      trackClientEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog);
      trackRequestEvents(fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog);
    }
    if (websocketDebuglog.enabled) {
      trackClientEvents(undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog);
      trackWebSocketEvents(websocketDebuglog);
    }
    module.exports = {
      channels
    };
  }
});

// node_modules/undici/lib/core/request.js
var require_request = __commonJS({
  "node_modules/undici/lib/core/request.js"(exports, module) {
    "use strict";
    var {
      InvalidArgumentError,
      NotSupportedError
    } = require_errors();
    var assert8 = __require("assert");
    var {
      isValidHTTPToken,
      isValidHeaderValue,
      isStream,
      destroy,
      isBuffer,
      isFormDataLike,
      isIterable,
      hasSafeIterator,
      isBlobLike,
      serializePathWithQuery,
      parseHeaders,
      assertRequestHandler,
      getServerName,
      normalizedMethodRecords,
      getProtocolFromUrlString
    } = require_util();
    var { channels } = require_diagnostics();
    var { headerNameLowerCasedRecord } = require_constants2();
    var invalidPathRegex = /[^\u0021-\u00ff]/;
    function isValidContentLengthHeaderValue(val) {
      if (typeof val !== "string" || val.length === 0) {
        return false;
      }
      for (let i = 0; i < val.length; i++) {
        const charCode = val.charCodeAt(i);
        if (charCode < 48 || charCode > 57) {
          return false;
        }
      }
      return true;
    }
    var kHandler = /* @__PURE__ */ Symbol("handler");
    var kController = /* @__PURE__ */ Symbol("controller");
    var kResume = /* @__PURE__ */ Symbol("resume");
    var RequestController = class {
      #paused = false;
      #reason = null;
      #aborted = false;
      #abort;
      [kResume] = null;
      rawHeaders = null;
      rawTrailers = null;
      constructor(abort) {
        this.#abort = abort;
      }
      pause() {
        this.#paused = true;
      }
      resume() {
        if (this.#paused) {
          this.#paused = false;
          this[kResume]?.();
        }
      }
      abort(reason) {
        if (!this.#aborted) {
          this.#aborted = true;
          this.#reason = reason;
          this.#abort(reason);
        }
      }
      get aborted() {
        return this.#aborted;
      }
      get reason() {
        return this.#reason;
      }
      get paused() {
        return this.#paused;
      }
    };
    var Request2 = class {
      constructor(origin, {
        path: path2,
        method,
        body,
        headers,
        query,
        idempotent,
        blocking,
        upgrade,
        headersTimeout,
        bodyTimeout,
        reset,
        expectContinue,
        servername,
        throwOnError,
        maxRedirections,
        typeOfService
      }, handler) {
        if (typeof path2 !== "string") {
          throw new InvalidArgumentError("path must be a string");
        } else if (path2[0] !== "/" && !(path2.startsWith("http://") || path2.startsWith("https://")) && method !== "CONNECT") {
          throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
        } else if (invalidPathRegex.test(path2)) {
          throw new InvalidArgumentError("invalid request path");
        }
        if (typeof method !== "string") {
          throw new InvalidArgumentError("method must be a string");
        } else if (normalizedMethodRecords[method] === void 0 && !isValidHTTPToken(method)) {
          throw new InvalidArgumentError("invalid request method");
        }
        if (upgrade && typeof upgrade !== "string") {
          throw new InvalidArgumentError("upgrade must be a string");
        }
        if (upgrade && !isValidHeaderValue(upgrade)) {
          throw new InvalidArgumentError("invalid upgrade header");
        }
        if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
          throw new InvalidArgumentError("invalid headersTimeout");
        }
        if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
          throw new InvalidArgumentError("invalid bodyTimeout");
        }
        if (reset != null && typeof reset !== "boolean") {
          throw new InvalidArgumentError("invalid reset");
        }
        if (expectContinue != null && typeof expectContinue !== "boolean") {
          throw new InvalidArgumentError("invalid expectContinue");
        }
        if (throwOnError != null) {
          throw new InvalidArgumentError("invalid throwOnError");
        }
        if (maxRedirections != null && maxRedirections !== 0) {
          throw new InvalidArgumentError("maxRedirections is not supported, use the redirect interceptor");
        }
        if (typeOfService != null && (!Number.isInteger(typeOfService) || typeOfService < 0 || typeOfService > 255)) {
          throw new InvalidArgumentError("typeOfService must be an integer between 0 and 255");
        }
        this.headersTimeout = headersTimeout;
        this.bodyTimeout = bodyTimeout;
        this.method = method;
        this.typeOfService = typeOfService ?? 0;
        this.abort = null;
        if (body == null) {
          this.body = null;
        } else if (isStream(body)) {
          this.body = body;
          const rState = this.body._readableState;
          if (!rState || !rState.autoDestroy) {
            this.endHandler = function autoDestroy() {
              destroy(this);
            };
            this.body.on("end", this.endHandler);
          }
          this.errorHandler = (err) => {
            if (this.abort) {
              this.abort(err);
            } else {
              this.error = err;
            }
          };
          this.body.on("error", this.errorHandler);
        } else if (isBuffer(body)) {
          this.body = body.byteLength ? body : null;
        } else if (ArrayBuffer.isView(body)) {
          this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null;
        } else if (body instanceof ArrayBuffer) {
          this.body = body.byteLength ? Buffer.from(body) : null;
        } else if (typeof body === "string") {
          this.body = body.length ? Buffer.from(body) : null;
        } else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) {
          this.body = body;
        } else {
          throw new InvalidArgumentError("body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable");
        }
        this.completed = false;
        this.aborted = false;
        this.upgrade = upgrade || null;
        this.path = query ? serializePathWithQuery(path2, query) : path2;
        this.origin = origin;
        this.protocol = getProtocolFromUrlString(origin);
        this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
        this.blocking = blocking ?? this.method !== "HEAD";
        this.reset = reset == null ? null : reset;
        this.host = null;
        this.contentLength = null;
        this.contentType = null;
        this.headers = [];
        this.expectContinue = expectContinue != null ? expectContinue : false;
        if (Array.isArray(headers)) {
          if (headers.length % 2 !== 0) {
            throw new InvalidArgumentError("headers array must be even");
          }
          for (let i = 0; i < headers.length; i += 2) {
            processHeader(this, headers[i], headers[i + 1]);
          }
        } else if (headers && typeof headers === "object") {
          if (hasSafeIterator(headers)) {
            for (const header of headers) {
              if (!Array.isArray(header) || header.length !== 2) {
                throw new InvalidArgumentError("headers must be in key-value pair format");
              }
              processHeader(this, header[0], header[1]);
            }
          } else {
            const keys = Object.keys(headers);
            for (let i = 0; i < keys.length; ++i) {
              processHeader(this, keys[i], headers[keys[i]]);
            }
          }
        } else if (headers != null) {
          throw new InvalidArgumentError("headers must be an object or an array");
        }
        assertRequestHandler(handler, method, upgrade);
        this.servername = servername || getServerName(this.host) || null;
        this[kHandler] = handler;
        if (channels.create.hasSubscribers) {
          channels.create.publish({ request: this });
        }
      }
      onBodySent(chunk) {
        if (channels.bodyChunkSent.hasSubscribers) {
          channels.bodyChunkSent.publish({ request: this, chunk });
        }
        if (this[kHandler].onBodySent) {
          try {
            return this[kHandler].onBodySent(chunk);
          } catch (err) {
            this.abort(err);
          }
        }
      }
      onRequestSent() {
        if (channels.bodySent.hasSubscribers) {
          channels.bodySent.publish({ request: this });
        }
        if (this[kHandler].onRequestSent) {
          try {
            return this[kHandler].onRequestSent();
          } catch (err) {
            this.abort(err);
          }
        }
      }
      onRequestStart(abort, context) {
        assert8(!this.aborted);
        assert8(!this.completed);
        this[kController] = new RequestController(abort);
        if (this.error) {
          this[kController].abort(this.error);
          return;
        }
        this.abort = abort;
        return this[kHandler].onRequestStart(this[kController], context);
      }
      onResponseStarted() {
        return this[kHandler].onResponseStarted?.();
      }
      onResponseStart(statusCode, headers, resume, statusText) {
        assert8(!this.aborted);
        assert8(!this.completed);
        if (channels.headers.hasSubscribers) {
          channels.headers.publish({ request: this, response: { statusCode, headers, statusText } });
        }
        const controller = this[kController];
        if (controller) {
          controller[kResume] = resume;
          controller.rawHeaders = headers;
        }
        const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers;
        try {
          this[kHandler].onResponseStart?.(controller, statusCode, parsedHeaders, statusText);
          return !controller?.paused;
        } catch (err) {
          this.abort(err);
          return false;
        }
      }
      onResponseData(chunk) {
        assert8(!this.aborted);
        assert8(!this.completed);
        if (channels.bodyChunkReceived.hasSubscribers) {
          channels.bodyChunkReceived.publish({ request: this, chunk });
        }
        const controller = this[kController];
        try {
          this[kHandler].onResponseData?.(controller, chunk);
          return !controller?.paused;
        } catch (err) {
          this.abort(err);
          return false;
        }
      }
      onRequestUpgrade(statusCode, headers, socket) {
        assert8(!this.aborted);
        assert8(!this.completed);
        const controller = this[kController];
        if (controller) {
          controller.rawHeaders = headers;
        }
        const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers;
        return this[kHandler].onRequestUpgrade?.(controller, statusCode, parsedHeaders, socket);
      }
      onResponseEnd(trailers) {
        this.onFinally();
        assert8(!this.aborted);
        assert8(!this.completed);
        this.completed = true;
        if (channels.trailers.hasSubscribers) {
          channels.trailers.publish({ request: this, trailers });
        }
        const controller = this[kController];
        if (controller) {
          controller.rawTrailers = trailers;
        }
        const parsedTrailers = Array.isArray(trailers) ? parseHeaders(trailers) : trailers;
        try {
          return this[kHandler].onResponseEnd?.(controller, parsedTrailers);
        } catch (err) {
          this.onResponseError(err);
        }
      }
      onResponseError(error) {
        this.onFinally();
        if (channels.error.hasSubscribers) {
          channels.error.publish({ request: this, error });
        }
        if (this.aborted) {
          return;
        }
        this.aborted = true;
        const controller = this[kController];
        return this[kHandler].onResponseError?.(controller, error);
      }
      onFinally() {
        if (this.errorHandler) {
          this.body.off("error", this.errorHandler);
          this.errorHandler = null;
        }
        if (this.endHandler) {
          this.body.off("end", this.endHandler);
          this.endHandler = null;
        }
      }
      addHeader(key, value) {
        processHeader(this, key, value);
        return this;
      }
    };
    function processHeader(request, key, val) {
      if (val && (typeof val === "object" && !Array.isArray(val))) {
        throw new InvalidArgumentError(`invalid ${key} header`);
      } else if (val === void 0) {
        return;
      }
      let headerName = headerNameLowerCasedRecord[key];
      if (headerName === void 0) {
        headerName = key.toLowerCase();
        if (headerNameLowerCasedRecord[headerName] === void 0 && !isValidHTTPToken(headerName)) {
          throw new InvalidArgumentError("invalid header key");
        }
      }
      if (Array.isArray(val)) {
        const arr = [];
        for (let i = 0; i < val.length; i++) {
          if (typeof val[i] === "string") {
            if (!isValidHeaderValue(val[i])) {
              throw new InvalidArgumentError(`invalid ${key} header`);
            }
            arr.push(val[i]);
          } else if (val[i] === null) {
            arr.push("");
          } else if (typeof val[i] === "object") {
            throw new InvalidArgumentError(`invalid ${key} header`);
          } else {
            arr.push(`${val[i]}`);
          }
        }
        val = arr;
      } else if (typeof val === "string") {
        if (!isValidHeaderValue(val)) {
          throw new InvalidArgumentError(`invalid ${key} header`);
        }
      } else if (val === null) {
        val = "";
      } else {
        val = `${val}`;
      }
      if (headerName === "host") {
        if (request.host !== null) {
          throw new InvalidArgumentError("duplicate host header");
        }
        if (typeof val !== "string") {
          throw new InvalidArgumentError("invalid host header");
        }
        request.host = val;
      } else if (headerName === "content-length") {
        if (request.contentLength !== null) {
          throw new InvalidArgumentError("duplicate content-length header");
        }
        if (!isValidContentLengthHeaderValue(val)) {
          throw new InvalidArgumentError("invalid content-length header");
        }
        request.contentLength = parseInt(val, 10);
      } else if (request.contentType === null && headerName === "content-type") {
        request.contentType = val;
        request.headers.push(key, val);
      } else if (headerName === "transfer-encoding" || headerName === "keep-alive" || headerName === "upgrade") {
        throw new InvalidArgumentError(`invalid ${headerName} header`);
      } else if (headerName === "connection") {
        const value = typeof val === "string" ? val : null;
        if (value === null) {
          throw new InvalidArgumentError("invalid connection header");
        }
        for (const token of value.toLowerCase().split(",")) {
          const trimmed = token.trim();
          if (!isValidHTTPToken(trimmed)) {
            throw new InvalidArgumentError("invalid connection header");
          }
          if (trimmed === "close") {
            request.reset = true;
          }
        }
      } else if (headerName === "expect") {
        throw new NotSupportedError("expect header not supported");
      } else {
        request.headers.push(key, val);
      }
    }
    module.exports = Request2;
  }
});

// node_modules/undici/lib/dispatcher/dispatcher.js
var require_dispatcher = __commonJS({
  "node_modules/undici/lib/dispatcher/dispatcher.js"(exports, module) {
    "use strict";
    var EventEmitter = __require("events");
    var Dispatcher = class extends EventEmitter {
      dispatch() {
        throw new Error("not implemented");
      }
      close() {
        throw new Error("not implemented");
      }
      destroy() {
        throw new Error("not implemented");
      }
      compose(...args) {
        const interceptors = Array.isArray(args[0]) ? args[0] : args;
        let dispatch = this.dispatch.bind(this);
        for (const interceptor of interceptors) {
          if (interceptor == null) {
            continue;
          }
          if (typeof interceptor !== "function") {
            throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`);
          }
          dispatch = interceptor(dispatch);
          if (dispatch == null || typeof dispatch !== "function" || dispatch.length !== 2) {
            throw new TypeError("invalid interceptor");
          }
        }
        return new Proxy(this, {
          get: (target, key) => key === "dispatch" ? dispatch : target[key]
        });
      }
    };
    module.exports = Dispatcher;
  }
});

// node_modules/undici/lib/dispatcher/dispatcher-base.js
var require_dispatcher_base = __commonJS({
  "node_modules/undici/lib/dispatcher/dispatcher-base.js"(exports, module) {
    "use strict";
    var Dispatcher = require_dispatcher();
    var {
      ClientDestroyedError,
      ClientClosedError,
      InvalidArgumentError
    } = require_errors();
    var { kDestroy, kClose, kClosed, kDestroyed, kDispatch } = require_symbols();
    var kOnDestroyed = /* @__PURE__ */ Symbol("onDestroyed");
    var kOnClosed = /* @__PURE__ */ Symbol("onClosed");
    var kWebSocketOptions = /* @__PURE__ */ Symbol("webSocketOptions");
    var DispatcherBase = class extends Dispatcher {
      /** @type {boolean} */
      [kDestroyed] = false;
      /** @type {Array<Function|null} */
      [kOnDestroyed] = null;
      /** @type {boolean} */
      [kClosed] = false;
      /** @type {Array<Function>|null} */
      [kOnClosed] = null;
      /**
       * @param {import('../../types/dispatcher').DispatcherOptions} [opts]
       */
      constructor(opts) {
        super();
        this[kWebSocketOptions] = opts?.webSocket ?? {};
      }
      /**
       * @returns {import('../../types/dispatcher').WebSocketOptions}
       */
      get webSocketOptions() {
        return {
          maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024
          // 128 MB default
        };
      }
      /** @returns {boolean} */
      get destroyed() {
        return this[kDestroyed];
      }
      /** @returns {boolean} */
      get closed() {
        return this[kClosed];
      }
      close(callback) {
        if (callback === void 0) {
          return new Promise((resolve, reject) => {
            this.close((err, data) => {
              return err ? reject(err) : resolve(data);
            });
          });
        }
        if (typeof callback !== "function") {
          throw new InvalidArgumentError("invalid callback");
        }
        if (this[kDestroyed]) {
          const err = new ClientDestroyedError();
          queueMicrotask(() => callback(err, null));
          return;
        }
        if (this[kClosed]) {
          if (this[kOnClosed]) {
            this[kOnClosed].push(callback);
          } else {
            queueMicrotask(() => callback(null, null));
          }
          return;
        }
        this[kClosed] = true;
        this[kOnClosed] ??= [];
        this[kOnClosed].push(callback);
        const onClosed = () => {
          const callbacks = this[kOnClosed];
          this[kOnClosed] = null;
          for (let i = 0; i < callbacks.length; i++) {
            callbacks[i](null, null);
          }
        };
        this[kClose]().then(() => this.destroy()).then(() => queueMicrotask(onClosed));
      }
      destroy(err, callback) {
        if (typeof err === "function") {
          callback = err;
          err = null;
        }
        if (callback === void 0) {
          return new Promise((resolve, reject) => {
            this.destroy(err, (err2, data) => {
              return err2 ? reject(err2) : resolve(data);
            });
          });
        }
        if (typeof callback !== "function") {
          throw new InvalidArgumentError("invalid callback");
        }
        if (this[kDestroyed]) {
          if (this[kOnDestroyed]) {
            this[kOnDestroyed].push(callback);
          } else {
            queueMicrotask(() => callback(null, null));
          }
          return;
        }
        if (!err) {
          err = new ClientDestroyedError();
        }
        this[kDestroyed] = true;
        this[kOnDestroyed] ??= [];
        this[kOnDestroyed].push(callback);
        const onDestroyed = () => {
          const callbacks = this[kOnDestroyed];
          this[kOnDestroyed] = null;
          for (let i = 0; i < callbacks.length; i++) {
            callbacks[i](null, null);
          }
        };
        this[kDestroy](err).then(() => queueMicrotask(onDestroyed));
      }
      dispatch(opts, handler) {
        if (!handler || typeof handler !== "object") {
          throw new InvalidArgumentError("handler must be an object");
        }
        try {
          if (!opts || typeof opts !== "object") {
            throw new InvalidArgumentError("opts must be an object.");
          }
          if (opts.dispatcher) {
            throw new InvalidArgumentError("opts.dispatcher is not supported by instance methods. Pass opts.dispatcher to the top-level undici functions or call the dispatcher instance method directly.");
          }
          if (this[kDestroyed] || this[kOnDestroyed]) {
            throw new ClientDestroyedError();
          }
          if (this[kClosed]) {
            throw new ClientClosedError();
          }
          return this[kDispatch](opts, handler);
        } catch (err) {
          if (typeof handler.onResponseError !== "function") {
            throw err;
          }
          handler.onResponseError(null, err);
          return false;
        }
      }
    };
    module.exports = DispatcherBase;
  }
});

// node_modules/undici/lib/core/connect.js
var require_connect = __commonJS({
  "node_modules/undici/lib/core/connect.js"(exports, module) {
    "use strict";
    var net = __require("net");
    var assert8 = __require("assert");
    var util2 = require_util();
    var { InvalidArgumentError } = require_errors();
    var tls;
    var SessionCache = class WeakSessionCache {
      constructor(maxCachedSessions) {
        this._maxCachedSessions = maxCachedSessions;
        this._sessionCache = /* @__PURE__ */ new Map();
        this._sessionRegistry = new FinalizationRegistry((key) => {
          if (this._sessionCache.size < this._maxCachedSessions) {
            return;
          }
          const ref = this._sessionCache.get(key);
          if (ref !== void 0 && ref.deref() === void 0) {
            this._sessionCache.delete(key);
          }
        });
      }
      get(sessionKey) {
        const ref = this._sessionCache.get(sessionKey);
        return ref ? ref.deref() : null;
      }
      set(sessionKey, session) {
        if (this._maxCachedSessions === 0) {
          return;
        }
        if (this._sessionCache.has(sessionKey)) {
          this._sessionCache.delete(sessionKey);
        } else if (this._sessionCache.size >= this._maxCachedSessions) {
          for (const [key, ref] of this._sessionCache) {
            if (ref.deref() === void 0) {
              this._sessionCache.delete(key);
              return;
            }
          }
          const oldest = this._sessionCache.keys().next();
          if (!oldest.done) {
            this._sessionCache.delete(oldest.value);
          }
        }
        this._sessionCache.set(sessionKey, new WeakRef(session));
        this._sessionRegistry.register(session, sessionKey);
      }
    };
    function buildConnector({ allowH2, useH2c, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) {
      if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
        throw new InvalidArgumentError("maxCachedSessions must be a positive integer or zero");
      }
      const options = { path: socketPath, ...opts };
      const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions);
      timeout = timeout == null ? 1e4 : timeout;
      allowH2 = allowH2 != null ? allowH2 : true;
      return function connect({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {
        let socket;
        if (protocol === "https:") {
          if (!tls) {
            tls = __require("tls");
          }
          servername = servername || options.servername || util2.getServerName(host) || null;
          const sessionKey = servername || hostname;
          assert8(sessionKey);
          const session = customSession || sessionCache.get(sessionKey) || null;
          port = port || 443;
          socket = tls.connect({
            highWaterMark: 16384,
            // TLS in node can't have bigger HWM anyway...
            ...options,
            servername,
            session,
            localAddress,
            ALPNProtocols: allowH2 ? ["http/1.1", "h2"] : ["http/1.1"],
            socket: httpSocket,
            // upgrade socket connection
            port,
            host: hostname
          });
          socket.on("session", function(session2) {
            sessionCache.set(sessionKey, session2);
          });
        } else {
          assert8(!httpSocket, "httpSocket can only be sent on TLS update");
          port = port || 80;
          socket = net.connect({
            highWaterMark: 64 * 1024,
            // Same as nodejs fs streams.
            ...options,
            localAddress,
            port,
            host: hostname
          });
          if (useH2c === true) {
            socket.alpnProtocol = "h2";
          }
        }
        if (options.keepAlive == null || options.keepAlive) {
          const keepAliveInitialDelay = options.keepAliveInitialDelay === void 0 ? 6e4 : options.keepAliveInitialDelay;
          socket.setKeepAlive(true, keepAliveInitialDelay);
        }
        const clearConnectTimeout = util2.setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port });
        socket.setNoDelay(true).once(protocol === "https:" ? "secureConnect" : "connect", function() {
          queueMicrotask(clearConnectTimeout);
          if (callback) {
            const cb = callback;
            callback = null;
            cb(null, this);
          }
        }).on("error", function(err) {
          queueMicrotask(clearConnectTimeout);
          if (callback) {
            const cb = callback;
            callback = null;
            cb(err);
          }
        });
        return socket;
      };
    }
    module.exports = buildConnector;
  }
});

// node_modules/undici/lib/llhttp/utils.js
var require_utils = __commonJS({
  "node_modules/undici/lib/llhttp/utils.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.enumToMap = enumToMap;
    function enumToMap(obj, filter = [], exceptions = []) {
      const emptyFilter = (filter?.length ?? 0) === 0;
      const emptyExceptions = (exceptions?.length ?? 0) === 0;
      return Object.fromEntries(Object.entries(obj).filter(([, value]) => {
        return typeof value === "number" && (emptyFilter || filter.includes(value)) && (emptyExceptions || !exceptions.includes(value));
      }));
    }
  }
});

// node_modules/undici/lib/llhttp/constants.js
var require_constants3 = __commonJS({
  "node_modules/undici/lib/llhttp/constants.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SPECIAL_HEADERS = exports.MINOR = exports.MAJOR = exports.HTAB_SP_VCHAR_OBS_TEXT = exports.QUOTED_STRING = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.HEX = exports.URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.STATUSES_HTTP = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.HEADER_STATE = exports.FINISH = exports.STATUSES = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;
    var utils_1 = require_utils();
    exports.ERROR = {
      OK: 0,
      INTERNAL: 1,
      STRICT: 2,
      CR_EXPECTED: 25,
      LF_EXPECTED: 3,
      UNEXPECTED_CONTENT_LENGTH: 4,
      UNEXPECTED_SPACE: 30,
      CLOSED_CONNECTION: 5,
      INVALID_METHOD: 6,
      INVALID_URL: 7,
      INVALID_CONSTANT: 8,
      INVALID_VERSION: 9,
      INVALID_HEADER_TOKEN: 10,
      INVALID_CONTENT_LENGTH: 11,
      INVALID_CHUNK_SIZE: 12,
      INVALID_STATUS: 13,
      INVALID_EOF_STATE: 14,
      INVALID_TRANSFER_ENCODING: 15,
      CB_MESSAGE_BEGIN: 16,
      CB_HEADERS_COMPLETE: 17,
      CB_MESSAGE_COMPLETE: 18,
      CB_CHUNK_HEADER: 19,
      CB_CHUNK_COMPLETE: 20,
      PAUSED: 21,
      PAUSED_UPGRADE: 22,
      PAUSED_H2_UPGRADE: 23,
      USER: 24,
      CB_URL_COMPLETE: 26,
      CB_STATUS_COMPLETE: 27,
      CB_METHOD_COMPLETE: 32,
      CB_VERSION_COMPLETE: 33,
      CB_HEADER_FIELD_COMPLETE: 28,
      CB_HEADER_VALUE_COMPLETE: 29,
      CB_CHUNK_EXTENSION_NAME_COMPLETE: 34,
      CB_CHUNK_EXTENSION_VALUE_COMPLETE: 35,
      CB_RESET: 31,
      CB_PROTOCOL_COMPLETE: 38
    };
    exports.TYPE = {
      BOTH: 0,
      // default
      REQUEST: 1,
      RESPONSE: 2
    };
    exports.FLAGS = {
      CONNECTION_KEEP_ALIVE: 1 << 0,
      CONNECTION_CLOSE: 1 << 1,
      CONNECTION_UPGRADE: 1 << 2,
      CHUNKED: 1 << 3,
      UPGRADE: 1 << 4,
      CONTENT_LENGTH: 1 << 5,
      SKIPBODY: 1 << 6,
      TRAILING: 1 << 7,
      // 1 << 8 is unused
      TRANSFER_ENCODING: 1 << 9
    };
    exports.LENIENT_FLAGS = {
      HEADERS: 1 << 0,
      CHUNKED_LENGTH: 1 << 1,
      KEEP_ALIVE: 1 << 2,
      TRANSFER_ENCODING: 1 << 3,
      VERSION: 1 << 4,
      DATA_AFTER_CLOSE: 1 << 5,
      OPTIONAL_LF_AFTER_CR: 1 << 6,
      OPTIONAL_CRLF_AFTER_CHUNK: 1 << 7,
      OPTIONAL_CR_BEFORE_LF: 1 << 8,
      SPACES_AFTER_CHUNK_SIZE: 1 << 9
    };
    exports.METHODS = {
      "DELETE": 0,
      "GET": 1,
      "HEAD": 2,
      "POST": 3,
      "PUT": 4,
      /* pathological */
      "CONNECT": 5,
      "OPTIONS": 6,
      "TRACE": 7,
      /* WebDAV */
      "COPY": 8,
      "LOCK": 9,
      "MKCOL": 10,
      "MOVE": 11,
      "PROPFIND": 12,
      "PROPPATCH": 13,
      "SEARCH": 14,
      "UNLOCK": 15,
      "BIND": 16,
      "REBIND": 17,
      "UNBIND": 18,
      "ACL": 19,
      /* subversion */
      "REPORT": 20,
      "MKACTIVITY": 21,
      "CHECKOUT": 22,
      "MERGE": 23,
      /* upnp */
      "M-SEARCH": 24,
      "NOTIFY": 25,
      "SUBSCRIBE": 26,
      "UNSUBSCRIBE": 27,
      /* RFC-5789 */
      "PATCH": 28,
      "PURGE": 29,
      /* CalDAV */
      "MKCALENDAR": 30,
      /* RFC-2068, section 19.6.1.2 */
      "LINK": 31,
      "UNLINK": 32,
      /* icecast */
      "SOURCE": 33,
      /* RFC-7540, section 11.6 */
      "PRI": 34,
      /* RFC-2326 RTSP */
      "DESCRIBE": 35,
      "ANNOUNCE": 36,
      "SETUP": 37,
      "PLAY": 38,
      "PAUSE": 39,
      "TEARDOWN": 40,
      "GET_PARAMETER": 41,
      "SET_PARAMETER": 42,
      "REDIRECT": 43,
      "RECORD": 44,
      /* RAOP */
      "FLUSH": 45,
      /* DRAFT https://www.ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-02.html */
      "QUERY": 46
    };
    exports.STATUSES = {
      CONTINUE: 100,
      SWITCHING_PROTOCOLS: 101,
      PROCESSING: 102,
      EARLY_HINTS: 103,
      RESPONSE_IS_STALE: 110,
      // Unofficial
      REVALIDATION_FAILED: 111,
      // Unofficial
      DISCONNECTED_OPERATION: 112,
      // Unofficial
      HEURISTIC_EXPIRATION: 113,
      // Unofficial
      MISCELLANEOUS_WARNING: 199,
      // Unofficial
      OK: 200,
      CREATED: 201,
      ACCEPTED: 202,
      NON_AUTHORITATIVE_INFORMATION: 203,
      NO_CONTENT: 204,
      RESET_CONTENT: 205,
      PARTIAL_CONTENT: 206,
      MULTI_STATUS: 207,
      ALREADY_REPORTED: 208,
      TRANSFORMATION_APPLIED: 214,
      // Unofficial
      IM_USED: 226,
      MISCELLANEOUS_PERSISTENT_WARNING: 299,
      // Unofficial
      MULTIPLE_CHOICES: 300,
      MOVED_PERMANENTLY: 301,
      FOUND: 302,
      SEE_OTHER: 303,
      NOT_MODIFIED: 304,
      USE_PROXY: 305,
      SWITCH_PROXY: 306,
      // No longer used
      TEMPORARY_REDIRECT: 307,
      PERMANENT_REDIRECT: 308,
      BAD_REQUEST: 400,
      UNAUTHORIZED: 401,
      PAYMENT_REQUIRED: 402,
      FORBIDDEN: 403,
      NOT_FOUND: 404,
      METHOD_NOT_ALLOWED: 405,
      NOT_ACCEPTABLE: 406,
      PROXY_AUTHENTICATION_REQUIRED: 407,
      REQUEST_TIMEOUT: 408,
      CONFLICT: 409,
      GONE: 410,
      LENGTH_REQUIRED: 411,
      PRECONDITION_FAILED: 412,
      PAYLOAD_TOO_LARGE: 413,
      URI_TOO_LONG: 414,
      UNSUPPORTED_MEDIA_TYPE: 415,
      RANGE_NOT_SATISFIABLE: 416,
      EXPECTATION_FAILED: 417,
      IM_A_TEAPOT: 418,
      PAGE_EXPIRED: 419,
      // Unofficial
      ENHANCE_YOUR_CALM: 420,
      // Unofficial
      MISDIRECTED_REQUEST: 421,
      UNPROCESSABLE_ENTITY: 422,
      LOCKED: 423,
      FAILED_DEPENDENCY: 424,
      TOO_EARLY: 425,
      UPGRADE_REQUIRED: 426,
      PRECONDITION_REQUIRED: 428,
      TOO_MANY_REQUESTS: 429,
      REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL: 430,
      // Unofficial
      REQUEST_HEADER_FIELDS_TOO_LARGE: 431,
      LOGIN_TIMEOUT: 440,
      // Unofficial
      NO_RESPONSE: 444,
      // Unofficial
      RETRY_WITH: 449,
      // Unofficial
      BLOCKED_BY_PARENTAL_CONTROL: 450,
      // Unofficial
      UNAVAILABLE_FOR_LEGAL_REASONS: 451,
      CLIENT_CLOSED_LOAD_BALANCED_REQUEST: 460,
      // Unofficial
      INVALID_X_FORWARDED_FOR: 463,
      // Unofficial
      REQUEST_HEADER_TOO_LARGE: 494,
      // Unofficial
      SSL_CERTIFICATE_ERROR: 495,
      // Unofficial
      SSL_CERTIFICATE_REQUIRED: 496,
      // Unofficial
      HTTP_REQUEST_SENT_TO_HTTPS_PORT: 497,
      // Unofficial
      INVALID_TOKEN: 498,
      // Unofficial
      CLIENT_CLOSED_REQUEST: 499,
      // Unofficial
      INTERNAL_SERVER_ERROR: 500,
      NOT_IMPLEMENTED: 501,
      BAD_GATEWAY: 502,
      SERVICE_UNAVAILABLE: 503,
      GATEWAY_TIMEOUT: 504,
      HTTP_VERSION_NOT_SUPPORTED: 505,
      VARIANT_ALSO_NEGOTIATES: 506,
      INSUFFICIENT_STORAGE: 507,
      LOOP_DETECTED: 508,
      BANDWIDTH_LIMIT_EXCEEDED: 509,
      NOT_EXTENDED: 510,
      NETWORK_AUTHENTICATION_REQUIRED: 511,
      WEB_SERVER_UNKNOWN_ERROR: 520,
      // Unofficial
      WEB_SERVER_IS_DOWN: 521,
      // Unofficial
      CONNECTION_TIMEOUT: 522,
      // Unofficial
      ORIGIN_IS_UNREACHABLE: 523,
      // Unofficial
      TIMEOUT_OCCURED: 524,
      // Unofficial
      SSL_HANDSHAKE_FAILED: 525,
      // Unofficial
      INVALID_SSL_CERTIFICATE: 526,
      // Unofficial
      RAILGUN_ERROR: 527,
      // Unofficial
      SITE_IS_OVERLOADED: 529,
      // Unofficial
      SITE_IS_FROZEN: 530,
      // Unofficial
      IDENTITY_PROVIDER_AUTHENTICATION_ERROR: 561,
      // Unofficial
      NETWORK_READ_TIMEOUT: 598,
      // Unofficial
      NETWORK_CONNECT_TIMEOUT: 599
      // Unofficial
    };
    exports.FINISH = {
      SAFE: 0,
      SAFE_WITH_CB: 1,
      UNSAFE: 2
    };
    exports.HEADER_STATE = {
      GENERAL: 0,
      CONNECTION: 1,
      CONTENT_LENGTH: 2,
      TRANSFER_ENCODING: 3,
      UPGRADE: 4,
      CONNECTION_KEEP_ALIVE: 5,
      CONNECTION_CLOSE: 6,
      CONNECTION_UPGRADE: 7,
      TRANSFER_ENCODING_CHUNKED: 8
    };
    exports.METHODS_HTTP = [
      exports.METHODS.DELETE,
      exports.METHODS.GET,
      exports.METHODS.HEAD,
      exports.METHODS.POST,
      exports.METHODS.PUT,
      exports.METHODS.CONNECT,
      exports.METHODS.OPTIONS,
      exports.METHODS.TRACE,
      exports.METHODS.COPY,
      exports.METHODS.LOCK,
      exports.METHODS.MKCOL,
      exports.METHODS.MOVE,
      exports.METHODS.PROPFIND,
      exports.METHODS.PROPPATCH,
      exports.METHODS.SEARCH,
      exports.METHODS.UNLOCK,
      exports.METHODS.BIND,
      exports.METHODS.REBIND,
      exports.METHODS.UNBIND,
      exports.METHODS.ACL,
      exports.METHODS.REPORT,
      exports.METHODS.MKACTIVITY,
      exports.METHODS.CHECKOUT,
      exports.METHODS.MERGE,
      exports.METHODS["M-SEARCH"],
      exports.METHODS.NOTIFY,
      exports.METHODS.SUBSCRIBE,
      exports.METHODS.UNSUBSCRIBE,
      exports.METHODS.PATCH,
      exports.METHODS.PURGE,
      exports.METHODS.MKCALENDAR,
      exports.METHODS.LINK,
      exports.METHODS.UNLINK,
      exports.METHODS.PRI,
      // TODO(indutny): should we allow it with HTTP?
      exports.METHODS.SOURCE,
      exports.METHODS.QUERY
    ];
    exports.METHODS_ICE = [
      exports.METHODS.SOURCE
    ];
    exports.METHODS_RTSP = [
      exports.METHODS.OPTIONS,
      exports.METHODS.DESCRIBE,
      exports.METHODS.ANNOUNCE,
      exports.METHODS.SETUP,
      exports.METHODS.PLAY,
      exports.METHODS.PAUSE,
      exports.METHODS.TEARDOWN,
      exports.METHODS.GET_PARAMETER,
      exports.METHODS.SET_PARAMETER,
      exports.METHODS.REDIRECT,
      exports.METHODS.RECORD,
      exports.METHODS.FLUSH,
      // For AirPlay
      exports.METHODS.GET,
      exports.METHODS.POST
    ];
    exports.METHOD_MAP = (0, utils_1.enumToMap)(exports.METHODS);
    exports.H_METHOD_MAP = Object.fromEntries(Object.entries(exports.METHODS).filter(([k]) => k.startsWith("H")));
    exports.STATUSES_HTTP = [
      exports.STATUSES.CONTINUE,
      exports.STATUSES.SWITCHING_PROTOCOLS,
      exports.STATUSES.PROCESSING,
      exports.STATUSES.EARLY_HINTS,
      exports.STATUSES.RESPONSE_IS_STALE,
      exports.STATUSES.REVALIDATION_FAILED,
      exports.STATUSES.DISCONNECTED_OPERATION,
      exports.STATUSES.HEURISTIC_EXPIRATION,
      exports.STATUSES.MISCELLANEOUS_WARNING,
      exports.STATUSES.OK,
      exports.STATUSES.CREATED,
      exports.STATUSES.ACCEPTED,
      exports.STATUSES.NON_AUTHORITATIVE_INFORMATION,
      exports.STATUSES.NO_CONTENT,
      exports.STATUSES.RESET_CONTENT,
      exports.STATUSES.PARTIAL_CONTENT,
      exports.STATUSES.MULTI_STATUS,
      exports.STATUSES.ALREADY_REPORTED,
      exports.STATUSES.TRANSFORMATION_APPLIED,
      exports.STATUSES.IM_USED,
      exports.STATUSES.MISCELLANEOUS_PERSISTENT_WARNING,
      exports.STATUSES.MULTIPLE_CHOICES,
      exports.STATUSES.MOVED_PERMANENTLY,
      exports.STATUSES.FOUND,
      exports.STATUSES.SEE_OTHER,
      exports.STATUSES.NOT_MODIFIED,
      exports.STATUSES.USE_PROXY,
      exports.STATUSES.SWITCH_PROXY,
      exports.STATUSES.TEMPORARY_REDIRECT,
      exports.STATUSES.PERMANENT_REDIRECT,
      exports.STATUSES.BAD_REQUEST,
      exports.STATUSES.UNAUTHORIZED,
      exports.STATUSES.PAYMENT_REQUIRED,
      exports.STATUSES.FORBIDDEN,
      exports.STATUSES.NOT_FOUND,
      exports.STATUSES.METHOD_NOT_ALLOWED,
      exports.STATUSES.NOT_ACCEPTABLE,
      exports.STATUSES.PROXY_AUTHENTICATION_REQUIRED,
      exports.STATUSES.REQUEST_TIMEOUT,
      exports.STATUSES.CONFLICT,
      exports.STATUSES.GONE,
      exports.STATUSES.LENGTH_REQUIRED,
      exports.STATUSES.PRECONDITION_FAILED,
      exports.STATUSES.PAYLOAD_TOO_LARGE,
      exports.STATUSES.URI_TOO_LONG,
      exports.STATUSES.UNSUPPORTED_MEDIA_TYPE,
      exports.STATUSES.RANGE_NOT_SATISFIABLE,
      exports.STATUSES.EXPECTATION_FAILED,
      exports.STATUSES.IM_A_TEAPOT,
      exports.STATUSES.PAGE_EXPIRED,
      exports.STATUSES.ENHANCE_YOUR_CALM,
      exports.STATUSES.MISDIRECTED_REQUEST,
      exports.STATUSES.UNPROCESSABLE_ENTITY,
      exports.STATUSES.LOCKED,
      exports.STATUSES.FAILED_DEPENDENCY,
      exports.STATUSES.TOO_EARLY,
      exports.STATUSES.UPGRADE_REQUIRED,
      exports.STATUSES.PRECONDITION_REQUIRED,
      exports.STATUSES.TOO_MANY_REQUESTS,
      exports.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL,
      exports.STATUSES.REQUEST_HEADER_FIELDS_TOO_LARGE,
      exports.STATUSES.LOGIN_TIMEOUT,
      exports.STATUSES.NO_RESPONSE,
      exports.STATUSES.RETRY_WITH,
      exports.STATUSES.BLOCKED_BY_PARENTAL_CONTROL,
      exports.STATUSES.UNAVAILABLE_FOR_LEGAL_REASONS,
      exports.STATUSES.CLIENT_CLOSED_LOAD_BALANCED_REQUEST,
      exports.STATUSES.INVALID_X_FORWARDED_FOR,
      exports.STATUSES.REQUEST_HEADER_TOO_LARGE,
      exports.STATUSES.SSL_CERTIFICATE_ERROR,
      exports.STATUSES.SSL_CERTIFICATE_REQUIRED,
      exports.STATUSES.HTTP_REQUEST_SENT_TO_HTTPS_PORT,
      exports.STATUSES.INVALID_TOKEN,
      exports.STATUSES.CLIENT_CLOSED_REQUEST,
      exports.STATUSES.INTERNAL_SERVER_ERROR,
      exports.STATUSES.NOT_IMPLEMENTED,
      exports.STATUSES.BAD_GATEWAY,
      exports.STATUSES.SERVICE_UNAVAILABLE,
      exports.STATUSES.GATEWAY_TIMEOUT,
      exports.STATUSES.HTTP_VERSION_NOT_SUPPORTED,
      exports.STATUSES.VARIANT_ALSO_NEGOTIATES,
      exports.STATUSES.INSUFFICIENT_STORAGE,
      exports.STATUSES.LOOP_DETECTED,
      exports.STATUSES.BANDWIDTH_LIMIT_EXCEEDED,
      exports.STATUSES.NOT_EXTENDED,
      exports.STATUSES.NETWORK_AUTHENTICATION_REQUIRED,
      exports.STATUSES.WEB_SERVER_UNKNOWN_ERROR,
      exports.STATUSES.WEB_SERVER_IS_DOWN,
      exports.STATUSES.CONNECTION_TIMEOUT,
      exports.STATUSES.ORIGIN_IS_UNREACHABLE,
      exports.STATUSES.TIMEOUT_OCCURED,
      exports.STATUSES.SSL_HANDSHAKE_FAILED,
      exports.STATUSES.INVALID_SSL_CERTIFICATE,
      exports.STATUSES.RAILGUN_ERROR,
      exports.STATUSES.SITE_IS_OVERLOADED,
      exports.STATUSES.SITE_IS_FROZEN,
      exports.STATUSES.IDENTITY_PROVIDER_AUTHENTICATION_ERROR,
      exports.STATUSES.NETWORK_READ_TIMEOUT,
      exports.STATUSES.NETWORK_CONNECT_TIMEOUT
    ];
    exports.ALPHA = [];
    for (let i = "A".charCodeAt(0); i <= "Z".charCodeAt(0); i++) {
      exports.ALPHA.push(String.fromCharCode(i));
      exports.ALPHA.push(String.fromCharCode(i + 32));
    }
    exports.NUM_MAP = {
      0: 0,
      1: 1,
      2: 2,
      3: 3,
      4: 4,
      5: 5,
      6: 6,
      7: 7,
      8: 8,
      9: 9
    };
    exports.HEX_MAP = {
      0: 0,
      1: 1,
      2: 2,
      3: 3,
      4: 4,
      5: 5,
      6: 6,
      7: 7,
      8: 8,
      9: 9,
      A: 10,
      B: 11,
      C: 12,
      D: 13,
      E: 14,
      F: 15,
      a: 10,
      b: 11,
      c: 12,
      d: 13,
      e: 14,
      f: 15
    };
    exports.NUM = [
      "0",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9"
    ];
    exports.ALPHANUM = exports.ALPHA.concat(exports.NUM);
    exports.MARK = ["-", "_", ".", "!", "~", "*", "'", "(", ")"];
    exports.USERINFO_CHARS = exports.ALPHANUM.concat(exports.MARK).concat(["%", ";", ":", "&", "=", "+", "$", ","]);
    exports.URL_CHAR = [
      "!",
      '"',
      "$",
      "%",
      "&",
      "'",
      "(",
      ")",
      "*",
      "+",
      ",",
      "-",
      ".",
      "/",
      ":",
      ";",
      "<",
      "=",
      ">",
      "@",
      "[",
      "\\",
      "]",
      "^",
      "_",
      "`",
      "{",
      "|",
      "}",
      "~"
    ].concat(exports.ALPHANUM);
    exports.HEX = exports.NUM.concat(["a", "b", "c", "d", "e", "f", "A", "B", "C", "D", "E", "F"]);
    exports.TOKEN = [
      "!",
      "#",
      "$",
      "%",
      "&",
      "'",
      "*",
      "+",
      "-",
      ".",
      "^",
      "_",
      "`",
      "|",
      "~"
    ].concat(exports.ALPHANUM);
    exports.HEADER_CHARS = ["	"];
    for (let i = 32; i <= 255; i++) {
      if (i !== 127) {
        exports.HEADER_CHARS.push(i);
      }
    }
    exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44);
    exports.QUOTED_STRING = ["	", " "];
    for (let i = 33; i <= 255; i++) {
      if (i !== 34 && i !== 92) {
        exports.QUOTED_STRING.push(i);
      }
    }
    exports.HTAB_SP_VCHAR_OBS_TEXT = ["	", " "];
    for (let i = 33; i <= 126; i++) {
      exports.HTAB_SP_VCHAR_OBS_TEXT.push(i);
    }
    for (let i = 128; i <= 255; i++) {
      exports.HTAB_SP_VCHAR_OBS_TEXT.push(i);
    }
    exports.MAJOR = exports.NUM_MAP;
    exports.MINOR = exports.MAJOR;
    exports.SPECIAL_HEADERS = {
      "connection": exports.HEADER_STATE.CONNECTION,
      "content-length": exports.HEADER_STATE.CONTENT_LENGTH,
      "proxy-connection": exports.HEADER_STATE.CONNECTION,
      "transfer-encoding": exports.HEADER_STATE.TRANSFER_ENCODING,
      "upgrade": exports.HEADER_STATE.UPGRADE
    };
    exports.default = {
      ERROR: exports.ERROR,
      TYPE: exports.TYPE,
      FLAGS: exports.FLAGS,
      LENIENT_FLAGS: exports.LENIENT_FLAGS,
      METHODS: exports.METHODS,
      STATUSES: exports.STATUSES,
      FINISH: exports.FINISH,
      HEADER_STATE: exports.HEADER_STATE,
      ALPHA: exports.ALPHA,
      NUM_MAP: exports.NUM_MAP,
      HEX_MAP: exports.HEX_MAP,
      NUM: exports.NUM,
      ALPHANUM: exports.ALPHANUM,
      MARK: exports.MARK,
      USERINFO_CHARS: exports.USERINFO_CHARS,
      URL_CHAR: exports.URL_CHAR,
      HEX: exports.HEX,
      TOKEN: exports.TOKEN,
      HEADER_CHARS: exports.HEADER_CHARS,
      CONNECTION_TOKEN_CHARS: exports.CONNECTION_TOKEN_CHARS,
      QUOTED_STRING: exports.QUOTED_STRING,
      HTAB_SP_VCHAR_OBS_TEXT: exports.HTAB_SP_VCHAR_OBS_TEXT,
      MAJOR: exports.MAJOR,
      MINOR: exports.MINOR,
      SPECIAL_HEADERS: exports.SPECIAL_HEADERS,
      METHODS_HTTP: exports.METHODS_HTTP,
      METHODS_ICE: exports.METHODS_ICE,
      METHODS_RTSP: exports.METHODS_RTSP,
      METHOD_MAP: exports.METHOD_MAP,
      H_METHOD_MAP: exports.H_METHOD_MAP,
      STATUSES_HTTP: exports.STATUSES_HTTP
    };
  }
});

// node_modules/undici/lib/llhttp/llhttp-wasm.js
var require_llhttp_wasm = __commonJS({
  "node_modules/undici/lib/llhttp/llhttp-wasm.js"(exports, module) {
    "use strict";
    var { Buffer: Buffer2 } = __require("buffer");
    var wasmBase64 = " ";
    var wasmBuffer;
    Object.defineProperty(module, "exports", {
      get: () => {
        return wasmBuffer ? wasmBuffer : wasmBuffer = Buffer2.from(wasmBase64, "base64");
      }
    });
  }
});

// node_modules/undici/lib/llhttp/llhttp_simd-wasm.js
var require_llhttp_simd_wasm = __commonJS({
  "node_modules/undici/lib/llhttp/llhttp_simd-wasm.js"(exports, module) {
    "use strict";
    var { Buffer: Buffer2 } = __require("buffer");
    var wasmBase64 = " ";
    var wasmBuffer;
    Object.defineProperty(module, "exports", {
      get: () => {
        return wasmBuffer ? wasmBuffer : wasmBuffer = Buffer2.from(wasmBase64, "base64");
      }
    });
  }
});

// node_modules/undici/lib/web/fetch/constants.js
var require_constants4 = __commonJS({
  "node_modules/undici/lib/web/fetch/constants.js"(exports, module) {
    "use strict";
    var corsSafeListedMethods = (
      /** @type {const} */
      ["GET", "HEAD", "POST"]
    );
    var corsSafeListedMethodsSet = new Set(corsSafeListedMethods);
    var nullBodyStatus = (
      /** @type {const} */
      [101, 204, 205, 304]
    );
    var redirectStatus = (
      /** @type {const} */
      [301, 302, 303, 307, 308]
    );
    var redirectStatusSet = new Set(redirectStatus);
    var badPorts = (
      /** @type {const} */
      [
        "1",
        "7",
        "9",
        "11",
        "13",
        "15",
        "17",
        "19",
        "20",
        "21",
        "22",
        "23",
        "25",
        "37",
        "42",
        "43",
        "53",
        "69",
        "77",
        "79",
        "87",
        "95",
        "101",
        "102",
        "103",
        "104",
        "109",
        "110",
        "111",
        "113",
        "115",
        "117",
        "119",
        "123",
        "135",
        "137",
        "139",
        "143",
        "161",
        "179",
        "389",
        "427",
        "465",
        "512",
        "513",
        "514",
        "515",
        "526",
        "530",
        "531",
        "532",
        "540",
        "548",
        "554",
        "556",
        "563",
        "587",
        "601",
        "636",
        "989",
        "990",
        "993",
        "995",
        "1719",
        "1720",
        "1723",
        "2049",
        "3659",
        "4045",
        "4190",
        "5060",
        "5061",
        "6000",
        "6566",
        "6665",
        "6666",
        "6667",
        "6668",
        "6669",
        "6679",
        "6697",
        "10080"
      ]
    );
    var badPortsSet = new Set(badPorts);
    var referrerPolicyTokens = (
      /** @type {const} */
      [
        "no-referrer",
        "no-referrer-when-downgrade",
        "same-origin",
        "origin",
        "strict-origin",
        "origin-when-cross-origin",
        "strict-origin-when-cross-origin",
        "unsafe-url"
      ]
    );
    var referrerPolicy = (
      /** @type {const} */
      [
        "",
        ...referrerPolicyTokens
      ]
    );
    var referrerPolicyTokensSet = new Set(referrerPolicyTokens);
    var requestRedirect = (
      /** @type {const} */
      ["follow", "manual", "error"]
    );
    var safeMethods = (
      /** @type {const} */
      ["GET", "HEAD", "OPTIONS", "TRACE"]
    );
    var safeMethodsSet = new Set(safeMethods);
    var requestMode = (
      /** @type {const} */
      ["navigate", "same-origin", "no-cors", "cors"]
    );
    var requestCredentials = (
      /** @type {const} */
      ["omit", "same-origin", "include"]
    );
    var requestCache = (
      /** @type {const} */
      [
        "default",
        "no-store",
        "reload",
        "no-cache",
        "force-cache",
        "only-if-cached"
      ]
    );
    var requestBodyHeader = (
      /** @type {const} */
      [
        "content-encoding",
        "content-language",
        "content-location",
        "content-type",
        // See https://github.com/nodejs/undici/issues/2021
        // 'Content-Length' is a forbidden header name, which is typically
        // removed in the Headers implementation. However, undici doesn't
        // filter out headers, so we add it here.
        "content-length"
      ]
    );
    var requestDuplex = (
      /** @type {const} */
      [
        "half"
      ]
    );
    var forbiddenMethods = (
      /** @type {const} */
      ["CONNECT", "TRACE", "TRACK"]
    );
    var forbiddenMethodsSet = new Set(forbiddenMethods);
    var subresource = (
      /** @type {const} */
      [
        "audio",
        "audioworklet",
        "font",
        "image",
        "manifest",
        "paintworklet",
        "script",
        "style",
        "track",
        "video",
        "xslt",
        ""
      ]
    );
    var subresourceSet = new Set(subresource);
    module.exports = {
      subresource,
      forbiddenMethods,
      requestBodyHeader,
      referrerPolicy,
      requestRedirect,
      requestMode,
      requestCredentials,
      requestCache,
      redirectStatus,
      corsSafeListedMethods,
      nullBodyStatus,
      safeMethods,
      badPorts,
      requestDuplex,
      subresourceSet,
      badPortsSet,
      redirectStatusSet,
      corsSafeListedMethodsSet,
      safeMethodsSet,
      forbiddenMethodsSet,
      referrerPolicyTokens: referrerPolicyTokensSet
    };
  }
});

// node_modules/undici/lib/web/fetch/global.js
var require_global = __commonJS({
  "node_modules/undici/lib/web/fetch/global.js"(exports, module) {
    "use strict";
    var globalOrigin = /* @__PURE__ */ Symbol.for("undici.globalOrigin.1");
    function getGlobalOrigin() {
      return globalThis[globalOrigin];
    }
    function setGlobalOrigin(newOrigin) {
      if (newOrigin === void 0) {
        Object.defineProperty(globalThis, globalOrigin, {
          value: void 0,
          writable: true,
          enumerable: false,
          configurable: false
        });
        return;
      }
      const parsedURL = new URL(newOrigin);
      if (parsedURL.protocol !== "http:" && parsedURL.protocol !== "https:") {
        throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`);
      }
      Object.defineProperty(globalThis, globalOrigin, {
        value: parsedURL,
        writable: true,
        enumerable: false,
        configurable: false
      });
    }
    module.exports = {
      getGlobalOrigin,
      setGlobalOrigin
    };
  }
});

// node_modules/undici/lib/encoding/index.js
var require_encoding = __commonJS({
  "node_modules/undici/lib/encoding/index.js"(exports, module) {
    "use strict";
    var textDecoder = new TextDecoder();
    function utf8DecodeBytes(buffer2) {
      if (buffer2.length === 0) {
        return "";
      }
      if (buffer2[0] === 239 && buffer2[1] === 187 && buffer2[2] === 191) {
        buffer2 = buffer2.subarray(3);
      }
      const output = textDecoder.decode(buffer2);
      return output;
    }
    module.exports = {
      utf8DecodeBytes
    };
  }
});

// node_modules/undici/lib/web/infra/index.js
var require_infra = __commonJS({
  "node_modules/undici/lib/web/infra/index.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var { utf8DecodeBytes } = require_encoding();
    function collectASequenceOfCodePoints(condition, input, position) {
      let result = "";
      while (position.position < input.length && condition(input[position.position])) {
        result += input[position.position];
        position.position++;
      }
      return result;
    }
    function collectASequenceOfCodePointsFast(char, input, position) {
      const idx = input.indexOf(char, position.position);
      const start = position.position;
      if (idx === -1) {
        position.position = input.length;
        return input.slice(start);
      }
      position.position = idx;
      return input.slice(start, position.position);
    }
    var ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g;
    function forgivingBase64(data) {
      data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, "");
      let dataLength = data.length;
      if (dataLength % 4 === 0) {
        if (data.charCodeAt(dataLength - 1) === 61) {
          --dataLength;
          if (data.charCodeAt(dataLength - 1) === 61) {
            --dataLength;
          }
        }
      }
      if (dataLength % 4 === 1) {
        return "failure";
      }
      if (/[^+/0-9A-Za-z]/.test(data.length === dataLength ? data : data.substring(0, dataLength))) {
        return "failure";
      }
      const buffer2 = Buffer.from(data, "base64");
      return new Uint8Array(buffer2.buffer, buffer2.byteOffset, buffer2.byteLength);
    }
    function isASCIIWhitespace(char) {
      return char === 9 || // \t
      char === 10 || // \n
      char === 12 || // \f
      char === 13 || // \r
      char === 32;
    }
    function isomorphicDecode(input) {
      const length = input.length;
      if ((2 << 15) - 1 > length) {
        return String.fromCharCode.apply(null, input);
      }
      let result = "";
      let i = 0;
      let addition = (2 << 15) - 1;
      while (i < length) {
        if (i + addition > length) {
          addition = length - i;
        }
        result += String.fromCharCode.apply(null, input.subarray(i, i += addition));
      }
      return result;
    }
    var invalidIsomorphicEncodeValueRegex = /[^\x00-\xFF]/;
    function isomorphicEncode(input) {
      assert8(!invalidIsomorphicEncodeValueRegex.test(input));
      return input;
    }
    function parseJSONFromBytes(bytes) {
      return JSON.parse(utf8DecodeBytes(bytes));
    }
    function removeASCIIWhitespace(str, leading = true, trailing = true) {
      return removeChars(str, leading, trailing, isASCIIWhitespace);
    }
    function removeChars(str, leading, trailing, predicate) {
      let lead = 0;
      let trail = str.length - 1;
      if (leading) {
        while (lead < str.length && predicate(str.charCodeAt(lead))) lead++;
      }
      if (trailing) {
        while (trail > 0 && predicate(str.charCodeAt(trail))) trail--;
      }
      return lead === 0 && trail === str.length - 1 ? str : str.slice(lead, trail + 1);
    }
    function serializeJavascriptValueToJSONString(value) {
      const result = JSON.stringify(value);
      if (result === void 0) {
        throw new TypeError("Value is not JSON serializable");
      }
      assert8(typeof result === "string");
      return result;
    }
    module.exports = {
      collectASequenceOfCodePoints,
      collectASequenceOfCodePointsFast,
      forgivingBase64,
      isASCIIWhitespace,
      isomorphicDecode,
      isomorphicEncode,
      parseJSONFromBytes,
      removeASCIIWhitespace,
      removeChars,
      serializeJavascriptValueToJSONString
    };
  }
});

// node_modules/undici/lib/web/fetch/data-url.js
var require_data_url = __commonJS({
  "node_modules/undici/lib/web/fetch/data-url.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var { forgivingBase64, collectASequenceOfCodePoints, collectASequenceOfCodePointsFast, isomorphicDecode, removeASCIIWhitespace, removeChars } = require_infra();
    var encoder5 = new TextEncoder();
    var HTTP_TOKEN_CODEPOINTS = /^[-!#$%&'*+.^_|~A-Za-z0-9]+$/u;
    var HTTP_WHITESPACE_REGEX = /[\u000A\u000D\u0009\u0020]/u;
    var HTTP_QUOTED_STRING_TOKENS = /^[\u0009\u0020-\u007E\u0080-\u00FF]+$/u;
    function dataURLProcessor(dataURL) {
      assert8(dataURL.protocol === "data:");
      let input = URLSerializer(dataURL, true);
      input = input.slice(5);
      const position = { position: 0 };
      let mimeType = collectASequenceOfCodePointsFast(
        ",",
        input,
        position
      );
      const mimeTypeLength = mimeType.length;
      mimeType = removeASCIIWhitespace(mimeType, true, true);
      if (position.position >= input.length) {
        return "failure";
      }
      position.position++;
      const encodedBody = input.slice(mimeTypeLength + 1);
      let body = stringPercentDecode(encodedBody);
      if (/;(?:\u0020*)base64$/ui.test(mimeType)) {
        const stringBody = isomorphicDecode(body);
        body = forgivingBase64(stringBody);
        if (body === "failure") {
          return "failure";
        }
        mimeType = mimeType.slice(0, -6);
        mimeType = mimeType.replace(/(\u0020+)$/u, "");
        mimeType = mimeType.slice(0, -1);
      }
      if (mimeType.startsWith(";")) {
        mimeType = "text/plain" + mimeType;
      }
      let mimeTypeRecord = parseMIMEType(mimeType);
      if (mimeTypeRecord === "failure") {
        mimeTypeRecord = parseMIMEType("text/plain;charset=US-ASCII");
      }
      return { mimeType: mimeTypeRecord, body };
    }
    function URLSerializer(url, excludeFragment = false) {
      if (!excludeFragment) {
        return url.href;
      }
      const href = url.href;
      const hashLength = url.hash.length;
      const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength);
      if (!hashLength && href.endsWith("#")) {
        return serialized.slice(0, -1);
      }
      return serialized;
    }
    function stringPercentDecode(input) {
      const bytes = encoder5.encode(input);
      return percentDecode(bytes);
    }
    function isHexCharByte(byte) {
      return byte >= 48 && byte <= 57 || byte >= 65 && byte <= 70 || byte >= 97 && byte <= 102;
    }
    function hexByteToNumber(byte) {
      return (
        // 0-9
        byte >= 48 && byte <= 57 ? byte - 48 : (byte & 223) - 55
      );
    }
    function percentDecode(input) {
      const length = input.length;
      const output = new Uint8Array(length);
      let j = 0;
      let i = 0;
      while (i < length) {
        const byte = input[i];
        if (byte !== 37) {
          output[j++] = byte;
        } else if (byte === 37 && !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2]))) {
          output[j++] = 37;
        } else {
          output[j++] = hexByteToNumber(input[i + 1]) << 4 | hexByteToNumber(input[i + 2]);
          i += 2;
        }
        ++i;
      }
      return length === j ? output : output.subarray(0, j);
    }
    function parseMIMEType(input) {
      input = removeHTTPWhitespace(input, true, true);
      const position = { position: 0 };
      const type = collectASequenceOfCodePointsFast(
        "/",
        input,
        position
      );
      if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {
        return "failure";
      }
      if (position.position >= input.length) {
        return "failure";
      }
      position.position++;
      let subtype = collectASequenceOfCodePointsFast(
        ";",
        input,
        position
      );
      subtype = removeHTTPWhitespace(subtype, false, true);
      if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {
        return "failure";
      }
      const typeLowercase = type.toLowerCase();
      const subtypeLowercase = subtype.toLowerCase();
      const mimeType = {
        type: typeLowercase,
        subtype: subtypeLowercase,
        /** @type {Map<string, string>} */
        parameters: /* @__PURE__ */ new Map(),
        // https://mimesniff.spec.whatwg.org/#mime-type-essence
        essence: `${typeLowercase}/${subtypeLowercase}`
      };
      while (position.position < input.length) {
        position.position++;
        collectASequenceOfCodePoints(
          // https://fetch.spec.whatwg.org/#http-whitespace
          (char) => HTTP_WHITESPACE_REGEX.test(char),
          input,
          position
        );
        let parameterName = collectASequenceOfCodePoints(
          (char) => char !== ";" && char !== "=",
          input,
          position
        );
        parameterName = parameterName.toLowerCase();
        if (position.position < input.length) {
          if (input[position.position] === ";") {
            continue;
          }
          position.position++;
        }
        if (position.position >= input.length) {
          break;
        }
        let parameterValue = null;
        if (input[position.position] === '"') {
          parameterValue = collectAnHTTPQuotedString(input, position, true);
          collectASequenceOfCodePointsFast(
            ";",
            input,
            position
          );
        } else {
          parameterValue = collectASequenceOfCodePointsFast(
            ";",
            input,
            position
          );
          parameterValue = removeHTTPWhitespace(parameterValue, false, true);
          if (parameterValue.length === 0) {
            continue;
          }
        }
        if (parameterName.length !== 0 && HTTP_TOKEN_CODEPOINTS.test(parameterName) && (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && !mimeType.parameters.has(parameterName)) {
          mimeType.parameters.set(parameterName, parameterValue);
        }
      }
      return mimeType;
    }
    function collectAnHTTPQuotedString(input, position, extractValue = false) {
      const positionStart = position.position;
      let value = "";
      assert8(input[position.position] === '"');
      position.position++;
      while (true) {
        value += collectASequenceOfCodePoints(
          (char) => char !== '"' && char !== "\\",
          input,
          position
        );
        if (position.position >= input.length) {
          break;
        }
        const quoteOrBackslash = input[position.position];
        position.position++;
        if (quoteOrBackslash === "\\") {
          if (position.position >= input.length) {
            value += "\\";
            break;
          }
          value += input[position.position];
          position.position++;
        } else {
          assert8(quoteOrBackslash === '"');
          break;
        }
      }
      if (extractValue) {
        return value;
      }
      return input.slice(positionStart, position.position);
    }
    function serializeAMimeType(mimeType) {
      assert8(mimeType !== "failure");
      const { parameters, essence } = mimeType;
      let serialization = essence;
      for (let [name, value] of parameters.entries()) {
        serialization += ";";
        serialization += name;
        serialization += "=";
        if (!HTTP_TOKEN_CODEPOINTS.test(value)) {
          value = value.replace(/[\\"]/ug, "\\$&");
          value = '"' + value;
          value += '"';
        }
        serialization += value;
      }
      return serialization;
    }
    function isHTTPWhiteSpace(char) {
      return char === 13 || char === 10 || char === 9 || char === 32;
    }
    function removeHTTPWhitespace(str, leading = true, trailing = true) {
      return removeChars(str, leading, trailing, isHTTPWhiteSpace);
    }
    function minimizeSupportedMimeType(mimeType) {
      switch (mimeType.essence) {
        case "application/ecmascript":
        case "application/javascript":
        case "application/x-ecmascript":
        case "application/x-javascript":
        case "text/ecmascript":
        case "text/javascript":
        case "text/javascript1.0":
        case "text/javascript1.1":
        case "text/javascript1.2":
        case "text/javascript1.3":
        case "text/javascript1.4":
        case "text/javascript1.5":
        case "text/jscript":
        case "text/livescript":
        case "text/x-ecmascript":
        case "text/x-javascript":
          return "text/javascript";
        case "application/json":
        case "text/json":
          return "application/json";
        case "image/svg+xml":
          return "image/svg+xml";
        case "text/xml":
        case "application/xml":
          return "application/xml";
      }
      if (mimeType.subtype.endsWith("+json")) {
        return "application/json";
      }
      if (mimeType.subtype.endsWith("+xml")) {
        return "application/xml";
      }
      return "";
    }
    module.exports = {
      dataURLProcessor,
      URLSerializer,
      stringPercentDecode,
      parseMIMEType,
      collectAnHTTPQuotedString,
      serializeAMimeType,
      removeHTTPWhitespace,
      minimizeSupportedMimeType,
      HTTP_TOKEN_CODEPOINTS
    };
  }
});

// node_modules/undici/lib/web/webidl/index.js
var require_webidl = __commonJS({
  "node_modules/undici/lib/web/webidl/index.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var { types, inspect } = __require("util");
    var { markAsUncloneable } = __require("worker_threads");
    var UNDEFINED = 1;
    var BOOLEAN = 2;
    var STRING = 3;
    var SYMBOL = 4;
    var NUMBER = 5;
    var BIGINT = 6;
    var NULL = 7;
    var OBJECT = 8;
    var FunctionPrototypeSymbolHasInstance = Function.call.bind(Function.prototype[Symbol.hasInstance]);
    var webidl = {
      converters: {},
      util: {},
      errors: {},
      is: {}
    };
    webidl.errors.exception = function(message) {
      return new TypeError(`${message.header}: ${message.message}`);
    };
    webidl.errors.conversionFailed = function(opts) {
      const plural = opts.types.length === 1 ? "" : " one of";
      const message = `${opts.argument} could not be converted to${plural}: ${opts.types.join(", ")}.`;
      return webidl.errors.exception({
        header: opts.prefix,
        message
      });
    };
    webidl.errors.invalidArgument = function(context) {
      return webidl.errors.exception({
        header: context.prefix,
        message: `"${context.value}" is an invalid ${context.type}.`
      });
    };
    webidl.brandCheck = function(V, I) {
      if (!FunctionPrototypeSymbolHasInstance(I, V)) {
        const err = new TypeError("Illegal invocation");
        err.code = "ERR_INVALID_THIS";
        throw err;
      }
    };
    webidl.brandCheckMultiple = function(List) {
      const prototypes = List.map((c) => webidl.util.MakeTypeAssertion(c));
      return (V) => {
        if (prototypes.every((typeCheck) => !typeCheck(V))) {
          const err = new TypeError("Illegal invocation");
          err.code = "ERR_INVALID_THIS";
          throw err;
        }
      };
    };
    webidl.argumentLengthCheck = function({ length }, min, ctx) {
      if (length < min) {
        throw webidl.errors.exception({
          message: `${min} argument${min !== 1 ? "s" : ""} required, but${length ? " only" : ""} ${length} found.`,
          header: ctx
        });
      }
    };
    webidl.illegalConstructor = function() {
      throw webidl.errors.exception({
        header: "TypeError",
        message: "Illegal constructor"
      });
    };
    webidl.util.MakeTypeAssertion = function(I) {
      return (O) => FunctionPrototypeSymbolHasInstance(I, O);
    };
    webidl.util.Type = function(V) {
      switch (typeof V) {
        case "undefined":
          return UNDEFINED;
        case "boolean":
          return BOOLEAN;
        case "string":
          return STRING;
        case "symbol":
          return SYMBOL;
        case "number":
          return NUMBER;
        case "bigint":
          return BIGINT;
        case "function":
        case "object": {
          if (V === null) {
            return NULL;
          }
          return OBJECT;
        }
      }
    };
    webidl.util.Types = {
      UNDEFINED,
      BOOLEAN,
      STRING,
      SYMBOL,
      NUMBER,
      BIGINT,
      NULL,
      OBJECT
    };
    webidl.util.TypeValueToString = function(o3) {
      switch (webidl.util.Type(o3)) {
        case UNDEFINED:
          return "Undefined";
        case BOOLEAN:
          return "Boolean";
        case STRING:
          return "String";
        case SYMBOL:
          return "Symbol";
        case NUMBER:
          return "Number";
        case BIGINT:
          return "BigInt";
        case NULL:
          return "Null";
        case OBJECT:
          return "Object";
      }
    };
    webidl.util.markAsUncloneable = markAsUncloneable;
    webidl.util.ConvertToInt = function(V, bitLength, signedness, flags) {
      let upperBound;
      let lowerBound;
      if (bitLength === 64) {
        upperBound = Math.pow(2, 53) - 1;
        if (signedness === "unsigned") {
          lowerBound = 0;
        } else {
          lowerBound = Math.pow(-2, 53) + 1;
        }
      } else if (signedness === "unsigned") {
        lowerBound = 0;
        upperBound = Math.pow(2, bitLength) - 1;
      } else {
        lowerBound = -Math.pow(2, bitLength - 1);
        upperBound = Math.pow(2, bitLength - 1) - 1;
      }
      let x = Number(V);
      if (x === 0) {
        x = 0;
      }
      if (webidl.util.HasFlag(flags, webidl.attributes.EnforceRange)) {
        if (Number.isNaN(x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY) {
          throw webidl.errors.exception({
            header: "Integer conversion",
            message: `Could not convert ${webidl.util.Stringify(V)} to an integer.`
          });
        }
        x = webidl.util.IntegerPart(x);
        if (x < lowerBound || x > upperBound) {
          throw webidl.errors.exception({
            header: "Integer conversion",
            message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`
          });
        }
        return x;
      }
      if (!Number.isNaN(x) && webidl.util.HasFlag(flags, webidl.attributes.Clamp)) {
        x = Math.min(Math.max(x, lowerBound), upperBound);
        if (Math.floor(x) % 2 === 0) {
          x = Math.floor(x);
        } else {
          x = Math.ceil(x);
        }
        return x;
      }
      if (Number.isNaN(x) || x === 0 && Object.is(0, x) || x === Number.POSITIVE_INFINITY || x === Number.NEGATIVE_INFINITY) {
        return 0;
      }
      x = webidl.util.IntegerPart(x);
      x = x % Math.pow(2, bitLength);
      if (signedness === "signed" && x >= Math.pow(2, bitLength - 1)) {
        return x - Math.pow(2, bitLength);
      }
      return x;
    };
    webidl.util.IntegerPart = function(n) {
      const r = Math.floor(Math.abs(n));
      if (n < 0) {
        return -1 * r;
      }
      return r;
    };
    webidl.util.Stringify = function(V) {
      const type = webidl.util.Type(V);
      switch (type) {
        case SYMBOL:
          return `Symbol(${V.description})`;
        case OBJECT:
          return inspect(V);
        case STRING:
          return `"${V}"`;
        case BIGINT:
          return `${V}n`;
        default:
          return `${V}`;
      }
    };
    webidl.util.IsResizableArrayBuffer = function(V) {
      if (types.isArrayBuffer(V)) {
        return V.resizable;
      }
      if (types.isSharedArrayBuffer(V)) {
        return V.growable;
      }
      throw webidl.errors.exception({
        header: "IsResizableArrayBuffer",
        message: `"${webidl.util.Stringify(V)}" is not an array buffer.`
      });
    };
    webidl.util.HasFlag = function(flags, attributes) {
      return typeof flags === "number" && (flags & attributes) === attributes;
    };
    webidl.sequenceConverter = function(converter) {
      return (V, prefix, argument, Iterable) => {
        if (webidl.util.Type(V) !== OBJECT) {
          throw webidl.errors.exception({
            header: prefix,
            message: `${argument} (${webidl.util.Stringify(V)}) is not iterable.`
          });
        }
        const method = typeof Iterable === "function" ? Iterable() : V?.[Symbol.iterator]?.();
        const seq = [];
        let index2 = 0;
        if (method === void 0 || typeof method.next !== "function") {
          throw webidl.errors.exception({
            header: prefix,
            message: `${argument} is not iterable.`
          });
        }
        while (true) {
          const { done, value } = method.next();
          if (done) {
            break;
          }
          seq.push(converter(value, prefix, `${argument}[${index2++}]`));
        }
        return seq;
      };
    };
    webidl.recordConverter = function(keyConverter, valueConverter) {
      return (O, prefix, argument) => {
        if (webidl.util.Type(O) !== OBJECT) {
          throw webidl.errors.exception({
            header: prefix,
            message: `${argument} ("${webidl.util.TypeValueToString(O)}") is not an Object.`
          });
        }
        const result = {};
        if (!types.isProxy(O)) {
          const keys2 = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)];
          for (const key of keys2) {
            const keyName = webidl.util.Stringify(key);
            const typedKey = keyConverter(key, prefix, `Key ${keyName} in ${argument}`);
            const typedValue = valueConverter(O[key], prefix, `${argument}[${keyName}]`);
            result[typedKey] = typedValue;
          }
          return result;
        }
        const keys = Reflect.ownKeys(O);
        for (const key of keys) {
          const desc = Reflect.getOwnPropertyDescriptor(O, key);
          if (desc?.enumerable) {
            const typedKey = keyConverter(key, prefix, argument);
            const typedValue = valueConverter(O[key], prefix, argument);
            result[typedKey] = typedValue;
          }
        }
        return result;
      };
    };
    webidl.interfaceConverter = function(TypeCheck, name) {
      return (V, prefix, argument) => {
        if (!TypeCheck(V)) {
          throw webidl.errors.exception({
            header: prefix,
            message: `Expected ${argument} ("${webidl.util.Stringify(V)}") to be an instance of ${name}.`
          });
        }
        return V;
      };
    };
    webidl.dictionaryConverter = function(converters) {
      converters.sort((a, b) => (a.key > b.key) - (a.key < b.key));
      return (dictionary, prefix, argument) => {
        const dict = {};
        if (dictionary != null && webidl.util.Type(dictionary) !== OBJECT) {
          throw webidl.errors.exception({
            header: prefix,
            message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
          });
        }
        for (const options of converters) {
          const { key, defaultValue, required, converter } = options;
          if (required === true) {
            if (dictionary == null || !Object.hasOwn(dictionary, key)) {
              throw webidl.errors.exception({
                header: prefix,
                message: `Missing required key "${key}".`
              });
            }
          }
          let value = dictionary?.[key];
          const hasDefault = defaultValue !== void 0;
          if (hasDefault && value === void 0) {
            value = defaultValue();
          }
          if (required || hasDefault || value !== void 0) {
            value = converter(value, prefix, `${argument}.${key}`);
            if (options.allowedValues && !options.allowedValues.includes(value)) {
              throw webidl.errors.exception({
                header: prefix,
                message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(", ")}.`
              });
            }
            dict[key] = value;
          }
        }
        return dict;
      };
    };
    webidl.nullableConverter = function(converter) {
      return (V, prefix, argument) => {
        if (V === null) {
          return V;
        }
        return converter(V, prefix, argument);
      };
    };
    webidl.is.USVString = function(value) {
      return typeof value === "string" && value.isWellFormed();
    };
    webidl.is.ReadableStream = webidl.util.MakeTypeAssertion(ReadableStream);
    webidl.is.Blob = webidl.util.MakeTypeAssertion(Blob);
    webidl.is.URLSearchParams = webidl.util.MakeTypeAssertion(URLSearchParams);
    webidl.is.File = webidl.util.MakeTypeAssertion(File);
    webidl.is.URL = webidl.util.MakeTypeAssertion(URL);
    webidl.is.AbortSignal = webidl.util.MakeTypeAssertion(AbortSignal);
    webidl.is.MessagePort = webidl.util.MakeTypeAssertion(MessagePort);
    webidl.is.BufferSource = function(V) {
      return types.isArrayBuffer(V) || ArrayBuffer.isView(V) && types.isArrayBuffer(V.buffer);
    };
    webidl.util.getCopyOfBytesHeldByBufferSource = function(bufferSource) {
      const jsBufferSource = bufferSource;
      let jsArrayBuffer = jsBufferSource;
      let offset = 0;
      let length = 0;
      if (types.isTypedArray(jsBufferSource) || types.isDataView(jsBufferSource)) {
        jsArrayBuffer = jsBufferSource.buffer;
        offset = jsBufferSource.byteOffset;
        length = jsBufferSource.byteLength;
      } else {
        assert8(types.isAnyArrayBuffer(jsBufferSource));
        length = jsBufferSource.byteLength;
      }
      if (jsArrayBuffer.detached) {
        return new Uint8Array(0);
      }
      const bytes = new Uint8Array(length);
      const view = new Uint8Array(jsArrayBuffer, offset, length);
      bytes.set(view);
      return bytes;
    };
    webidl.converters.DOMString = function(V, prefix, argument, flags) {
      if (V === null && webidl.util.HasFlag(flags, webidl.attributes.LegacyNullToEmptyString)) {
        return "";
      }
      if (typeof V === "symbol") {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} is a symbol, which cannot be converted to a DOMString.`
        });
      }
      return String(V);
    };
    webidl.converters.ByteString = function(V, prefix, argument) {
      if (typeof V === "symbol") {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} is a symbol, which cannot be converted to a ByteString.`
        });
      }
      const x = String(V);
      for (let index2 = 0; index2 < x.length; index2++) {
        if (x.charCodeAt(index2) > 255) {
          throw new TypeError(
            `Cannot convert argument to a ByteString because the character at index ${index2} has a value of ${x.charCodeAt(index2)} which is greater than 255.`
          );
        }
      }
      return x;
    };
    webidl.converters.USVString = function(value) {
      if (typeof value === "string") {
        return value.toWellFormed();
      }
      return `${value}`.toWellFormed();
    };
    webidl.converters.boolean = function(V) {
      const x = Boolean(V);
      return x;
    };
    webidl.converters.any = function(V) {
      return V;
    };
    webidl.converters["long long"] = function(V, prefix, argument) {
      const x = webidl.util.ConvertToInt(V, 64, "signed", 0, prefix, argument);
      return x;
    };
    webidl.converters["unsigned long long"] = function(V, prefix, argument) {
      const x = webidl.util.ConvertToInt(V, 64, "unsigned", 0, prefix, argument);
      return x;
    };
    webidl.converters["unsigned long"] = function(V, prefix, argument) {
      const x = webidl.util.ConvertToInt(V, 32, "unsigned", 0, prefix, argument);
      return x;
    };
    webidl.converters["unsigned short"] = function(V, prefix, argument, flags) {
      const x = webidl.util.ConvertToInt(V, 16, "unsigned", flags, prefix, argument);
      return x;
    };
    webidl.converters.ArrayBuffer = function(V, prefix, argument, flags) {
      if (webidl.util.Type(V) !== OBJECT || !types.isArrayBuffer(V)) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${argument} ("${webidl.util.Stringify(V)}")`,
          types: ["ArrayBuffer"]
        });
      }
      if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a resizable ArrayBuffer.`
        });
      }
      return V;
    };
    webidl.converters.SharedArrayBuffer = function(V, prefix, argument, flags) {
      if (webidl.util.Type(V) !== OBJECT || !types.isSharedArrayBuffer(V)) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${argument} ("${webidl.util.Stringify(V)}")`,
          types: ["SharedArrayBuffer"]
        });
      }
      if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a resizable SharedArrayBuffer.`
        });
      }
      return V;
    };
    webidl.converters.TypedArray = function(V, T, prefix, argument, flags) {
      if (webidl.util.Type(V) !== OBJECT || !types.isTypedArray(V) || V.constructor.name !== T.name) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${argument} ("${webidl.util.Stringify(V)}")`,
          types: [T.name]
        });
      }
      if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types.isSharedArrayBuffer(V.buffer)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a view on a shared array buffer.`
        });
      }
      if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a view on a resizable array buffer.`
        });
      }
      return V;
    };
    webidl.converters.DataView = function(V, prefix, argument, flags) {
      if (webidl.util.Type(V) !== OBJECT || !types.isDataView(V)) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${argument} ("${webidl.util.Stringify(V)}")`,
          types: ["DataView"]
        });
      }
      if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types.isSharedArrayBuffer(V.buffer)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a view on a shared array buffer.`
        });
      }
      if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a view on a resizable array buffer.`
        });
      }
      return V;
    };
    webidl.converters.ArrayBufferView = function(V, prefix, argument, flags) {
      if (webidl.util.Type(V) !== OBJECT || !types.isArrayBufferView(V)) {
        throw webidl.errors.conversionFailed({
          prefix,
          argument: `${argument} ("${webidl.util.Stringify(V)}")`,
          types: ["ArrayBufferView"]
        });
      }
      if (!webidl.util.HasFlag(flags, webidl.attributes.AllowShared) && types.isSharedArrayBuffer(V.buffer)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a view on a shared array buffer.`
        });
      }
      if (!webidl.util.HasFlag(flags, webidl.attributes.AllowResizable) && webidl.util.IsResizableArrayBuffer(V.buffer)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a view on a resizable array buffer.`
        });
      }
      return V;
    };
    webidl.converters.BufferSource = function(V, prefix, argument, flags) {
      if (types.isArrayBuffer(V)) {
        return webidl.converters.ArrayBuffer(V, prefix, argument, flags);
      }
      if (types.isArrayBufferView(V)) {
        flags &= ~webidl.attributes.AllowShared;
        return webidl.converters.ArrayBufferView(V, prefix, argument, flags);
      }
      if (types.isSharedArrayBuffer(V)) {
        throw webidl.errors.exception({
          header: prefix,
          message: `${argument} cannot be a SharedArrayBuffer.`
        });
      }
      throw webidl.errors.conversionFailed({
        prefix,
        argument: `${argument} ("${webidl.util.Stringify(V)}")`,
        types: ["ArrayBuffer", "ArrayBufferView"]
      });
    };
    webidl.converters.AllowSharedBufferSource = function(V, prefix, argument, flags) {
      if (types.isArrayBuffer(V)) {
        return webidl.converters.ArrayBuffer(V, prefix, argument, flags);
      }
      if (types.isSharedArrayBuffer(V)) {
        return webidl.converters.SharedArrayBuffer(V, prefix, argument, flags);
      }
      if (types.isArrayBufferView(V)) {
        flags |= webidl.attributes.AllowShared;
        return webidl.converters.ArrayBufferView(V, prefix, argument, flags);
      }
      throw webidl.errors.conversionFailed({
        prefix,
        argument: `${argument} ("${webidl.util.Stringify(V)}")`,
        types: ["ArrayBuffer", "SharedArrayBuffer", "ArrayBufferView"]
      });
    };
    webidl.converters["sequence<ByteString>"] = webidl.sequenceConverter(
      webidl.converters.ByteString
    );
    webidl.converters["sequence<sequence<ByteString>>"] = webidl.sequenceConverter(
      webidl.converters["sequence<ByteString>"]
    );
    webidl.converters["record<ByteString, ByteString>"] = webidl.recordConverter(
      webidl.converters.ByteString,
      webidl.converters.ByteString
    );
    webidl.converters.Blob = webidl.interfaceConverter(webidl.is.Blob, "Blob");
    webidl.converters.AbortSignal = webidl.interfaceConverter(
      webidl.is.AbortSignal,
      "AbortSignal"
    );
    webidl.converters.EventHandlerNonNull = function(V) {
      if (webidl.util.Type(V) !== OBJECT) {
        return null;
      }
      if (typeof V === "function") {
        return V;
      }
      return () => {
      };
    };
    webidl.attributes = {
      Clamp: 1 << 0,
      EnforceRange: 1 << 1,
      AllowShared: 1 << 2,
      AllowResizable: 1 << 3,
      LegacyNullToEmptyString: 1 << 4
    };
    module.exports = {
      webidl
    };
  }
});

// node_modules/undici/lib/web/fetch/util.js
var require_util2 = __commonJS({
  "node_modules/undici/lib/web/fetch/util.js"(exports, module) {
    "use strict";
    var { Transform } = __require("stream");
    var zlib = __require("zlib");
    var { redirectStatusSet, referrerPolicyTokens, badPortsSet } = require_constants4();
    var { getGlobalOrigin } = require_global();
    var { collectAnHTTPQuotedString, parseMIMEType } = require_data_url();
    var { performance: performance2 } = __require("perf_hooks");
    var { ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = require_util();
    var assert8 = __require("assert");
    var { isUint8Array } = __require("util/types");
    var { webidl } = require_webidl();
    var { isomorphicEncode, collectASequenceOfCodePoints, removeChars } = require_infra();
    function responseURL(response) {
      const urlList = response.urlList;
      const length = urlList.length;
      return length === 0 ? null : urlList[length - 1].toString();
    }
    function responseLocationURL(response, requestFragment) {
      if (!redirectStatusSet.has(response.status)) {
        return null;
      }
      let location = response.headersList.get("location", true);
      if (location !== null && isValidHeaderValue(location)) {
        if (!isValidEncodedURL(location)) {
          location = normalizeBinaryStringToUtf8(location);
        }
        location = new URL(location, responseURL(response));
      }
      if (location && !location.hash) {
        location.hash = requestFragment;
      }
      return location;
    }
    function isValidEncodedURL(url) {
      for (let i = 0; i < url.length; ++i) {
        const code = url.charCodeAt(i);
        if (code > 126 || // Non-US-ASCII + DEL
        code < 32) {
          return false;
        }
      }
      return true;
    }
    function normalizeBinaryStringToUtf8(value) {
      return Buffer.from(value, "binary").toString("utf8");
    }
    function requestCurrentURL(request) {
      return request.urlList[request.urlList.length - 1];
    }
    function requestBadPort(request) {
      const url = requestCurrentURL(request);
      if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) {
        return "blocked";
      }
      return "allowed";
    }
    function isErrorLike(object) {
      return object instanceof Error || (object?.constructor?.name === "Error" || object?.constructor?.name === "DOMException");
    }
    function isValidReasonPhrase(statusText) {
      for (let i = 0; i < statusText.length; ++i) {
        const c = statusText.charCodeAt(i);
        if (!(c === 9 || // HTAB
        c >= 32 && c <= 126 || // SP / VCHAR
        c >= 128 && c <= 255)) {
          return false;
        }
      }
      return true;
    }
    var isValidHeaderName = isValidHTTPToken;
    function isValidHeaderValue(potentialValue) {
      return (potentialValue[0] === "	" || potentialValue[0] === " " || potentialValue[potentialValue.length - 1] === "	" || potentialValue[potentialValue.length - 1] === " " || potentialValue.includes("\n") || potentialValue.includes("\r") || potentialValue.includes("\0")) === false;
    }
    function parseReferrerPolicy(actualResponse) {
      const policyHeader = (actualResponse.headersList.get("referrer-policy", true) ?? "").split(",");
      let policy = "";
      if (policyHeader.length) {
        for (let i = policyHeader.length; i !== 0; i--) {
          const token = policyHeader[i - 1].trim();
          if (referrerPolicyTokens.has(token)) {
            policy = token;
            break;
          }
        }
      }
      return policy;
    }
    function setRequestReferrerPolicyOnRedirect(request, actualResponse) {
      const policy = parseReferrerPolicy(actualResponse);
      if (policy !== "") {
        request.referrerPolicy = policy;
      }
    }
    function crossOriginResourcePolicyCheck() {
      return "allowed";
    }
    function corsCheck() {
      return "success";
    }
    function TAOCheck() {
      return "success";
    }
    function appendFetchMetadata(httpRequest) {
      let header = null;
      header = httpRequest.mode;
      httpRequest.headersList.set("sec-fetch-mode", header, true);
    }
    function appendRequestOriginHeader(request) {
      let serializedOrigin = request.origin;
      if (serializedOrigin === "client" || serializedOrigin === void 0) {
        return;
      }
      if (request.responseTainting === "cors" || request.mode === "websocket") {
        request.headersList.append("origin", serializedOrigin, true);
      } else if (request.method !== "GET" && request.method !== "HEAD") {
        switch (request.referrerPolicy) {
          case "no-referrer":
            serializedOrigin = null;
            break;
          case "no-referrer-when-downgrade":
          case "strict-origin":
          case "strict-origin-when-cross-origin":
            if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {
              serializedOrigin = null;
            }
            break;
          case "same-origin":
            if (!sameOrigin(request, requestCurrentURL(request))) {
              serializedOrigin = null;
            }
            break;
          default:
        }
        request.headersList.append("origin", serializedOrigin, true);
      }
    }
    function coarsenTime(timestamp, crossOriginIsolatedCapability) {
      return timestamp;
    }
    function clampAndCoarsenConnectionTimingInfo(connectionTimingInfo, defaultStartTime, crossOriginIsolatedCapability) {
      if (!connectionTimingInfo?.startTime || connectionTimingInfo.startTime < defaultStartTime) {
        return {
          domainLookupStartTime: defaultStartTime,
          domainLookupEndTime: defaultStartTime,
          connectionStartTime: defaultStartTime,
          connectionEndTime: defaultStartTime,
          secureConnectionStartTime: defaultStartTime,
          ALPNNegotiatedProtocol: connectionTimingInfo?.ALPNNegotiatedProtocol
        };
      }
      return {
        domainLookupStartTime: coarsenTime(connectionTimingInfo.domainLookupStartTime, crossOriginIsolatedCapability),
        domainLookupEndTime: coarsenTime(connectionTimingInfo.domainLookupEndTime, crossOriginIsolatedCapability),
        connectionStartTime: coarsenTime(connectionTimingInfo.connectionStartTime, crossOriginIsolatedCapability),
        connectionEndTime: coarsenTime(connectionTimingInfo.connectionEndTime, crossOriginIsolatedCapability),
        secureConnectionStartTime: coarsenTime(connectionTimingInfo.secureConnectionStartTime, crossOriginIsolatedCapability),
        ALPNNegotiatedProtocol: connectionTimingInfo.ALPNNegotiatedProtocol
      };
    }
    function coarsenedSharedCurrentTime(crossOriginIsolatedCapability) {
      return coarsenTime(performance2.now(), crossOriginIsolatedCapability);
    }
    function createOpaqueTimingInfo(timingInfo) {
      return {
        startTime: timingInfo.startTime ?? 0,
        redirectStartTime: 0,
        redirectEndTime: 0,
        postRedirectStartTime: timingInfo.startTime ?? 0,
        finalServiceWorkerStartTime: 0,
        finalNetworkResponseStartTime: 0,
        finalNetworkRequestStartTime: 0,
        endTime: 0,
        encodedBodySize: 0,
        decodedBodySize: 0,
        finalConnectionTimingInfo: null
      };
    }
    function makePolicyContainer() {
      return {
        referrerPolicy: "strict-origin-when-cross-origin"
      };
    }
    function clonePolicyContainer(policyContainer) {
      return {
        referrerPolicy: policyContainer.referrerPolicy
      };
    }
    function determineRequestsReferrer(request) {
      const policy = request.referrerPolicy;
      assert8(policy);
      let referrerSource = null;
      if (request.referrer === "client") {
        const globalOrigin = getGlobalOrigin();
        if (!globalOrigin || globalOrigin.origin === "null") {
          return "no-referrer";
        }
        referrerSource = new URL(globalOrigin);
      } else if (webidl.is.URL(request.referrer)) {
        referrerSource = request.referrer;
      }
      let referrerURL = stripURLForReferrer(referrerSource);
      const referrerOrigin = stripURLForReferrer(referrerSource, true);
      if (referrerURL.toString().length > 4096) {
        referrerURL = referrerOrigin;
      }
      switch (policy) {
        case "no-referrer":
          return "no-referrer";
        case "origin":
          if (referrerOrigin != null) {
            return referrerOrigin;
          }
          return stripURLForReferrer(referrerSource, true);
        case "unsafe-url":
          return referrerURL;
        case "strict-origin": {
          const currentURL = requestCurrentURL(request);
          if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
            return "no-referrer";
          }
          return referrerOrigin;
        }
        case "strict-origin-when-cross-origin": {
          const currentURL = requestCurrentURL(request);
          if (sameOrigin(referrerURL, currentURL)) {
            return referrerURL;
          }
          if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
            return "no-referrer";
          }
          return referrerOrigin;
        }
        case "same-origin":
          if (sameOrigin(request, referrerURL)) {
            return referrerURL;
          }
          return "no-referrer";
        case "origin-when-cross-origin":
          if (sameOrigin(request, referrerURL)) {
            return referrerURL;
          }
          return referrerOrigin;
        case "no-referrer-when-downgrade": {
          const currentURL = requestCurrentURL(request);
          if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
            return "no-referrer";
          }
          return referrerURL;
        }
      }
    }
    function stripURLForReferrer(url, originOnly = false) {
      assert8(webidl.is.URL(url));
      url = new URL(url);
      if (urlIsLocal(url)) {
        return "no-referrer";
      }
      url.username = "";
      url.password = "";
      url.hash = "";
      if (originOnly === true) {
        url.pathname = "";
        url.search = "";
      }
      return url;
    }
    var isPotentialleTrustworthyIPv4 = RegExp.prototype.test.bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/);
    var isPotentiallyTrustworthyIPv6 = RegExp.prototype.test.bind(/^(?:(?:0{1,4}:){7}|(?:0{1,4}:){1,6}:|::)0{0,3}1$/);
    function isOriginIPPotentiallyTrustworthy(origin) {
      if (origin.includes(":")) {
        if (origin[0] === "[" && origin[origin.length - 1] === "]") {
          origin = origin.slice(1, -1);
        }
        return isPotentiallyTrustworthyIPv6(origin);
      }
      return isPotentialleTrustworthyIPv4(origin);
    }
    function isOriginPotentiallyTrustworthy(origin) {
      if (origin == null || origin === "null") {
        return false;
      }
      origin = new URL(origin);
      if (origin.protocol === "https:" || origin.protocol === "wss:") {
        return true;
      }
      if (isOriginIPPotentiallyTrustworthy(origin.hostname)) {
        return true;
      }
      if (origin.hostname === "localhost" || origin.hostname === "localhost.") {
        return true;
      }
      if (origin.hostname.endsWith(".localhost") || origin.hostname.endsWith(".localhost.")) {
        return true;
      }
      if (origin.protocol === "file:") {
        return true;
      }
      return false;
    }
    function isURLPotentiallyTrustworthy(url) {
      if (!webidl.is.URL(url)) {
        return false;
      }
      if (url.href === "about:blank" || url.href === "about:srcdoc") {
        return true;
      }
      if (url.protocol === "data:") return true;
      if (url.protocol === "blob:") return true;
      return isOriginPotentiallyTrustworthy(url.origin);
    }
    function tryUpgradeRequestToAPotentiallyTrustworthyURL(request) {
    }
    function sameOrigin(A, B) {
      if (A.origin === B.origin && A.origin === "null") {
        return true;
      }
      if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {
        return true;
      }
      return false;
    }
    function isAborted2(fetchParams) {
      return fetchParams.controller.state === "aborted";
    }
    function isCancelled(fetchParams) {
      return fetchParams.controller.state === "aborted" || fetchParams.controller.state === "terminated";
    }
    function normalizeMethod(method) {
      return normalizedMethodRecordsBase[method.toLowerCase()] ?? method;
    }
    var esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
    function createIterator(name, kInternalIterator, keyIndex = 0, valueIndex = 1) {
      class FastIterableIterator {
        /** @type {any} */
        #target;
        /** @type {'key' | 'value' | 'key+value'} */
        #kind;
        /** @type {number} */
        #index;
        /**
         * @see https://webidl.spec.whatwg.org/#dfn-default-iterator-object
         * @param {unknown} target
         * @param {'key' | 'value' | 'key+value'} kind
         */
        constructor(target, kind) {
          this.#target = target;
          this.#kind = kind;
          this.#index = 0;
        }
        next() {
          if (typeof this !== "object" || this === null || !(#target in this)) {
            throw new TypeError(
              `'next' called on an object that does not implement interface ${name} Iterator.`
            );
          }
          const index2 = this.#index;
          const values = kInternalIterator(this.#target);
          const len = values.length;
          if (index2 >= len) {
            return {
              value: void 0,
              done: true
            };
          }
          const { [keyIndex]: key, [valueIndex]: value } = values[index2];
          this.#index = index2 + 1;
          let result;
          switch (this.#kind) {
            case "key":
              result = key;
              break;
            case "value":
              result = value;
              break;
            case "key+value":
              result = [key, value];
              break;
          }
          return {
            value: result,
            done: false
          };
        }
      }
      delete FastIterableIterator.prototype.constructor;
      Object.setPrototypeOf(FastIterableIterator.prototype, esIteratorPrototype);
      Object.defineProperties(FastIterableIterator.prototype, {
        [Symbol.toStringTag]: {
          writable: false,
          enumerable: false,
          configurable: true,
          value: `${name} Iterator`
        },
        next: { writable: true, enumerable: true, configurable: true }
      });
      return function(target, kind) {
        return new FastIterableIterator(target, kind);
      };
    }
    function iteratorMixin(name, object, kInternalIterator, keyIndex = 0, valueIndex = 1) {
      const makeIterator = createIterator(name, kInternalIterator, keyIndex, valueIndex);
      const properties = {
        keys: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: function keys() {
            webidl.brandCheck(this, object);
            return makeIterator(this, "key");
          }
        },
        values: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: function values() {
            webidl.brandCheck(this, object);
            return makeIterator(this, "value");
          }
        },
        entries: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: function entries() {
            webidl.brandCheck(this, object);
            return makeIterator(this, "key+value");
          }
        },
        forEach: {
          writable: true,
          enumerable: true,
          configurable: true,
          value: function forEach(callbackfn, thisArg = globalThis) {
            webidl.brandCheck(this, object);
            webidl.argumentLengthCheck(arguments, 1, `${name}.forEach`);
            if (typeof callbackfn !== "function") {
              throw new TypeError(
                `Failed to execute 'forEach' on '${name}': parameter 1 is not of type 'Function'.`
              );
            }
            for (const { 0: key, 1: value } of makeIterator(this, "key+value")) {
              callbackfn.call(thisArg, value, key, this);
            }
          }
        }
      };
      return Object.defineProperties(object.prototype, {
        ...properties,
        [Symbol.iterator]: {
          writable: true,
          enumerable: false,
          configurable: true,
          value: properties.entries.value
        }
      });
    }
    function fullyReadBody(body, processBody, processBodyError) {
      const successSteps = processBody;
      const errorSteps = processBodyError;
      try {
        const reader = body.stream.getReader();
        readAllBytes(reader, successSteps, errorSteps);
      } catch (e7) {
        errorSteps(e7);
      }
    }
    function readableStreamClose(controller) {
      try {
        controller.close();
        controller.byobRequest?.respond(0);
      } catch (err) {
        if (!err.message.includes("Controller is already closed") && !err.message.includes("ReadableStream is already closed")) {
          throw err;
        }
      }
    }
    async function readAllBytes(reader, successSteps, failureSteps) {
      try {
        const bytes = [];
        let byteLength = 0;
        do {
          const { done, value: chunk } = await reader.read();
          if (done) {
            successSteps(Buffer.concat(bytes, byteLength));
            return;
          }
          if (!isUint8Array(chunk)) {
            failureSteps(new TypeError("Received non-Uint8Array chunk"));
            return;
          }
          bytes.push(chunk);
          byteLength += chunk.length;
        } while (true);
      } catch (e7) {
        failureSteps(e7);
      }
    }
    function urlIsLocal(url) {
      assert8("protocol" in url);
      const protocol = url.protocol;
      return protocol === "about:" || protocol === "blob:" || protocol === "data:";
    }
    function urlHasHttpsScheme(url) {
      return typeof url === "string" && url[5] === ":" && url[0] === "h" && url[1] === "t" && url[2] === "t" && url[3] === "p" && url[4] === "s" || url.protocol === "https:";
    }
    function urlIsHttpHttpsScheme(url) {
      assert8("protocol" in url);
      const protocol = url.protocol;
      return protocol === "http:" || protocol === "https:";
    }
    function simpleRangeHeaderValue(value, allowWhitespace) {
      const data = value;
      if (!data.startsWith("bytes")) {
        return "failure";
      }
      const position = { position: 5 };
      if (allowWhitespace) {
        collectASequenceOfCodePoints(
          (char) => char === "	" || char === " ",
          data,
          position
        );
      }
      if (data.charCodeAt(position.position) !== 61) {
        return "failure";
      }
      position.position++;
      if (allowWhitespace) {
        collectASequenceOfCodePoints(
          (char) => char === "	" || char === " ",
          data,
          position
        );
      }
      const rangeStart = collectASequenceOfCodePoints(
        (char) => {
          const code = char.charCodeAt(0);
          return code >= 48 && code <= 57;
        },
        data,
        position
      );
      const rangeStartValue = rangeStart.length ? Number(rangeStart) : null;
      if (allowWhitespace) {
        collectASequenceOfCodePoints(
          (char) => char === "	" || char === " ",
          data,
          position
        );
      }
      if (data.charCodeAt(position.position) !== 45) {
        return "failure";
      }
      position.position++;
      if (allowWhitespace) {
        collectASequenceOfCodePoints(
          (char) => char === "	" || char === " ",
          data,
          position
        );
      }
      const rangeEnd = collectASequenceOfCodePoints(
        (char) => {
          const code = char.charCodeAt(0);
          return code >= 48 && code <= 57;
        },
        data,
        position
      );
      const rangeEndValue = rangeEnd.length ? Number(rangeEnd) : null;
      if (position.position < data.length) {
        return "failure";
      }
      if (rangeEndValue === null && rangeStartValue === null) {
        return "failure";
      }
      if (rangeStartValue > rangeEndValue) {
        return "failure";
      }
      return { rangeStartValue, rangeEndValue };
    }
    function buildContentRange(rangeStart, rangeEnd, fullLength) {
      let contentRange = "bytes ";
      contentRange += isomorphicEncode(`${rangeStart}`);
      contentRange += "-";
      contentRange += isomorphicEncode(`${rangeEnd}`);
      contentRange += "/";
      contentRange += isomorphicEncode(`${fullLength}`);
      return contentRange;
    }
    var InflateStream = class extends Transform {
      #zlibOptions;
      /** @param {zlib.ZlibOptions} [zlibOptions] */
      constructor(zlibOptions) {
        super();
        this.#zlibOptions = zlibOptions;
      }
      _transform(chunk, encoding, callback) {
        if (!this._inflateStream) {
          if (chunk.length === 0) {
            callback();
            return;
          }
          this._inflateStream = (chunk[0] & 15) === 8 ? zlib.createInflate(this.#zlibOptions) : zlib.createInflateRaw(this.#zlibOptions);
          this._inflateStream.on("data", this.push.bind(this));
          this._inflateStream.on("end", () => this.push(null));
          this._inflateStream.on("error", (err) => this.destroy(err));
        }
        this._inflateStream.write(chunk, encoding, callback);
      }
      _final(callback) {
        if (this._inflateStream) {
          this._inflateStream.end();
          this._inflateStream = null;
        }
        callback();
      }
    };
    function createInflate(zlibOptions) {
      return new InflateStream(zlibOptions);
    }
    function extractMimeType(headers) {
      let charset = null;
      let essence = null;
      let mimeType = null;
      const values = getDecodeSplit("content-type", headers);
      if (values === null) {
        return "failure";
      }
      for (const value of values) {
        const temporaryMimeType = parseMIMEType(value);
        if (temporaryMimeType === "failure" || temporaryMimeType.essence === "*/*") {
          continue;
        }
        mimeType = temporaryMimeType;
        if (mimeType.essence !== essence) {
          charset = null;
          if (mimeType.parameters.has("charset")) {
            charset = mimeType.parameters.get("charset");
          }
          essence = mimeType.essence;
        } else if (!mimeType.parameters.has("charset") && charset !== null) {
          mimeType.parameters.set("charset", charset);
        }
      }
      if (mimeType == null) {
        return "failure";
      }
      return mimeType;
    }
    function gettingDecodingSplitting(value) {
      const input = value;
      const position = { position: 0 };
      const values = [];
      let temporaryValue = "";
      while (position.position < input.length) {
        temporaryValue += collectASequenceOfCodePoints(
          (char) => char !== '"' && char !== ",",
          input,
          position
        );
        if (position.position < input.length) {
          if (input.charCodeAt(position.position) === 34) {
            temporaryValue += collectAnHTTPQuotedString(
              input,
              position
            );
            if (position.position < input.length) {
              continue;
            }
          } else {
            assert8(input.charCodeAt(position.position) === 44);
            position.position++;
          }
        }
        temporaryValue = removeChars(temporaryValue, true, true, (char) => char === 9 || char === 32);
        values.push(temporaryValue);
        temporaryValue = "";
      }
      return values;
    }
    function getDecodeSplit(name, list) {
      const value = list.get(name, true);
      if (value === null) {
        return null;
      }
      return gettingDecodingSplitting(value);
    }
    function hasAuthenticationEntry(request) {
      return false;
    }
    function includesCredentials(url) {
      return !!(url.username || url.password);
    }
    function isTraversableNavigable(navigable) {
      return navigable != null && navigable !== "client" && navigable !== "no-traversable";
    }
    var EnvironmentSettingsObjectBase = class {
      get baseUrl() {
        return getGlobalOrigin();
      }
      get origin() {
        return this.baseUrl?.origin;
      }
      policyContainer = makePolicyContainer();
    };
    var EnvironmentSettingsObject = class {
      settingsObject = new EnvironmentSettingsObjectBase();
    };
    var environmentSettingsObject = new EnvironmentSettingsObject();
    module.exports = {
      isAborted: isAborted2,
      isCancelled,
      isValidEncodedURL,
      ReadableStreamFrom,
      tryUpgradeRequestToAPotentiallyTrustworthyURL,
      clampAndCoarsenConnectionTimingInfo,
      coarsenedSharedCurrentTime,
      determineRequestsReferrer,
      makePolicyContainer,
      clonePolicyContainer,
      appendFetchMetadata,
      appendRequestOriginHeader,
      TAOCheck,
      corsCheck,
      crossOriginResourcePolicyCheck,
      createOpaqueTimingInfo,
      setRequestReferrerPolicyOnRedirect,
      isValidHTTPToken,
      requestBadPort,
      requestCurrentURL,
      responseURL,
      responseLocationURL,
      isURLPotentiallyTrustworthy,
      isValidReasonPhrase,
      sameOrigin,
      normalizeMethod,
      iteratorMixin,
      createIterator,
      isValidHeaderName,
      isValidHeaderValue,
      isErrorLike,
      fullyReadBody,
      readableStreamClose,
      urlIsLocal,
      urlHasHttpsScheme,
      urlIsHttpHttpsScheme,
      readAllBytes,
      simpleRangeHeaderValue,
      buildContentRange,
      createInflate,
      extractMimeType,
      getDecodeSplit,
      environmentSettingsObject,
      isOriginIPPotentiallyTrustworthy,
      hasAuthenticationEntry,
      includesCredentials,
      isTraversableNavigable
    };
  }
});

// node_modules/undici/lib/web/fetch/formdata.js
var require_formdata = __commonJS({
  "node_modules/undici/lib/web/fetch/formdata.js"(exports, module) {
    "use strict";
    var { iteratorMixin } = require_util2();
    var { kEnumerableProperty } = require_util();
    var { webidl } = require_webidl();
    var nodeUtil = __require("util");
    var FormData2 = class _FormData {
      #state = [];
      constructor(form = void 0) {
        webidl.util.markAsUncloneable(this);
        if (form !== void 0) {
          throw webidl.errors.conversionFailed({
            prefix: "FormData constructor",
            argument: "Argument 1",
            types: ["undefined"]
          });
        }
      }
      append(name, value, filename = void 0) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.append";
        webidl.argumentLengthCheck(arguments, 2, prefix);
        name = webidl.converters.USVString(name);
        if (arguments.length === 3 || webidl.is.Blob(value)) {
          value = webidl.converters.Blob(value, prefix, "value");
          if (filename !== void 0) {
            filename = webidl.converters.USVString(filename);
          }
        } else {
          value = webidl.converters.USVString(value);
        }
        const entry = makeEntry(name, value, filename);
        this.#state.push(entry);
      }
      delete(name) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.delete";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name = webidl.converters.USVString(name);
        this.#state = this.#state.filter((entry) => entry.name !== name);
      }
      get(name) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.get";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name = webidl.converters.USVString(name);
        const idx = this.#state.findIndex((entry) => entry.name === name);
        if (idx === -1) {
          return null;
        }
        return this.#state[idx].value;
      }
      getAll(name) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.getAll";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name = webidl.converters.USVString(name);
        return this.#state.filter((entry) => entry.name === name).map((entry) => entry.value);
      }
      has(name) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.has";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        name = webidl.converters.USVString(name);
        return this.#state.findIndex((entry) => entry.name === name) !== -1;
      }
      set(name, value, filename = void 0) {
        webidl.brandCheck(this, _FormData);
        const prefix = "FormData.set";
        webidl.argumentLengthCheck(arguments, 2, prefix);
        name = webidl.converters.USVString(name);
        if (arguments.length === 3 || webidl.is.Blob(value)) {
          value = webidl.converters.Blob(value, prefix, "value");
          if (filename !== void 0) {
            filename = webidl.converters.USVString(filename);
          }
        } else {
          value = webidl.converters.USVString(value);
        }
        const entry = makeEntry(name, value, filename);
        const idx = this.#state.findIndex((entry2) => entry2.name === name);
        if (idx !== -1) {
          this.#state = [
            ...this.#state.slice(0, idx),
            entry,
            ...this.#state.slice(idx + 1).filter((entry2) => entry2.name !== name)
          ];
        } else {
          this.#state.push(entry);
        }
      }
      [nodeUtil.inspect.custom](depth, options) {
        const state = this.#state.reduce((a, b) => {
          if (a[b.name]) {
            if (Array.isArray(a[b.name])) {
              a[b.name].push(b.value);
            } else {
              a[b.name] = [a[b.name], b.value];
            }
          } else {
            a[b.name] = b.value;
          }
          return a;
        }, { __proto__: null });
        options.depth ??= depth;
        options.colors ??= true;
        const output = nodeUtil.formatWithOptions(options, state);
        return `FormData ${output.slice(output.indexOf("]") + 2)}`;
      }
      /**
       * @param {FormData} formData
       */
      static getFormDataState(formData) {
        return formData.#state;
      }
      /**
       * @param {FormData} formData
       * @param {any[]} newState
       */
      static setFormDataState(formData, newState) {
        formData.#state = newState;
      }
    };
    var { getFormDataState, setFormDataState } = FormData2;
    Reflect.deleteProperty(FormData2, "getFormDataState");
    Reflect.deleteProperty(FormData2, "setFormDataState");
    iteratorMixin("FormData", FormData2, getFormDataState, "name", "value");
    Object.defineProperties(FormData2.prototype, {
      append: kEnumerableProperty,
      delete: kEnumerableProperty,
      get: kEnumerableProperty,
      getAll: kEnumerableProperty,
      has: kEnumerableProperty,
      set: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "FormData",
        configurable: true
      }
    });
    function makeEntry(name, value, filename) {
      if (typeof value === "string") {
      } else {
        if (!webidl.is.File(value)) {
          value = new File([value], "blob", { type: value.type });
        }
        if (filename !== void 0) {
          const options = {
            type: value.type,
            lastModified: value.lastModified
          };
          value = new File([value], filename, options);
        }
      }
      return { name, value };
    }
    webidl.is.FormData = webidl.util.MakeTypeAssertion(FormData2);
    module.exports = { FormData: FormData2, makeEntry, setFormDataState };
  }
});

// node_modules/undici/lib/web/fetch/formdata-parser.js
var require_formdata_parser = __commonJS({
  "node_modules/undici/lib/web/fetch/formdata-parser.js"(exports, module) {
    "use strict";
    var { bufferToLowerCasedHeaderName } = require_util();
    var { HTTP_TOKEN_CODEPOINTS } = require_data_url();
    var { makeEntry } = require_formdata();
    var { webidl } = require_webidl();
    var assert8 = __require("assert");
    var { isomorphicDecode } = require_infra();
    var dd = Buffer.from("--");
    var decoder2 = new TextDecoder();
    var decoderIgnoreBOM = new TextDecoder("utf-8", { ignoreBOM: true });
    function isAsciiString(chars) {
      for (let i = 0; i < chars.length; ++i) {
        if ((chars.charCodeAt(i) & ~127) !== 0) {
          return false;
        }
      }
      return true;
    }
    function validateBoundary(boundary) {
      const length = boundary.length;
      if (length < 27 || length > 70) {
        return false;
      }
      for (let i = 0; i < length; ++i) {
        const cp = boundary.charCodeAt(i);
        if (!(cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 39 || cp === 45 || cp === 95)) {
          return false;
        }
      }
      return true;
    }
    function multipartFormDataParser(input, mimeType) {
      assert8(mimeType !== "failure" && mimeType.essence === "multipart/form-data");
      const boundaryString = mimeType.parameters.get("boundary");
      if (boundaryString === void 0) {
        throw parsingError("missing boundary in content-type header");
      }
      const boundary = Buffer.from(`--${boundaryString}`, "utf8");
      const entryList = [];
      const position = { position: 0 };
      const firstBoundaryIndex = input.indexOf(boundary);
      if (firstBoundaryIndex === -1) {
        throw parsingError("no boundary found in multipart body");
      }
      position.position = firstBoundaryIndex;
      while (true) {
        if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) {
          position.position += boundary.length;
        } else {
          throw parsingError("expected a value starting with -- and the boundary");
        }
        if (bufferStartsWith(input, dd, position)) {
          return entryList;
        }
        if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
          throw parsingError("expected CRLF");
        }
        position.position += 2;
        const result = parseMultipartFormDataHeaders(input, position);
        let { name, filename, contentType, encoding } = result;
        position.position += 2;
        let body;
        {
          const boundaryIndex = input.indexOf(boundary.subarray(2), position.position);
          if (boundaryIndex === -1) {
            throw parsingError("expected boundary after body");
          }
          body = input.subarray(position.position, boundaryIndex - 4);
          position.position += body.length;
          if (encoding === "base64") {
            body = Buffer.from(body.toString(), "base64");
          }
        }
        if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
          throw parsingError("expected CRLF");
        } else {
          position.position += 2;
        }
        let value;
        if (filename !== null) {
          contentType ??= "text/plain";
          if (!isAsciiString(contentType)) {
            contentType = "";
          }
          value = new File([body], filename, { type: contentType });
        } else {
          value = decoderIgnoreBOM.decode(Buffer.from(body));
        }
        assert8(webidl.is.USVString(name));
        assert8(typeof value === "string" && webidl.is.USVString(value) || webidl.is.File(value));
        entryList.push(makeEntry(name, value, filename));
      }
    }
    function parseContentDispositionAttribute(input, position) {
      if (input[position.position] === 59) {
        position.position++;
      }
      collectASequenceOfBytes(
        (char) => char === 32 || char === 9,
        input,
        position
      );
      const attributeName = collectASequenceOfBytes(
        (char) => isToken(char) && char !== 61 && char !== 42,
        // not = or *
        input,
        position
      );
      if (attributeName.length === 0) {
        return null;
      }
      const attrNameStr = attributeName.toString("ascii").toLowerCase();
      const isExtended = input[position.position] === 42;
      if (isExtended) {
        position.position++;
      }
      if (input[position.position] !== 61) {
        return null;
      }
      position.position++;
      collectASequenceOfBytes(
        (char) => char === 32 || char === 9,
        input,
        position
      );
      let value;
      if (isExtended) {
        const headerValue = collectASequenceOfBytes(
          (char) => char !== 32 && char !== 13 && char !== 10 && char !== 59,
          // not space, CRLF, or ;
          input,
          position
        );
        if (headerValue[0] !== 117 && headerValue[0] !== 85 || // u or U
        headerValue[1] !== 116 && headerValue[1] !== 84 || // t or T
        headerValue[2] !== 102 && headerValue[2] !== 70 || // f or F
        headerValue[3] !== 45 || // -
        headerValue[4] !== 56) {
          throw parsingError("unknown encoding, expected utf-8''");
        }
        value = decodeURIComponent(decoder2.decode(headerValue.subarray(7)));
      } else if (input[position.position] === 34) {
        position.position++;
        const quotedValue = collectASequenceOfBytes(
          (char) => char !== 10 && char !== 13 && char !== 34,
          // not LF, CR, or "
          input,
          position
        );
        if (input[position.position] !== 34) {
          throw parsingError("Closing quote not found");
        }
        position.position++;
        value = decoder2.decode(quotedValue).replace(/%0A/ig, "\n").replace(/%0D/ig, "\r").replace(/%22/g, '"');
      } else {
        const tokenValue = collectASequenceOfBytes(
          (char) => isToken(char) && char !== 59,
          // not ;
          input,
          position
        );
        value = decoder2.decode(tokenValue);
      }
      return { name: attrNameStr, value, extended: isExtended };
    }
    function parseMultipartFormDataHeaders(input, position) {
      let name = null;
      let filename = null;
      let contentType = null;
      let encoding = null;
      while (true) {
        if (input[position.position] === 13 && input[position.position + 1] === 10) {
          if (name === null) {
            throw parsingError("header name is null");
          }
          return { name, filename, contentType, encoding };
        }
        let headerName = collectASequenceOfBytes(
          (char) => char !== 10 && char !== 13 && char !== 58,
          input,
          position
        );
        headerName = removeChars(headerName, true, true, (char) => char === 9 || char === 32);
        if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) {
          throw parsingError("header name does not match the field-name token production");
        }
        if (input[position.position] !== 58) {
          throw parsingError("expected :");
        }
        position.position++;
        collectASequenceOfBytes(
          (char) => char === 32 || char === 9,
          input,
          position
        );
        switch (bufferToLowerCasedHeaderName(headerName)) {
          case "content-disposition": {
            name = filename = null;
            let filenameIsExtended = false;
            const dispositionType = collectASequenceOfBytes(
              (char) => isToken(char),
              input,
              position
            );
            if (dispositionType.toString("ascii").toLowerCase() !== "form-data") {
              throw parsingError("expected form-data for content-disposition header");
            }
            while (position.position < input.length && (input[position.position] !== 13 || input[position.position + 1] !== 10)) {
              const attribute = parseContentDispositionAttribute(input, position);
              if (!attribute) {
                break;
              }
              if (attribute.name === "name") {
                name = attribute.value;
              } else if (attribute.name === "filename") {
                if (attribute.extended) {
                  filename = attribute.value;
                  filenameIsExtended = true;
                } else if (!filenameIsExtended) {
                  filename = attribute.value;
                }
              }
            }
            if (name === null) {
              throw parsingError("name attribute is required in content-disposition header");
            }
            break;
          }
          case "content-type": {
            let headerValue = collectASequenceOfBytes(
              (char) => char !== 10 && char !== 13,
              input,
              position
            );
            headerValue = removeChars(headerValue, false, true, (char) => char === 9 || char === 32);
            contentType = isomorphicDecode(headerValue);
            break;
          }
          case "content-transfer-encoding": {
            let headerValue = collectASequenceOfBytes(
              (char) => char !== 10 && char !== 13,
              input,
              position
            );
            headerValue = removeChars(headerValue, false, true, (char) => char === 9 || char === 32);
            encoding = isomorphicDecode(headerValue);
            break;
          }
          default: {
            collectASequenceOfBytes(
              (char) => char !== 10 && char !== 13,
              input,
              position
            );
          }
        }
        if (input[position.position] !== 13 || input[position.position + 1] !== 10) {
          throw parsingError("expected CRLF");
        } else {
          position.position += 2;
        }
      }
    }
    function collectASequenceOfBytes(condition, input, position) {
      let start = position.position;
      while (start < input.length && condition(input[start])) {
        ++start;
      }
      return input.subarray(position.position, position.position = start);
    }
    function removeChars(buf, leading, trailing, predicate) {
      let lead = 0;
      let trail = buf.length - 1;
      if (leading) {
        while (lead < buf.length && predicate(buf[lead])) lead++;
      }
      if (trailing) {
        while (trail > 0 && predicate(buf[trail])) trail--;
      }
      return lead === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead, trail + 1);
    }
    function bufferStartsWith(buffer2, start, position) {
      if (buffer2.length < start.length) {
        return false;
      }
      for (let i = 0; i < start.length; i++) {
        if (start[i] !== buffer2[position.position + i]) {
          return false;
        }
      }
      return true;
    }
    function parsingError(cause) {
      return new TypeError("Failed to parse body as FormData.", { cause: new TypeError(cause) });
    }
    function isCTL(char) {
      return char <= 31 || char === 127;
    }
    function isTSpecial(char) {
      return char === 40 || // (
      char === 41 || // )
      char === 60 || // <
      char === 62 || // >
      char === 64 || // @
      char === 44 || // ,
      char === 59 || // ;
      char === 58 || // :
      char === 92 || // \
      char === 34 || // "
      char === 47 || // /
      char === 91 || // [
      char === 93 || // ]
      char === 63 || // ?
      char === 61;
    }
    function isToken(char) {
      return char <= 127 && // ascii
      char !== 32 && // space
      char !== 9 && !isCTL(char) && !isTSpecial(char);
    }
    module.exports = {
      multipartFormDataParser,
      validateBoundary
    };
  }
});

// node_modules/undici/lib/util/runtime-features.js
var require_runtime_features = __commonJS({
  "node_modules/undici/lib/util/runtime-features.js"(exports, module) {
    "use strict";
    var lazyLoaders = {
      __proto__: null,
      "node:crypto": () => __require("crypto"),
      "node:sqlite": () => __require("sqlite")
    };
    function detectRuntimeFeatureByNodeModule(moduleName) {
      try {
        lazyLoaders[moduleName]();
        return true;
      } catch (err) {
        if (err.code !== "ERR_UNKNOWN_BUILTIN_MODULE" && err.code !== "ERR_NO_CRYPTO") {
          throw err;
        }
        return false;
      }
    }
    var runtimeFeaturesAsNodeModule = (
      /** @type {const} */
      ["crypto", "sqlite"]
    );
    function detectRuntimeFeature(feature) {
      if (runtimeFeaturesAsNodeModule.includes(
        /** @type {RuntimeFeatureByNodeModule} */
        feature
      )) {
        return detectRuntimeFeatureByNodeModule(`node:${feature}`);
      }
      throw new TypeError(`unknown feature: ${feature}`);
    }
    var RuntimeFeatures = class {
      /** @type {Map<Feature, boolean>} */
      #map = /* @__PURE__ */ new Map();
      /**
       * Clears all cached feature detections.
       */
      clear() {
        this.#map.clear();
      }
      /**
       * @param {Feature} feature
       * @returns {boolean}
       */
      has(feature) {
        return this.#map.get(feature) ?? this.#detectRuntimeFeature(feature);
      }
      /**
       * @param {Feature} feature
       * @param {boolean} value
       */
      set(feature, value) {
        if (runtimeFeaturesAsNodeModule.includes(feature) === false) {
          throw new TypeError(`unknown feature: ${feature}`);
        }
        this.#map.set(feature, value);
      }
      /**
       * @param {Feature} feature
       * @returns {boolean}
       */
      #detectRuntimeFeature(feature) {
        const result = detectRuntimeFeature(feature);
        this.#map.set(feature, result);
        return result;
      }
    };
    var instance = new RuntimeFeatures();
    module.exports.runtimeFeatures = instance;
    module.exports.default = instance;
  }
});

// node_modules/undici/lib/web/fetch/body.js
var require_body = __commonJS({
  "node_modules/undici/lib/web/fetch/body.js"(exports, module) {
    "use strict";
    var util2 = require_util();
    var {
      ReadableStreamFrom,
      readableStreamClose,
      fullyReadBody,
      extractMimeType
    } = require_util2();
    var { FormData: FormData2, setFormDataState } = require_formdata();
    var { webidl } = require_webidl();
    var assert8 = __require("assert");
    var { isErrored, isDisturbed } = __require("stream");
    var { isUint8Array } = __require("util/types");
    var { serializeAMimeType } = require_data_url();
    var { multipartFormDataParser } = require_formdata_parser();
    var { parseJSONFromBytes } = require_infra();
    var { utf8DecodeBytes } = require_encoding();
    var { runtimeFeatures } = require_runtime_features();
    var random = runtimeFeatures.has("crypto") ? __require("crypto").randomInt : (max) => Math.floor(Math.random() * max);
    var textEncoder = new TextEncoder();
    function noop() {
    }
    var streamRegistry = new FinalizationRegistry((weakRef) => {
      const stream = weakRef.deref();
      if (stream && !stream.locked && !isDisturbed(stream) && !isErrored(stream)) {
        stream.cancel("Response object has been garbage collected").catch(noop);
      }
    });
    function extractBody(object, keepalive = false) {
      let stream = null;
      let controller = null;
      if (webidl.is.ReadableStream(object)) {
        stream = object;
      } else if (webidl.is.Blob(object)) {
        stream = object.stream();
      } else {
        stream = new ReadableStream({
          pull() {
          },
          start(c) {
            controller = c;
          },
          cancel() {
          },
          type: "bytes"
        });
      }
      assert8(webidl.is.ReadableStream(stream));
      let action = null;
      let source = null;
      let length = null;
      let type = null;
      if (typeof object === "string") {
        source = object;
        type = "text/plain;charset=UTF-8";
      } else if (webidl.is.URLSearchParams(object)) {
        source = object.toString();
        type = "application/x-www-form-urlencoded;charset=UTF-8";
      } else if (webidl.is.BufferSource(object)) {
        source = webidl.util.getCopyOfBytesHeldByBufferSource(object);
      } else if (webidl.is.FormData(object)) {
        const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, "0")}`;
        const prefix = `--${boundary}\r
Content-Disposition: form-data`;
        const formdataEscape = (str) => str.replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22");
        const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, "\r\n");
        const blobParts = [];
        const rn = new Uint8Array([13, 10]);
        length = 0;
        let hasUnknownSizeValue = false;
        for (const [name, value] of object) {
          if (typeof value === "string") {
            const chunk2 = textEncoder.encode(prefix + `; name="${formdataEscape(normalizeLinefeeds(name))}"\r
\r
${normalizeLinefeeds(value)}\r
`);
            blobParts.push(chunk2);
            length += chunk2.byteLength;
          } else {
            const chunk2 = textEncoder.encode(`${prefix}; name="${formdataEscape(normalizeLinefeeds(name))}"` + (value.name ? `; filename="${formdataEscape(value.name)}"` : "") + `\r
Content-Type: ${value.type || "application/octet-stream"}\r
\r
`);
            blobParts.push(chunk2, value, rn);
            if (typeof value.size === "number") {
              length += chunk2.byteLength + value.size + rn.byteLength;
            } else {
              hasUnknownSizeValue = true;
            }
          }
        }
        const chunk = textEncoder.encode(`--${boundary}--\r
`);
        blobParts.push(chunk);
        length += chunk.byteLength;
        if (hasUnknownSizeValue) {
          length = null;
        }
        source = object;
        action = async function* () {
          for (const part of blobParts) {
            if (part.stream) {
              yield* part.stream();
            } else {
              yield part;
            }
          }
        };
        type = `multipart/form-data; boundary=${boundary}`;
      } else if (webidl.is.Blob(object)) {
        source = object;
        length = object.size;
        if (object.type) {
          type = object.type;
        }
      } else if (typeof object[Symbol.asyncIterator] === "function") {
        if (keepalive) {
          throw new TypeError("keepalive");
        }
        if (util2.isDisturbed(object) || object.locked) {
          throw new TypeError(
            "Response body object should not be disturbed or locked"
          );
        }
        stream = webidl.is.ReadableStream(object) ? object : ReadableStreamFrom(object);
      }
      if (typeof source === "string" || isUint8Array(source)) {
        action = () => {
          length = typeof source === "string" ? Buffer.byteLength(source) : source.length;
          return source;
        };
      }
      if (action != null) {
        ;
        (async () => {
          const result = action();
          const iterator = result?.[Symbol.asyncIterator]?.();
          if (iterator) {
            for await (const bytes of iterator) {
              if (isErrored(stream)) break;
              if (bytes.length) {
                controller.enqueue(new Uint8Array(bytes));
              }
            }
          } else if (result?.length && !isErrored(stream)) {
            controller.enqueue(typeof result === "string" ? textEncoder.encode(result) : new Uint8Array(result));
          }
          queueMicrotask(() => readableStreamClose(controller));
        })();
      }
      const body = { stream, source, length };
      return [body, type];
    }
    function safelyExtractBody(object, keepalive = false) {
      if (webidl.is.ReadableStream(object)) {
        assert8(!util2.isDisturbed(object), "The body has already been consumed.");
        assert8(!object.locked, "The stream is locked.");
      }
      return extractBody(object, keepalive);
    }
    function cloneBody(body) {
      const { 0: out1, 1: out2 } = body.stream.tee();
      body.stream = out1;
      return {
        stream: out2,
        length: body.length,
        source: body.source
      };
    }
    function bodyMixinMethods(instance, getInternalState) {
      const methods = {
        blob() {
          return consumeBody(this, (bytes) => {
            let mimeType = bodyMimeType(getInternalState(this));
            if (mimeType === null) {
              mimeType = "";
            } else if (mimeType) {
              mimeType = serializeAMimeType(mimeType);
            }
            return new Blob([bytes], { type: mimeType });
          }, instance, getInternalState);
        },
        arrayBuffer() {
          return consumeBody(this, (bytes) => {
            return new Uint8Array(bytes).buffer;
          }, instance, getInternalState);
        },
        text() {
          return consumeBody(this, utf8DecodeBytes, instance, getInternalState);
        },
        json() {
          return consumeBody(this, parseJSONFromBytes, instance, getInternalState);
        },
        formData() {
          return consumeBody(this, (value) => {
            const mimeType = bodyMimeType(getInternalState(this));
            if (mimeType !== null) {
              switch (mimeType.essence) {
                case "multipart/form-data": {
                  const parsed = multipartFormDataParser(value, mimeType);
                  const fd = new FormData2();
                  setFormDataState(fd, parsed);
                  return fd;
                }
                case "application/x-www-form-urlencoded": {
                  const entries = new URLSearchParams(value.toString());
                  const fd = new FormData2();
                  for (const [name, value2] of entries) {
                    fd.append(name, value2);
                  }
                  return fd;
                }
              }
            }
            throw new TypeError(
              'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".'
            );
          }, instance, getInternalState);
        },
        bytes() {
          return consumeBody(this, (bytes) => {
            return new Uint8Array(bytes);
          }, instance, getInternalState);
        }
      };
      return methods;
    }
    function mixinBody(prototype, getInternalState) {
      Object.assign(prototype.prototype, bodyMixinMethods(prototype, getInternalState));
    }
    function consumeBody(object, convertBytesToJSValue, instance, getInternalState) {
      try {
        webidl.brandCheck(object, instance);
      } catch (e7) {
        return Promise.reject(e7);
      }
      object = getInternalState(object);
      if (bodyUnusable(object)) {
        return Promise.reject(new TypeError("Body is unusable: Body has already been read"));
      }
      const promise = Promise.withResolvers();
      const errorSteps = promise.reject;
      const successSteps = (data) => {
        try {
          promise.resolve(convertBytesToJSValue(data));
        } catch (e7) {
          errorSteps(e7);
        }
      };
      if (object.body == null) {
        successSteps(Buffer.allocUnsafe(0));
        return promise.promise;
      }
      fullyReadBody(object.body, successSteps, errorSteps);
      return promise.promise;
    }
    function bodyUnusable(object) {
      const body = object.body;
      return body != null && (body.stream.locked || util2.isDisturbed(body.stream));
    }
    function bodyMimeType(requestOrResponse) {
      const headers = requestOrResponse.headersList;
      const mimeType = extractMimeType(headers);
      if (mimeType === "failure") {
        return null;
      }
      return mimeType;
    }
    module.exports = {
      extractBody,
      safelyExtractBody,
      cloneBody,
      mixinBody,
      streamRegistry,
      bodyUnusable
    };
  }
});

// node_modules/undici/lib/dispatcher/client-h1.js
var require_client_h1 = __commonJS({
  "node_modules/undici/lib/dispatcher/client-h1.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var util2 = require_util();
    var { channels } = require_diagnostics();
    var timers = require_timers();
    var {
      RequestContentLengthMismatchError,
      ResponseContentLengthMismatchError,
      RequestAbortedError,
      HeadersTimeoutError,
      HeadersOverflowError,
      SocketError,
      InformationalError,
      BodyTimeoutError,
      HTTPParserError,
      ResponseExceededMaxSizeError
    } = require_errors();
    var {
      kUrl,
      kReset,
      kClient,
      kParser,
      kBlocking,
      kRunning,
      kPending,
      kSize,
      kWriting,
      kQueue,
      kNoRef,
      kKeepAliveDefaultTimeout,
      kHostHeader,
      kPendingIdx,
      kRunningIdx,
      kError,
      kPipelining,
      kSocket,
      kKeepAliveTimeoutValue,
      kMaxHeadersSize,
      kKeepAliveMaxTimeout,
      kKeepAliveTimeoutThreshold,
      kHeadersTimeout,
      kBodyTimeout,
      kStrictContentLength,
      kMaxRequests,
      kCounter,
      kMaxResponseSize,
      kOnError,
      kResume,
      kHTTPContext,
      kClosed
    } = require_symbols();
    var constants = require_constants3();
    var EMPTY_BUF = Buffer.alloc(0);
    var FastBuffer = Buffer[Symbol.species];
    var removeAllListeners = util2.removeAllListeners;
    var extractBody;
    function lazyllhttp() {
      const llhttpWasmData = process.env.JEST_WORKER_ID ? require_llhttp_wasm() : void 0;
      let mod5;
      let useWasmSIMD = process.arch !== "ppc64";
      if (process.env.UNDICI_NO_WASM_SIMD === "1") {
        useWasmSIMD = false;
      } else if (process.env.UNDICI_NO_WASM_SIMD === "0") {
        useWasmSIMD = true;
      }
      if (useWasmSIMD) {
        try {
          mod5 = new WebAssembly.Module(require_llhttp_simd_wasm());
        } catch {
        }
      }
      if (!mod5) {
        mod5 = new WebAssembly.Module(llhttpWasmData || require_llhttp_wasm());
      }
      return new WebAssembly.Instance(mod5, {
        env: {
          /**
           * @param {number} p
           * @param {number} at
           * @param {number} len
           * @returns {number}
           */
          wasm_on_url: (p, at, len) => {
            return 0;
          },
          /**
           * @param {number} p
           * @param {number} at
           * @param {number} len
           * @returns {number}
           */
          wasm_on_status: (p, at, len) => {
            assert8(currentParser.ptr === p);
            const start = at - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len));
          },
          /**
           * @param {number} p
           * @returns {number}
           */
          wasm_on_message_begin: (p) => {
            assert8(currentParser.ptr === p);
            return currentParser.onMessageBegin();
          },
          /**
           * @param {number} p
           * @param {number} at
           * @param {number} len
           * @returns {number}
           */
          wasm_on_header_field: (p, at, len) => {
            assert8(currentParser.ptr === p);
            const start = at - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len));
          },
          /**
           * @param {number} p
           * @param {number} at
           * @param {number} len
           * @returns {number}
           */
          wasm_on_header_value: (p, at, len) => {
            assert8(currentParser.ptr === p);
            const start = at - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len));
          },
          /**
           * @param {number} p
           * @param {number} statusCode
           * @param {0|1} upgrade
           * @param {0|1} shouldKeepAlive
           * @returns {number}
           */
          wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
            assert8(currentParser.ptr === p);
            return currentParser.onHeadersComplete(statusCode, upgrade === 1, shouldKeepAlive === 1);
          },
          /**
           * @param {number} p
           * @param {number} at
           * @param {number} len
           * @returns {number}
           */
          wasm_on_body: (p, at, len) => {
            assert8(currentParser.ptr === p);
            const start = at - currentBufferPtr + currentBufferRef.byteOffset;
            return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len));
          },
          /**
           * @param {number} p
           * @returns {number}
           */
          wasm_on_message_complete: (p) => {
            assert8(currentParser.ptr === p);
            return currentParser.onMessageComplete();
          }
        }
      });
    }
    var llhttpInstance = null;
    var currentParser = null;
    var currentBufferRef = null;
    var currentBufferSize = 0;
    var currentBufferPtr = null;
    var currentBuffer = null;
    var USE_NATIVE_TIMER = 0;
    var USE_FAST_TIMER = 1;
    var TIMEOUT_HEADERS = 2 | USE_FAST_TIMER;
    var TIMEOUT_BODY = 4 | USE_FAST_TIMER;
    var TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER;
    var Parser = class {
      /**
         * @param {import('./client.js')} client
         * @param {import('net').Socket} socket
         * @param {*} llhttp
         */
      constructor(client, socket, { exports: exports2 }) {
        this.llhttp = exports2;
        this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE);
        this.client = client;
        this.socket = socket;
        this.timeout = null;
        this.timeoutWeakRef = new WeakRef(this);
        this.timeoutValue = null;
        this.timeoutType = null;
        this.statusCode = 0;
        this.statusText = "";
        this.upgrade = false;
        this.headers = [];
        this.headersSize = 0;
        this.headersMaxSize = client[kMaxHeadersSize];
        this.shouldKeepAlive = false;
        this.paused = false;
        this.resume = this.resume.bind(this);
        this.bytesRead = 0;
        this.keepAlive = "";
        this.contentLength = -1;
        this.connectionKeepAlive = false;
        this.maxResponseSize = client[kMaxResponseSize];
      }
      setTimeout(delay, type) {
        if (delay !== this.timeoutValue || type & USE_FAST_TIMER ^ this.timeoutType & USE_FAST_TIMER) {
          if (this.timeout) {
            timers.clearTimeout(this.timeout);
            this.timeout = null;
          }
          if (delay) {
            if (type & USE_FAST_TIMER) {
              this.timeout = timers.setFastTimeout(onParserTimeout, delay, this.timeoutWeakRef);
            } else {
              this.timeout = setTimeout(onParserTimeout, delay, this.timeoutWeakRef);
              this.timeout?.unref();
            }
          }
          this.timeoutValue = delay;
        } else if (this.timeout) {
          if (this.timeout.refresh) {
            this.timeout.refresh();
          }
        }
        this.timeoutType = type;
      }
      resume() {
        if (this.socket.destroyed || !this.paused) {
          return;
        }
        assert8(this.ptr != null);
        assert8(currentParser === null);
        this.llhttp.llhttp_resume(this.ptr);
        assert8(this.timeoutType === TIMEOUT_BODY);
        if (this.timeout) {
          if (this.timeout.refresh) {
            this.timeout.refresh();
          }
        }
        this.paused = false;
        this.execute(this.socket.read() || EMPTY_BUF);
        this.readMore();
      }
      readMore() {
        while (!this.paused && this.ptr) {
          const chunk = this.socket.read();
          if (chunk === null) {
            break;
          }
          this.execute(chunk);
        }
      }
      /**
       * @param {Buffer} chunk
       */
      execute(chunk) {
        assert8(currentParser === null);
        assert8(this.ptr != null);
        assert8(!this.paused);
        const { socket, llhttp } = this;
        if (chunk.length > currentBufferSize) {
          if (currentBufferPtr) {
            llhttp.free(currentBufferPtr);
          }
          currentBufferSize = Math.ceil(chunk.length / 4096) * 4096;
          currentBufferPtr = llhttp.malloc(currentBufferSize);
        }
        if (currentBuffer === null || currentBuffer.buffer !== llhttp.memory.buffer || currentBuffer.byteOffset !== currentBufferPtr || currentBuffer.byteLength !== currentBufferSize) {
          currentBuffer = new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize);
        }
        currentBuffer.set(chunk);
        try {
          let ret;
          try {
            currentBufferRef = chunk;
            currentParser = this;
            ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, chunk.length);
          } finally {
            currentParser = null;
            currentBufferRef = null;
          }
          if (ret !== constants.ERROR.OK) {
            const data = chunk.subarray(llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr);
            if (ret === constants.ERROR.PAUSED_UPGRADE) {
              this.onUpgrade(data);
            } else if (ret === constants.ERROR.PAUSED) {
              this.paused = true;
              socket.unshift(data);
            } else {
              const ptr = llhttp.llhttp_get_error_reason(this.ptr);
              let message = "";
              if (ptr) {
                const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0);
                message = "Response does not match the HTTP/1.1 protocol (" + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + ")";
              }
              throw new HTTPParserError(message, constants.ERROR[ret], data);
            }
          }
        } catch (err) {
          util2.destroy(socket, err);
        }
      }
      destroy() {
        assert8(currentParser === null);
        assert8(this.ptr != null);
        this.llhttp.llhttp_free(this.ptr);
        this.ptr = null;
        this.timeout && timers.clearTimeout(this.timeout);
        this.timeout = null;
        this.timeoutValue = null;
        this.timeoutType = null;
        this.paused = false;
      }
      /**
       * @param {Buffer} buf
       * @returns {0}
       */
      onStatus(buf) {
        this.statusText = buf.toString();
        return 0;
      }
      /**
       * @returns {0|-1}
       */
      onMessageBegin() {
        const { socket, client } = this;
        if (socket.destroyed) {
          return -1;
        }
        const request = client[kQueue][client[kRunningIdx]];
        if (!request) {
          return -1;
        }
        request.onResponseStarted();
        return 0;
      }
      /**
       * @param {Buffer} buf
       * @returns {number}
       */
      onHeaderField(buf) {
        const len = this.headers.length;
        if ((len & 1) === 0) {
          this.headers.push(buf);
        } else {
          this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]);
        }
        this.trackHeader(buf.length);
        return 0;
      }
      /**
       * @param {Buffer} buf
       * @returns {number}
       */
      onHeaderValue(buf) {
        let len = this.headers.length;
        if ((len & 1) === 1) {
          this.headers.push(buf);
          len += 1;
        } else {
          this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]);
        }
        const key = this.headers[len - 2];
        if (key.length === 10) {
          const headerName = util2.bufferToLowerCasedHeaderName(key);
          if (headerName === "keep-alive") {
            this.keepAlive += buf.toString();
          } else if (headerName === "connection") {
            this.connectionKeepAlive = this.headers[len - 1].length === 10 && util2.bufferToLowerCasedHeaderName(this.headers[len - 1]) === "keep-alive";
          }
        } else if (key.length === 14 && util2.bufferToLowerCasedHeaderName(key) === "content-length") {
          if (this.contentLength === -1) {
            this.contentLength = 0;
          }
          for (let i = 0; i < buf.length; i++) {
            this.contentLength = this.contentLength * 10 + (buf[i] - 48);
          }
        }
        this.trackHeader(buf.length);
        return 0;
      }
      /**
       * @param {number} len
       */
      trackHeader(len) {
        this.headersSize += len;
        if (this.headersSize >= this.headersMaxSize) {
          util2.destroy(this.socket, new HeadersOverflowError());
        }
      }
      /**
       * @param {Buffer} head
       */
      onUpgrade(head) {
        const { upgrade, client, socket, headers, statusCode } = this;
        assert8(upgrade);
        assert8(client[kSocket] === socket);
        assert8(!socket.destroyed);
        assert8(!this.paused);
        assert8((headers.length & 1) === 0);
        const request = client[kQueue][client[kRunningIdx]];
        assert8(request);
        assert8(request.upgrade || request.method === "CONNECT");
        this.statusCode = 0;
        this.statusText = "";
        this.shouldKeepAlive = false;
        this.headers = [];
        this.headersSize = 0;
        socket.unshift(head);
        socket[kParser].destroy();
        socket[kParser] = null;
        socket[kClient] = null;
        socket[kError] = null;
        removeAllListeners(socket);
        client[kSocket] = null;
        client[kHTTPContext] = null;
        client[kQueue][client[kRunningIdx]++] = null;
        client.emit("disconnect", client[kUrl], [client], new InformationalError("upgrade"));
        try {
          request.onRequestUpgrade(statusCode, headers, socket);
        } catch (err) {
          util2.destroy(socket, err);
        }
        client[kResume]();
      }
      /**
       * @param {number} statusCode
       * @param {boolean} upgrade
       * @param {boolean} shouldKeepAlive
       * @returns {number}
       */
      onHeadersComplete(statusCode, upgrade, shouldKeepAlive) {
        const { client, socket, headers, statusText } = this;
        if (socket.destroyed) {
          return -1;
        }
        const request = client[kQueue][client[kRunningIdx]];
        if (!request) {
          return -1;
        }
        assert8(!this.upgrade);
        assert8(this.statusCode < 200);
        if (statusCode === 100) {
          util2.destroy(socket, new SocketError("bad response", util2.getSocketInfo(socket)));
          return -1;
        }
        if (upgrade && !request.upgrade) {
          util2.destroy(socket, new SocketError("bad upgrade", util2.getSocketInfo(socket)));
          return -1;
        }
        assert8(this.timeoutType === TIMEOUT_HEADERS);
        this.statusCode = statusCode;
        this.shouldKeepAlive = shouldKeepAlive || // Override llhttp value which does not allow keepAlive for HEAD.
        request.method === "HEAD" && !socket[kReset] && this.connectionKeepAlive;
        if (this.statusCode >= 200) {
          const bodyTimeout = request.bodyTimeout != null ? request.bodyTimeout : client[kBodyTimeout];
          this.setTimeout(bodyTimeout, TIMEOUT_BODY);
        } else if (this.timeout) {
          if (this.timeout.refresh) {
            this.timeout.refresh();
          }
        }
        if (request.method === "CONNECT") {
          assert8(client[kRunning] === 1);
          this.upgrade = true;
          return 2;
        }
        if (upgrade) {
          assert8(client[kRunning] === 1);
          this.upgrade = true;
          return 2;
        }
        assert8((this.headers.length & 1) === 0);
        this.headers = [];
        this.headersSize = 0;
        if (this.shouldKeepAlive && client[kPipelining]) {
          const keepAliveTimeout = this.keepAlive ? util2.parseKeepAliveTimeout(this.keepAlive) : null;
          if (keepAliveTimeout != null) {
            const timeout = Math.min(
              keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
              client[kKeepAliveMaxTimeout]
            );
            if (timeout <= 0) {
              socket[kReset] = true;
            } else {
              client[kKeepAliveTimeoutValue] = timeout;
            }
          } else {
            client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout];
          }
        } else {
          socket[kReset] = true;
        }
        const pause = request.onResponseStart(statusCode, headers, this.resume, statusText) === false;
        if (request.aborted) {
          return -1;
        }
        if (request.method === "HEAD") {
          return 1;
        }
        if (statusCode < 200) {
          return 1;
        }
        if (socket[kBlocking]) {
          socket[kBlocking] = false;
          client[kResume]();
        }
        return pause ? constants.ERROR.PAUSED : 0;
      }
      /**
       * @param {Buffer} buf
       * @returns {number}
       */
      onBody(buf) {
        const { client, socket, statusCode, maxResponseSize } = this;
        if (socket.destroyed) {
          return -1;
        }
        const request = client[kQueue][client[kRunningIdx]];
        assert8(request);
        assert8(this.timeoutType === TIMEOUT_BODY);
        if (this.timeout) {
          if (this.timeout.refresh) {
            this.timeout.refresh();
          }
        }
        assert8(statusCode >= 200);
        if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
          util2.destroy(socket, new ResponseExceededMaxSizeError());
          return -1;
        }
        this.bytesRead += buf.length;
        if (request.onResponseData(buf) === false) {
          return constants.ERROR.PAUSED;
        }
        return 0;
      }
      /**
       * @returns {number}
       */
      onMessageComplete() {
        const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this;
        if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
          return -1;
        }
        if (upgrade) {
          return 0;
        }
        assert8(statusCode >= 100);
        assert8((this.headers.length & 1) === 0);
        const request = client[kQueue][client[kRunningIdx]];
        assert8(request);
        this.statusCode = 0;
        this.statusText = "";
        this.bytesRead = 0;
        this.contentLength = -1;
        this.keepAlive = "";
        this.connectionKeepAlive = false;
        this.headers = [];
        this.headersSize = 0;
        if (statusCode < 200) {
          return 0;
        }
        if (request.method !== "HEAD" && contentLength !== -1 && bytesRead !== contentLength) {
          util2.destroy(socket, new ResponseContentLengthMismatchError());
          return -1;
        }
        request.onResponseEnd(headers);
        client[kQueue][client[kRunningIdx]++] = null;
        if (socket[kWriting]) {
          assert8(client[kRunning] === 0);
          util2.destroy(socket, new InformationalError("reset"));
          return constants.ERROR.PAUSED;
        } else if (!shouldKeepAlive) {
          util2.destroy(socket, new InformationalError("reset"));
          return constants.ERROR.PAUSED;
        } else if (socket[kReset] && client[kRunning] === 0) {
          util2.destroy(socket, new InformationalError("reset"));
          return constants.ERROR.PAUSED;
        } else if (client[kPipelining] == null || client[kPipelining] === 1) {
          setImmediate(client[kResume]);
        } else {
          client[kResume]();
        }
        return 0;
      }
    };
    function onParserTimeout(parserWeakRef) {
      const parser = parserWeakRef.deref();
      if (!parser) {
        return;
      }
      const { socket, timeoutType, client, paused } = parser;
      if (timeoutType === TIMEOUT_HEADERS) {
        if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
          assert8(!paused, "cannot be paused while waiting for headers");
          util2.destroy(socket, new HeadersTimeoutError());
        }
      } else if (timeoutType === TIMEOUT_BODY) {
        if (!paused) {
          util2.destroy(socket, new BodyTimeoutError());
        }
      } else if (timeoutType === TIMEOUT_KEEP_ALIVE) {
        assert8(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]);
        util2.destroy(socket, new InformationalError("socket idle timeout"));
      }
    }
    function connectH1(client, socket) {
      client[kSocket] = socket;
      if (!llhttpInstance) {
        llhttpInstance = lazyllhttp();
      }
      if (socket.errored) {
        throw socket.errored;
      }
      if (socket.destroyed) {
        throw new SocketError("destroyed");
      }
      socket[kNoRef] = false;
      socket[kWriting] = false;
      socket[kReset] = false;
      socket[kBlocking] = false;
      socket[kParser] = new Parser(client, socket, llhttpInstance);
      util2.addListener(socket, "error", onHttpSocketError);
      util2.addListener(socket, "readable", onHttpSocketReadable);
      util2.addListener(socket, "end", onHttpSocketEnd);
      util2.addListener(socket, "close", onHttpSocketClose);
      socket[kClosed] = false;
      socket.on("close", onSocketClose);
      return {
        version: "h1",
        defaultPipelining: 1,
        write(request) {
          return writeH1(client, request);
        },
        resume() {
          resumeH1(client);
        },
        /**
         * @param {Error|undefined} err
         * @param {() => void} callback
         */
        destroy(err, callback) {
          if (socket[kClosed]) {
            queueMicrotask(callback);
          } else {
            socket.on("close", callback);
            socket.destroy(err);
          }
        },
        /**
         * @returns {boolean}
         */
        get destroyed() {
          return socket.destroyed;
        },
        /**
         * @param {import('../core/request.js')} request
         * @returns {boolean}
         */
        busy(request) {
          if (socket[kWriting] || socket[kReset] || socket[kBlocking]) {
            return true;
          }
          if (request) {
            if (client[kRunning] > 0 && !request.idempotent) {
              return true;
            }
            if (client[kRunning] > 0 && (request.upgrade || request.method === "CONNECT")) {
              return true;
            }
            if (client[kRunning] > 0 && util2.bodyLength(request.body) !== 0 && (util2.isStream(request.body) || util2.isAsyncIterable(request.body) || util2.isFormDataLike(request.body))) {
              return true;
            }
          }
          return false;
        }
      };
    }
    function onHttpSocketError(err) {
      assert8(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
      const parser = this[kParser];
      if (err.code === "ECONNRESET" && parser.statusCode && !parser.shouldKeepAlive) {
        parser.onMessageComplete();
        return;
      }
      this[kError] = err;
      this[kClient][kOnError](err);
    }
    function onHttpSocketReadable() {
      this[kParser]?.readMore();
    }
    function onHttpSocketEnd() {
      const parser = this[kParser];
      if (parser.statusCode && !parser.shouldKeepAlive) {
        parser.onMessageComplete();
        return;
      }
      util2.destroy(this, new SocketError("other side closed", util2.getSocketInfo(this)));
    }
    function onHttpSocketClose() {
      const parser = this[kParser];
      if (parser) {
        if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
          parser.onMessageComplete();
        }
        this[kParser].destroy();
        this[kParser] = null;
      }
      const err = this[kError] || new SocketError("closed", util2.getSocketInfo(this));
      const client = this[kClient];
      client[kSocket] = null;
      client[kHTTPContext] = null;
      if (client.destroyed) {
        assert8(client[kPending] === 0);
        const requests = client[kQueue].splice(client[kRunningIdx]);
        for (let i = 0; i < requests.length; i++) {
          const request = requests[i];
          util2.errorRequest(client, request, err);
        }
      } else if (client[kRunning] > 0 && err.code !== "UND_ERR_INFO") {
        const request = client[kQueue][client[kRunningIdx]];
        client[kQueue][client[kRunningIdx]++] = null;
        util2.errorRequest(client, request, err);
      }
      client[kPendingIdx] = client[kRunningIdx];
      assert8(client[kRunning] === 0);
      client.emit("disconnect", client[kUrl], [client], err);
      client[kResume]();
    }
    function onSocketClose() {
      this[kClosed] = true;
    }
    function resumeH1(client) {
      const socket = client[kSocket];
      if (socket && !socket.destroyed) {
        if (client[kSize] === 0) {
          if (!socket[kNoRef] && socket.unref) {
            socket.unref();
            socket[kNoRef] = true;
          }
        } else if (socket[kNoRef] && socket.ref) {
          socket.ref();
          socket[kNoRef] = false;
        }
        if (client[kSize] === 0) {
          if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
            socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE);
          }
        } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
          if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
            const request = client[kQueue][client[kRunningIdx]];
            const headersTimeout = request.headersTimeout != null ? request.headersTimeout : client[kHeadersTimeout];
            socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS);
          }
        }
      }
    }
    function shouldSendContentLength(method) {
      return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
    }
    function writeH1(client, request) {
      const { method, path: path2, host, upgrade, blocking, reset } = request;
      let { body, headers, contentLength } = request;
      const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
      if (util2.isFormDataLike(body)) {
        if (!extractBody) {
          extractBody = require_body().extractBody;
        }
        const [bodyStream, contentType] = extractBody(body);
        if (request.contentType == null) {
          headers.push("content-type", contentType);
        }
        body = bodyStream.stream;
        contentLength = bodyStream.length;
      } else if (util2.isBlobLike(body) && request.contentType == null && body.type) {
        headers.push("content-type", body.type);
      }
      if (body && typeof body.read === "function") {
        body.read(0);
      }
      const bodyLength = util2.bodyLength(body);
      contentLength = bodyLength ?? contentLength;
      if (contentLength === null) {
        contentLength = request.contentLength;
      }
      if (contentLength === 0 && !expectsPayload) {
        contentLength = null;
      }
      if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {
        if (client[kStrictContentLength]) {
          util2.errorRequest(client, request, new RequestContentLengthMismatchError());
          return false;
        }
        process.emitWarning(new RequestContentLengthMismatchError());
      }
      const socket = client[kSocket];
      const abort = (err) => {
        if (request.aborted || request.completed) {
          return;
        }
        util2.errorRequest(client, request, err || new RequestAbortedError());
        util2.destroy(body);
        util2.destroy(socket, new InformationalError("aborted"));
      };
      try {
        request.onRequestStart(abort, null);
      } catch (err) {
        util2.errorRequest(client, request, err);
      }
      if (request.aborted) {
        return false;
      }
      if (method === "HEAD") {
        socket[kReset] = true;
      }
      if (upgrade || method === "CONNECT") {
        socket[kReset] = true;
      }
      if (reset != null) {
        socket[kReset] = reset;
      }
      if (client[kMaxRequests] && ++socket[kCounter] >= client[kMaxRequests]) {
        socket[kReset] = true;
      }
      if (blocking) {
        socket[kBlocking] = true;
      }
      if (socket.setTypeOfService) {
        socket.setTypeOfService(request.typeOfService);
      }
      let header = `${method} ${path2} HTTP/1.1\r
`;
      if (typeof host === "string") {
        header += `host: ${host}\r
`;
      } else {
        header += client[kHostHeader];
      }
      if (upgrade) {
        header += `connection: upgrade\r
upgrade: ${upgrade}\r
`;
      } else if (client[kPipelining] && !socket[kReset]) {
        header += "connection: keep-alive\r\n";
      } else {
        header += "connection: close\r\n";
      }
      if (Array.isArray(headers)) {
        for (let n = 0; n < headers.length; n += 2) {
          const key = headers[n + 0];
          const val = headers[n + 1];
          if (Array.isArray(val)) {
            for (let i = 0; i < val.length; i++) {
              header += `${key}: ${val[i]}\r
`;
            }
          } else {
            header += `${key}: ${val}\r
`;
          }
        }
      }
      if (channels.sendHeaders.hasSubscribers) {
        channels.sendHeaders.publish({ request, headers: header, socket });
      }
      if (!body || bodyLength === 0) {
        writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload);
      } else if (util2.isBuffer(body)) {
        writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload);
      } else if (util2.isBlobLike(body)) {
        if (typeof body.stream === "function") {
          writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload);
        } else {
          writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload);
        }
      } else if (util2.isStream(body)) {
        writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload);
      } else if (util2.isIterable(body)) {
        writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload);
      } else {
        assert8(false);
      }
      return true;
    }
    function writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload) {
      assert8(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
      let finished2 = false;
      const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header });
      const onData = function(chunk) {
        if (finished2) {
          return;
        }
        try {
          if (!writer.write(chunk) && this.pause) {
            this.pause();
          }
        } catch (err) {
          util2.destroy(this, err);
        }
      };
      const onDrain = function() {
        if (finished2) {
          return;
        }
        if (body.resume) {
          body.resume();
        }
      };
      const onClose = function() {
        queueMicrotask(() => {
          body.removeListener("error", onFinished);
        });
        if (!finished2) {
          const err = new RequestAbortedError();
          queueMicrotask(() => onFinished(err));
        }
      };
      const onFinished = function(err) {
        if (finished2) {
          return;
        }
        finished2 = true;
        assert8(socket.destroyed || socket[kWriting] && client[kRunning] <= 1);
        socket.off("drain", onDrain).off("error", onFinished);
        body.removeListener("data", onData).removeListener("end", onFinished).removeListener("close", onClose);
        if (!err) {
          try {
            writer.end();
          } catch (er) {
            err = er;
          }
        }
        writer.destroy(err);
        if (err && (err.code !== "UND_ERR_INFO" || err.message !== "reset")) {
          util2.destroy(body, err);
        } else {
          util2.destroy(body);
        }
      };
      body.on("data", onData).on("end", onFinished).on("error", onFinished).on("close", onClose);
      if (body.resume) {
        body.resume();
      }
      socket.on("drain", onDrain).on("error", onFinished);
      if (body.errorEmitted ?? body.errored) {
        setImmediate(onFinished, body.errored);
      } else if (body.endEmitted ?? body.readableEnded) {
        setImmediate(onFinished, null);
      }
      if (body.closeEmitted ?? body.closed) {
        setImmediate(onClose);
      }
    }
    function writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload) {
      try {
        if (!body) {
          if (contentLength === 0) {
            socket.write(`${header}content-length: 0\r
\r
`, "latin1");
          } else {
            assert8(contentLength === null, "no body must not have content length");
            socket.write(`${header}\r
`, "latin1");
          }
        } else if (util2.isBuffer(body)) {
          assert8(contentLength === body.byteLength, "buffer body must have content length");
          socket.cork();
          socket.write(`${header}content-length: ${contentLength}\r
\r
`, "latin1");
          socket.write(body);
          socket.uncork();
          request.onBodySent(body);
          if (!expectsPayload && request.reset !== false) {
            socket[kReset] = true;
          }
        }
        request.onRequestSent();
        client[kResume]();
      } catch (err) {
        abort(err);
      }
    }
    async function writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload) {
      assert8(contentLength === body.size, "blob body must have content length");
      try {
        if (contentLength != null && contentLength !== body.size) {
          throw new RequestContentLengthMismatchError();
        }
        const buffer2 = Buffer.from(await body.arrayBuffer());
        socket.cork();
        socket.write(`${header}content-length: ${contentLength}\r
\r
`, "latin1");
        socket.write(buffer2);
        socket.uncork();
        request.onBodySent(buffer2);
        request.onRequestSent();
        if (!expectsPayload && request.reset !== false) {
          socket[kReset] = true;
        }
        client[kResume]();
      } catch (err) {
        abort(err);
      }
    }
    async function writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload) {
      assert8(contentLength !== 0 || client[kRunning] === 0, "iterator body cannot be pipelined");
      let callback = null;
      function onDrain() {
        if (callback) {
          const cb = callback;
          callback = null;
          cb();
        }
      }
      const waitForDrain = () => new Promise((resolve, reject) => {
        assert8(callback === null);
        if (socket[kError]) {
          reject(socket[kError]);
        } else {
          callback = resolve;
        }
      });
      socket.on("close", onDrain).on("drain", onDrain);
      const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header });
      try {
        for await (const chunk of body) {
          if (socket[kError]) {
            throw socket[kError];
          }
          if (!writer.write(chunk)) {
            await waitForDrain();
          }
        }
        writer.end();
      } catch (err) {
        writer.destroy(err);
      } finally {
        socket.off("close", onDrain).off("drain", onDrain);
      }
    }
    var AsyncWriter = class {
      /**
       *
       * @param {object} arg
       * @param {AbortCallback} arg.abort
       * @param {import('net').Socket} arg.socket
       * @param {import('../core/request.js')} arg.request
       * @param {number} arg.contentLength
       * @param {import('./client.js')} arg.client
       * @param {boolean} arg.expectsPayload
       * @param {string} arg.header
       */
      constructor({ abort, socket, request, contentLength, client, expectsPayload, header }) {
        this.socket = socket;
        this.request = request;
        this.contentLength = contentLength;
        this.client = client;
        this.bytesWritten = 0;
        this.expectsPayload = expectsPayload;
        this.header = header;
        this.abort = abort;
        socket[kWriting] = true;
      }
      /**
       * @param {string|Uint8Array} chunk
       * @returns
       */
      write(chunk) {
        const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this;
        if (socket[kError]) {
          throw socket[kError];
        }
        if (socket.destroyed) {
          return false;
        }
        const len = chunk instanceof Uint8Array ? chunk.byteLength : Buffer.byteLength(chunk);
        if (!len) {
          return true;
        }
        if (contentLength !== null && bytesWritten + len > contentLength) {
          if (client[kStrictContentLength]) {
            throw new RequestContentLengthMismatchError();
          }
          process.emitWarning(new RequestContentLengthMismatchError());
        }
        socket.cork();
        if (bytesWritten === 0) {
          if (!expectsPayload && request.reset !== false) {
            socket[kReset] = true;
          }
          if (contentLength === null) {
            socket.write(`${header}transfer-encoding: chunked\r
`, "latin1");
          } else {
            socket.write(`${header}content-length: ${contentLength}\r
\r
`, "latin1");
          }
        }
        if (contentLength === null) {
          socket.write(`\r
${len.toString(16)}\r
`, "latin1");
        }
        this.bytesWritten += len;
        const ret = socket.write(chunk);
        socket.uncork();
        request.onBodySent(chunk);
        if (!ret) {
          if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
            if (socket[kParser].timeout.refresh) {
              socket[kParser].timeout.refresh();
            }
          }
        }
        return ret;
      }
      /**
       * @returns {void}
       */
      end() {
        const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this;
        request.onRequestSent();
        socket[kWriting] = false;
        if (socket[kError]) {
          throw socket[kError];
        }
        if (socket.destroyed) {
          return;
        }
        if (bytesWritten === 0) {
          if (expectsPayload) {
            socket.write(`${header}content-length: 0\r
\r
`, "latin1");
          } else {
            socket.write(`${header}\r
`, "latin1");
          }
        } else if (contentLength === null) {
          socket.write("\r\n0\r\n\r\n", "latin1");
        }
        if (contentLength !== null && bytesWritten !== contentLength) {
          if (client[kStrictContentLength]) {
            throw new RequestContentLengthMismatchError();
          } else {
            process.emitWarning(new RequestContentLengthMismatchError());
          }
        }
        if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
          if (socket[kParser].timeout.refresh) {
            socket[kParser].timeout.refresh();
          }
        }
        client[kResume]();
      }
      /**
       * @param {Error} [err]
       * @returns {void}
       */
      destroy(err) {
        const { socket, client, abort } = this;
        socket[kWriting] = false;
        if (err) {
          assert8(client[kRunning] <= 1, "pipeline should only contain this request");
          abort(err);
        }
      }
    };
    module.exports = connectH1;
  }
});

// node_modules/undici/lib/dispatcher/client-h2.js
var require_client_h2 = __commonJS({
  "node_modules/undici/lib/dispatcher/client-h2.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var { pipeline } = __require("stream");
    var util2 = require_util();
    var {
      RequestContentLengthMismatchError,
      RequestAbortedError,
      SocketError,
      InformationalError,
      InvalidArgumentError
    } = require_errors();
    var {
      kUrl,
      kReset,
      kClient,
      kRunning,
      kPending,
      kQueue,
      kPendingIdx,
      kRunningIdx,
      kError,
      kSocket,
      kStrictContentLength,
      kOnError,
      kMaxConcurrentStreams,
      kPingInterval,
      kHTTP2Session,
      kHTTP2InitialWindowSize,
      kHTTP2ConnectionWindowSize,
      kResume,
      kSize,
      kHTTPContext,
      kClosed,
      kBodyTimeout,
      kEnableConnectProtocol,
      kRemoteSettings,
      kHTTP2Stream,
      kHTTP2SessionState
    } = require_symbols();
    var { channels } = require_diagnostics();
    var kOpenStreams = /* @__PURE__ */ Symbol("open streams");
    var kRequestStreamId = /* @__PURE__ */ Symbol("request stream id");
    var kRequestStream = /* @__PURE__ */ Symbol("request stream");
    var kRequestStreamCleanup = /* @__PURE__ */ Symbol("request stream cleanup");
    var kRequestStreamOnData = /* @__PURE__ */ Symbol("request stream on data");
    var kRequestStreamOnCloseError = /* @__PURE__ */ Symbol("request stream on close error");
    var kReceivedGoAway = /* @__PURE__ */ Symbol("received goaway");
    var extractBody;
    var http2;
    try {
      http2 = __require("http2");
    } catch {
      http2 = { constants: {} };
    }
    var {
      constants: {
        HTTP2_HEADER_AUTHORITY,
        HTTP2_HEADER_METHOD,
        HTTP2_HEADER_PATH,
        HTTP2_HEADER_SCHEME,
        HTTP2_HEADER_CONTENT_LENGTH,
        HTTP2_HEADER_EXPECT,
        HTTP2_HEADER_STATUS,
        HTTP2_HEADER_PROTOCOL,
        NGHTTP2_NO_ERROR,
        NGHTTP2_REFUSED_STREAM
      }
    } = http2;
    function getGoAwayError(session, errorCode) {
      return session[kError] || (errorCode === NGHTTP2_NO_ERROR ? new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`) : new SocketError(`HTTP/2: "GOAWAY" frame received with code ${errorCode}`, util2.getSocketInfo(session[kSocket])));
    }
    function getGoAwayPendingIdx(client, lastStreamID) {
      const maxAcceptedStreamID = Number.isInteger(lastStreamID) ? lastStreamID : Number.MAX_SAFE_INTEGER;
      for (let i = client[kRunningIdx]; i < client[kPendingIdx]; i++) {
        const request = client[kQueue][i];
        if (request == null) {
          continue;
        }
        if (typeof request[kRequestStreamId] !== "number" || request[kRequestStreamId] > maxAcceptedStreamID) {
          return i;
        }
      }
      return client[kPendingIdx];
    }
    function detachRequestFromStream(request) {
      request[kRequestStreamId] = null;
      request[kRequestStream] = null;
      request[kRequestStreamCleanup] = null;
    }
    function bindRequestToStream(request, stream, cleanup) {
      const previousCleanup = request[kRequestStreamCleanup];
      detachRequestFromStream(request);
      previousCleanup?.();
      request[kRequestStreamId] = stream.id;
      request[kRequestStream] = stream;
      request[kRequestStreamCleanup] = cleanup;
    }
    function clearRequestStream(request) {
      const cleanup = request[kRequestStreamCleanup];
      detachRequestFromStream(request);
      cleanup?.();
    }
    function canRetryRequestAfterGoAway(request) {
      const { body } = request;
      return body == null || util2.isBuffer(body) || util2.isBlobLike(body);
    }
    function closeRequestStream(request, code = NGHTTP2_REFUSED_STREAM) {
      const stream = request[kRequestStream];
      clearRequestStream(request);
      if (stream != null && !stream.destroyed && !stream.closed) {
        try {
          stream.close(code);
        } catch {
        }
      }
    }
    function connectH2(client, socket) {
      client[kSocket] = socket;
      const http2InitialWindowSize = client[kHTTP2InitialWindowSize];
      const http2ConnectionWindowSize = client[kHTTP2ConnectionWindowSize];
      const session = http2.connect(client[kUrl], {
        createConnection: () => socket,
        peerMaxConcurrentStreams: client[kMaxConcurrentStreams],
        settings: {
          // TODO(metcoder95): add support for PUSH
          enablePush: false,
          ...http2InitialWindowSize != null ? { initialWindowSize: http2InitialWindowSize } : null
        }
      });
      client[kSocket] = socket;
      session[kOpenStreams] = 0;
      session[kClient] = client;
      session[kSocket] = socket;
      session[kHTTP2SessionState] = {
        ping: {
          interval: client[kPingInterval] === 0 ? null : setInterval(onHttp2SendPing, client[kPingInterval], session).unref()
        }
      };
      session[kReceivedGoAway] = false;
      session[kEnableConnectProtocol] = false;
      session[kRemoteSettings] = false;
      if (http2ConnectionWindowSize) {
        util2.addListener(session, "connect", applyConnectionWindowSize.bind(session, http2ConnectionWindowSize));
      }
      util2.addListener(session, "error", onHttp2SessionError);
      util2.addListener(session, "frameError", onHttp2FrameError);
      util2.addListener(session, "end", onHttp2SessionEnd);
      util2.addListener(session, "goaway", onHttp2SessionGoAway);
      util2.addListener(session, "close", onHttp2SessionClose);
      util2.addListener(session, "remoteSettings", onHttp2RemoteSettings);
      session.unref();
      client[kHTTP2Session] = session;
      socket[kHTTP2Session] = session;
      util2.addListener(socket, "error", onHttp2SocketError);
      util2.addListener(socket, "end", onHttp2SocketEnd);
      util2.addListener(socket, "close", onHttp2SocketClose);
      socket[kClosed] = false;
      socket.on("close", onSocketClose);
      return {
        version: "h2",
        defaultPipelining: Infinity,
        /**
         * @param {import('../core/request.js')} request
         * @returns {boolean}
        */
        write(request) {
          return writeH2(client, request);
        },
        /**
         * @returns {void}
         */
        resume() {
          resumeH2(client);
        },
        /**
         * @param {Error | null} err
         * @param {() => void} callback
         */
        destroy(err, callback) {
          if (socket[kClosed]) {
            queueMicrotask(callback);
          } else {
            socket.destroy(err).on("close", callback);
          }
        },
        /**
         * @type {boolean}
         */
        get destroyed() {
          return socket.destroyed;
        },
        /**
         * @param {import('../core/request.js')} request
         * @returns {boolean}
        */
        busy(request) {
          if (session[kRemoteSettings] === false && client[kRunning] > 0) {
            return true;
          }
          if (client[kRunning] >= client[kMaxConcurrentStreams]) {
            return true;
          }
          if (request != null) {
            if (client[kRunning] > 0) {
              if (request.idempotent === false) return true;
              if ((request.upgrade === "websocket" || request.method === "CONNECT") && session[kRemoteSettings] === false) return true;
              if (util2.bodyLength(request.body) !== 0 && (util2.isStream(request.body) || util2.isAsyncIterable(request.body) || util2.isFormDataLike(request.body))) return true;
            } else {
              return (request.upgrade === "websocket" || request.method === "CONNECT") && session[kRemoteSettings] === false;
            }
          }
          return false;
        }
      };
    }
    function resumeH2(client) {
      const socket = client[kSocket];
      if (socket?.destroyed === false) {
        if (client[kSize] === 0 || client[kMaxConcurrentStreams] === 0) {
          socket.unref();
          client[kHTTP2Session].unref();
        } else {
          socket.ref();
          client[kHTTP2Session].ref();
        }
      }
    }
    function applyConnectionWindowSize(connectionWindowSize) {
      try {
        if (typeof this.setLocalWindowSize === "function") {
          this.setLocalWindowSize(connectionWindowSize);
        }
      } catch {
      }
    }
    function onHttp2RemoteSettings(settings) {
      this[kClient][kMaxConcurrentStreams] = settings.maxConcurrentStreams ?? this[kClient][kMaxConcurrentStreams];
      if (this[kRemoteSettings] === true && this[kEnableConnectProtocol] === true && settings.enableConnectProtocol === false) {
        const err = new InformationalError("HTTP/2: Server disabled extended CONNECT protocol against RFC-8441");
        this[kSocket][kError] = err;
        this[kClient][kOnError](err);
        return;
      }
      this[kEnableConnectProtocol] = settings.enableConnectProtocol ?? this[kEnableConnectProtocol];
      this[kRemoteSettings] = true;
      this[kClient][kResume]();
    }
    function onHttp2SendPing(session) {
      const state = session[kHTTP2SessionState];
      if ((session.closed || session.destroyed) && state.ping.interval != null) {
        clearInterval(state.ping.interval);
        state.ping.interval = null;
        return;
      }
      session.ping(onPing.bind(session));
      function onPing(err, duration) {
        const client = this[kClient];
        const socket = this[kSocket];
        if (err != null) {
          const error = new InformationalError(`HTTP/2: "PING" errored - type ${err.message}`);
          socket[kError] = error;
          client[kOnError](error);
        } else {
          client.emit("ping", duration);
        }
      }
    }
    function onHttp2SessionError(err) {
      assert8(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
      this[kSocket][kError] = err;
      this[kClient][kOnError](err);
    }
    function onHttp2FrameError(type, code, id) {
      if (id === 0) {
        const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`);
        this[kSocket][kError] = err;
        this[kClient][kOnError](err);
      }
    }
    function onHttp2SessionEnd() {
      const err = new SocketError("other side closed", util2.getSocketInfo(this[kSocket]));
      this.destroy(err);
      util2.destroy(this[kSocket], err);
    }
    function onHttp2SessionGoAway(errorCode, lastStreamID) {
      if (this[kReceivedGoAway]) {
        return;
      }
      this[kReceivedGoAway] = true;
      const err = getGoAwayError(this, errorCode);
      const client = this[kClient];
      const previousPendingIdx = client[kPendingIdx];
      const pendingIdx = getGoAwayPendingIdx(client, lastStreamID);
      const retriableRequests = [];
      for (let i = pendingIdx; i < previousPendingIdx; i++) {
        const request = client[kQueue][i];
        if (request != null) {
          closeRequestStream(request);
          if (canRetryRequestAfterGoAway(request)) {
            retriableRequests.push(request);
          } else {
            util2.errorRequest(client, request, err);
          }
        }
      }
      if (pendingIdx !== previousPendingIdx) {
        const remainingPendingRequests = client[kQueue].slice(previousPendingIdx);
        client[kQueue].length = pendingIdx;
        client[kQueue].push(...retriableRequests, ...remainingPendingRequests);
      }
      if (client[kHTTP2Session] === this) {
        client[kSocket] = null;
        client[kHTTPContext] = null;
        client[kHTTP2Session] = null;
      }
      if (!this.closed && !this.destroyed) {
        this.close();
      }
      client[kPendingIdx] = pendingIdx;
      client.emit("disconnect", client[kUrl], [client], err);
      client[kResume]();
    }
    function onHttp2SessionClose() {
      const { [kClient]: client, [kHTTP2SessionState]: state, [kSocket]: socket } = this;
      const err = socket[kError] || this[kError] || new SocketError("closed", util2.getSocketInfo(socket));
      if (client[kHTTP2Session] === this) {
        client[kSocket] = null;
        client[kHTTPContext] = null;
        client[kHTTP2Session] = null;
      }
      if (state.ping.interval != null) {
        clearInterval(state.ping.interval);
        state.ping.interval = null;
      }
      if (client.destroyed) {
        assert8(client[kPending] === 0);
        const requests = client[kQueue].splice(client[kRunningIdx]);
        for (let i = 0; i < requests.length; i++) {
          const request = requests[i];
          util2.errorRequest(client, request, err);
        }
      }
    }
    function onHttp2SocketClose() {
      const err = this[kError] || new SocketError("closed", util2.getSocketInfo(this));
      const session = this[kHTTP2Session];
      const client = session[kClient];
      if (client[kSocket] !== this) {
        if (session[kReceivedGoAway] || client[kHTTP2Session] != null && client[kHTTP2Session] !== session) {
          return;
        }
      }
      client[kSocket] = null;
      client[kHTTPContext] = null;
      if (client[kHTTP2Session] === session) {
        client[kHTTP2Session] = null;
      }
      session.destroy(err);
      client[kPendingIdx] = client[kRunningIdx];
      assert8(client[kRunning] === 0);
      client.emit("disconnect", client[kUrl], [client], err);
      client[kResume]();
    }
    function onHttp2SocketError(err) {
      assert8(err.code !== "ERR_TLS_CERT_ALTNAME_INVALID");
      this[kError] = err;
      this[kClient][kOnError](err);
    }
    function onHttp2SocketEnd() {
      util2.destroy(this, new SocketError("other side closed", util2.getSocketInfo(this)));
    }
    function onSocketClose() {
      this[kClosed] = true;
    }
    function noop() {
    }
    function closeStreamSession(stream) {
      const session = stream[kHTTP2Session];
      stream[kHTTP2Session] = null;
      session[kOpenStreams] -= 1;
      if (session[kOpenStreams] === 0) {
        session.unref();
      }
    }
    function onUpgradeStreamClose() {
      this.off("error", noop);
      const failUpgradeStream = this[kRequestStreamOnCloseError];
      this[kRequestStreamOnCloseError] = null;
      failUpgradeStream(new InformationalError("HTTP/2: stream closed before response headers"));
      closeStreamSession(this);
    }
    function onRequestStreamClose() {
      const onData = this[kRequestStreamOnData];
      this[kRequestStreamOnData] = null;
      this.off("data", onData);
      this.off("error", noop);
      closeStreamSession(this);
    }
    function shouldSendContentLength(method) {
      return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
    }
    function writeH2(client, request) {
      const requestTimeout = request.bodyTimeout ?? client[kBodyTimeout];
      const session = client[kHTTP2Session];
      const { method, path: path2, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
      let { body } = request;
      if (upgrade != null && upgrade !== "websocket") {
        util2.errorRequest(client, request, new InvalidArgumentError(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
        return false;
      }
      const headers = {};
      for (let n = 0; n < reqHeaders.length; n += 2) {
        const key = reqHeaders[n + 0];
        const val = reqHeaders[n + 1];
        if (key === "cookie") {
          if (headers[key] != null) {
            headers[key] = Array.isArray(headers[key]) ? (headers[key].push(val), headers[key]) : [headers[key], val];
          } else {
            headers[key] = val;
          }
          continue;
        }
        if (Array.isArray(val)) {
          for (let i = 0; i < val.length; i++) {
            if (headers[key]) {
              headers[key] += `, ${val[i]}`;
            } else {
              headers[key] = val[i];
            }
          }
        } else if (headers[key]) {
          headers[key] += `, ${val}`;
        } else {
          headers[key] = val;
        }
      }
      let stream = null;
      const { hostname, port } = client[kUrl];
      headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ""}`;
      headers[HTTP2_HEADER_METHOD] = method;
      let requestFinalized = false;
      const finalizeRequest = (resetPendingIdx = false) => {
        if (requestFinalized) {
          return;
        }
        requestFinalized = true;
        client[kQueue][client[kRunningIdx]++] = null;
        if (resetPendingIdx) {
          client[kPendingIdx] = client[kRunningIdx];
        }
        client[kResume]();
      };
      const abort = (err, resetPendingIdx = false) => {
        if (request.aborted || request.completed) {
          return;
        }
        err = err || new RequestAbortedError();
        util2.errorRequest(client, request, err);
        if (stream != null) {
          clearRequestStream(request);
          stream.close();
          client[kOnError](err);
          finalizeRequest(resetPendingIdx);
        }
        util2.destroy(body, err);
      };
      const requestStream = (headers2, options) => {
        try {
          return session.request(headers2, options);
        } catch (err) {
          if (err?.code !== "ERR_HTTP2_INVALID_CONNECTION_HEADERS") {
            throw err;
          }
          const wrappedErr = new InformationalError(err.message, { cause: err });
          session[kError] = wrappedErr;
          session[kSocket][kError] = wrappedErr;
          session.destroy(wrappedErr);
          util2.destroy(session[kSocket], wrappedErr);
          abort(wrappedErr);
          return null;
        }
      };
      try {
        request.onRequestStart(abort, null);
      } catch (err) {
        util2.errorRequest(client, request, err);
      }
      if (request.aborted) {
        return false;
      }
      if (upgrade || method === "CONNECT") {
        session.ref();
        const setupUpgradeStream = (stream2) => {
          let responseReceived2 = false;
          const removeUpgradeStreamListeners = () => {
            stream2.off("response", onUpgradeResponse);
            stream2.off("error", onUpgradeStreamError);
            stream2.off("end", onUpgradeStreamEnd);
            stream2.off("timeout", onUpgradeStreamTimeout);
            stream2.off("error", noop);
          };
          const releaseUpgradeStream = () => {
            if (request[kRequestStream] === stream2) {
              detachRequestFromStream(request);
            }
            removeUpgradeStreamListeners();
            if (!stream2.destroyed && !stream2.closed) {
              stream2.once("error", noop);
            }
          };
          const failUpgradeStream = (err) => {
            if (responseReceived2 || request.aborted || request.completed) {
              return;
            }
            releaseUpgradeStream();
            abort(err, true);
          };
          const onUpgradeStreamError = () => {
            if (typeof stream2.rstCode === "number" && stream2.rstCode !== 0) {
              failUpgradeStream(new InformationalError(`HTTP/2: "stream error" received - code ${stream2.rstCode}`));
            } else {
              failUpgradeStream(new InformationalError("HTTP/2: stream errored before response headers"));
            }
          };
          const onUpgradeStreamEnd = () => {
            failUpgradeStream(new InformationalError("HTTP/2: stream half-closed (remote)"));
          };
          const onUpgradeStreamTimeout = () => {
            failUpgradeStream(new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`));
          };
          const onUpgradeResponse = (headers2, _flags) => {
            responseReceived2 = true;
            const statusCode = headers2[HTTP2_HEADER_STATUS];
            delete headers2[HTTP2_HEADER_STATUS];
            request.onRequestUpgrade(statusCode, headers2, stream2);
            if (request.aborted || request.completed) {
              return;
            }
            removeUpgradeStreamListeners();
            detachRequestFromStream(request);
            finalizeRequest();
          };
          bindRequestToStream(request, stream2, releaseUpgradeStream);
          stream2.once("response", onUpgradeResponse);
          stream2.on("error", onUpgradeStreamError);
          stream2.once("end", onUpgradeStreamEnd);
          stream2.on("timeout", onUpgradeStreamTimeout);
          stream2[kHTTP2Session] = session;
          stream2[kRequestStreamOnCloseError] = failUpgradeStream;
          stream2.once("close", onUpgradeStreamClose);
          ++session[kOpenStreams];
          stream2.setTimeout(requestTimeout);
        };
        if (upgrade === "websocket") {
          if (session[kEnableConnectProtocol] === false) {
            util2.errorRequest(client, request, new InformationalError("HTTP/2: Extended CONNECT protocol not supported by server"));
            session.unref();
            return false;
          }
          headers[HTTP2_HEADER_METHOD] = "CONNECT";
          headers[HTTP2_HEADER_PROTOCOL] = "websocket";
          headers[HTTP2_HEADER_PATH] = path2;
          if (protocol === "ws:" || protocol === "wss:") {
            headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
          } else {
            headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
          }
          stream = requestStream(headers, { endStream: false, signal });
          if (stream == null) {
            session.unref();
            return false;
          }
          stream[kHTTP2Stream] = true;
          setupUpgradeStream(stream);
          return true;
        }
        stream = requestStream(headers, { endStream: false, signal });
        if (stream == null) {
          session.unref();
          return false;
        }
        stream[kHTTP2Stream] = true;
        setupUpgradeStream(stream);
        return true;
      }
      headers[HTTP2_HEADER_PATH] = path2;
      headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
      const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
      if (body && typeof body.read === "function") {
        body.read(0);
      }
      let contentLength = util2.bodyLength(body);
      if (util2.isFormDataLike(body)) {
        extractBody ??= require_body().extractBody;
        const [bodyStream, contentType] = extractBody(body);
        headers["content-type"] = contentType;
        body = bodyStream.stream;
        contentLength = bodyStream.length;
      }
      if (contentLength == null) {
        contentLength = request.contentLength;
      }
      if (contentLength === 0 && !expectsPayload) {
        contentLength = null;
      }
      if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {
        if (client[kStrictContentLength]) {
          util2.errorRequest(client, request, new RequestContentLengthMismatchError());
          return false;
        }
        process.emitWarning(new RequestContentLengthMismatchError());
      }
      if (contentLength != null) {
        assert8(body || contentLength === 0, "no body must not have content length");
        headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`;
      }
      session.ref();
      if (channels.sendHeaders.hasSubscribers) {
        let header = "";
        for (const key in headers) {
          header += `${key}: ${headers[key]}\r
`;
        }
        channels.sendHeaders.publish({ request, headers: header, socket: session[kSocket] });
      }
      const shouldEndStream = body === null;
      if (expectContinue) {
        headers[HTTP2_HEADER_EXPECT] = "100-continue";
        stream = requestStream(headers, { endStream: shouldEndStream, signal });
        if (stream == null) {
          return false;
        }
        stream[kHTTP2Stream] = true;
        bindRequestToStream(request, stream, null);
      } else {
        stream = requestStream(headers, {
          endStream: shouldEndStream,
          signal
        });
        if (stream == null) {
          return false;
        }
        stream[kHTTP2Stream] = true;
        bindRequestToStream(request, stream, null);
      }
      ++session[kOpenStreams];
      stream.setTimeout(requestTimeout);
      let responseReceived = false;
      const onData = (chunk) => {
        if (request.aborted || request.completed) {
          return;
        }
        if (request.onResponseData(chunk) === false) {
          stream.pause();
        }
      };
      const removeRequestStreamListeners = () => {
        stream.off("error", noop);
        stream.off("continue", writeBodyH2);
        stream.off("response", onResponse);
        stream.off("end", onEnd);
        stream.off("error", onError);
        stream.off("frameError", onFrameError);
        stream.off("aborted", onAborted);
        stream.off("timeout", onTimeout);
        stream.off("trailers", onTrailers);
        stream.off("data", onData);
      };
      const releaseRequestStream = () => {
        if (request[kRequestStream] === stream) {
          detachRequestFromStream(request);
        }
        removeRequestStreamListeners();
        if (!stream.destroyed && !stream.closed) {
          stream.once("error", noop);
        }
      };
      const onResponse = (headers2) => {
        stream.off("response", onResponse);
        const statusCode = headers2[HTTP2_HEADER_STATUS];
        delete headers2[HTTP2_HEADER_STATUS];
        request.onResponseStarted();
        responseReceived = true;
        if (request.aborted) {
          releaseRequestStream();
          return;
        }
        if (request.onResponseStart(Number(statusCode), headers2, stream.resume.bind(stream), "") === false) {
          stream.pause();
        }
        stream.on("data", onData);
      };
      const onEnd = () => {
        stream.off("end", onEnd);
        releaseRequestStream();
        if (responseReceived) {
          if (!request.aborted && !request.completed) {
            request.onResponseEnd({});
          }
          finalizeRequest();
        } else {
          abort(new InformationalError("HTTP/2: stream half-closed (remote)"), true);
        }
      };
      stream[kHTTP2Session] = session;
      stream[kRequestStreamOnData] = onData;
      stream.once("close", onRequestStreamClose);
      const onError = function(err) {
        stream.off("error", onError);
        releaseRequestStream();
        abort(err);
      };
      const onFrameError = (type, code) => {
        stream.off("frameError", onFrameError);
        releaseRequestStream();
        abort(new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`));
      };
      const onAborted = () => {
        stream.off("data", onData);
      };
      const onTimeout = () => {
        releaseRequestStream();
        const err = new InformationalError(`HTTP/2: "stream timeout after ${requestTimeout}"`);
        abort(err);
      };
      const onTrailers = (trailers) => {
        stream.off("trailers", onTrailers);
        if (request.aborted || request.completed) {
          return;
        }
        releaseRequestStream();
        request.onResponseEnd(trailers);
        finalizeRequest();
      };
      bindRequestToStream(request, stream, releaseRequestStream);
      if (expectContinue) {
        stream.once("continue", writeBodyH2);
      }
      stream.once("response", onResponse);
      stream.once("end", onEnd);
      stream.once("error", onError);
      stream.once("frameError", onFrameError);
      stream.on("aborted", onAborted);
      stream.on("timeout", onTimeout);
      stream.once("trailers", onTrailers);
      if (!expectContinue) {
        writeBodyH2();
      }
      return true;
      function writeBodyH2() {
        if (!body || contentLength === 0) {
          writeBuffer(
            abort,
            stream,
            null,
            client,
            request,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else if (util2.isBuffer(body)) {
          writeBuffer(
            abort,
            stream,
            body,
            client,
            request,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else if (util2.isBlobLike(body)) {
          if (typeof body.stream === "function") {
            writeIterable(
              abort,
              stream,
              body.stream(),
              client,
              request,
              client[kSocket],
              contentLength,
              expectsPayload
            );
          } else {
            writeBlob(
              abort,
              stream,
              body,
              client,
              request,
              client[kSocket],
              contentLength,
              expectsPayload
            );
          }
        } else if (util2.isStream(body)) {
          writeStream(
            abort,
            client[kSocket],
            expectsPayload,
            stream,
            body,
            client,
            request,
            contentLength
          );
        } else if (util2.isIterable(body)) {
          writeIterable(
            abort,
            stream,
            body,
            client,
            request,
            client[kSocket],
            contentLength,
            expectsPayload
          );
        } else {
          assert8(false);
        }
      }
    }
    function writeBuffer(abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
      try {
        if (body != null && util2.isBuffer(body)) {
          assert8(contentLength === body.byteLength, "buffer body must have content length");
          h2stream.cork();
          h2stream.write(body);
          h2stream.uncork();
          h2stream.end();
          request.onBodySent(body);
        }
        if (!expectsPayload) {
          socket[kReset] = true;
        }
        request.onRequestSent();
        client[kResume]();
      } catch (error) {
        abort(error);
      }
    }
    function writeStream(abort, socket, expectsPayload, h2stream, body, client, request, contentLength) {
      assert8(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
      const pipe2 = pipeline(
        body,
        h2stream,
        (err) => {
          if (err) {
            util2.destroy(pipe2, err);
            abort(err);
          } else {
            util2.removeAllListeners(pipe2);
            request.onRequestSent();
            if (!expectsPayload) {
              socket[kReset] = true;
            }
            client[kResume]();
          }
        }
      );
      util2.addListener(pipe2, "data", onPipeData);
      function onPipeData(chunk) {
        request.onBodySent(chunk);
      }
    }
    async function writeBlob(abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
      assert8(contentLength === body.size, "blob body must have content length");
      try {
        if (contentLength != null && contentLength !== body.size) {
          throw new RequestContentLengthMismatchError();
        }
        const buffer2 = Buffer.from(await body.arrayBuffer());
        h2stream.cork();
        h2stream.write(buffer2);
        h2stream.uncork();
        h2stream.end();
        request.onBodySent(buffer2);
        request.onRequestSent();
        if (!expectsPayload) {
          socket[kReset] = true;
        }
        client[kResume]();
      } catch (err) {
        abort(err);
      }
    }
    async function writeIterable(abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
      assert8(contentLength !== 0 || client[kRunning] === 0, "iterator body cannot be pipelined");
      let callback = null;
      function onDrain() {
        if (callback) {
          const cb = callback;
          callback = null;
          cb();
        }
      }
      const waitForDrain = () => new Promise((resolve, reject) => {
        assert8(callback === null);
        if (socket[kError]) {
          reject(socket[kError]);
        } else {
          callback = resolve;
        }
      });
      h2stream.on("close", onDrain).on("drain", onDrain);
      try {
        for await (const chunk of body) {
          if (socket[kError]) {
            throw socket[kError];
          }
          const res = h2stream.write(chunk);
          request.onBodySent(chunk);
          if (!res) {
            await waitForDrain();
          }
        }
        h2stream.end();
        request.onRequestSent();
        if (!expectsPayload) {
          socket[kReset] = true;
        }
        client[kResume]();
      } catch (err) {
        abort(err);
      } finally {
        h2stream.off("close", onDrain).off("drain", onDrain);
      }
    }
    module.exports = connectH2;
  }
});

// node_modules/undici/lib/dispatcher/client.js
var require_client = __commonJS({
  "node_modules/undici/lib/dispatcher/client.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var net = __require("net");
    var http2 = __require("http");
    var util2 = require_util();
    var { ClientStats } = require_stats();
    var { channels } = require_diagnostics();
    var Request2 = require_request();
    var DispatcherBase = require_dispatcher_base();
    var {
      InvalidArgumentError,
      InformationalError,
      ClientDestroyedError
    } = require_errors();
    var buildConnector = require_connect();
    var {
      kUrl,
      kServerName,
      kClient,
      kBusy,
      kConnect,
      kResuming,
      kRunning,
      kPending,
      kSize,
      kQueue,
      kConnected,
      kConnecting,
      kNeedDrain,
      kKeepAliveDefaultTimeout,
      kHostHeader,
      kPendingIdx,
      kRunningIdx,
      kError,
      kPipelining,
      kKeepAliveTimeoutValue,
      kMaxHeadersSize,
      kKeepAliveMaxTimeout,
      kKeepAliveTimeoutThreshold,
      kHeadersTimeout,
      kBodyTimeout,
      kStrictContentLength,
      kConnector,
      kMaxRequests,
      kCounter,
      kClose,
      kDestroy,
      kDispatch,
      kLocalAddress,
      kMaxResponseSize,
      kOnError,
      kHTTPContext,
      kMaxConcurrentStreams,
      kHTTP2InitialWindowSize,
      kHTTP2ConnectionWindowSize,
      kResume,
      kPingInterval
    } = require_symbols();
    var connectH1 = require_client_h1();
    var connectH2 = require_client_h2();
    var kClosedResolve = /* @__PURE__ */ Symbol("kClosedResolve");
    var getDefaultNodeMaxHeaderSize = http2 && http2.maxHeaderSize && Number.isInteger(http2.maxHeaderSize) && http2.maxHeaderSize > 0 ? () => http2.maxHeaderSize : () => {
      throw new InvalidArgumentError("http module not available or http.maxHeaderSize invalid");
    };
    var noop = () => {
    };
    function getPipelining(client) {
      return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1;
    }
    var Client = class extends DispatcherBase {
      /**
       *
       * @param {string|URL} url
       * @param {import('../../types/client.js').Client.Options} options
       */
      constructor(url, {
        maxHeaderSize,
        headersTimeout,
        socketTimeout,
        requestTimeout,
        connectTimeout,
        bodyTimeout,
        idleTimeout,
        keepAlive,
        keepAliveTimeout,
        maxKeepAliveTimeout,
        keepAliveMaxTimeout,
        keepAliveTimeoutThreshold,
        socketPath,
        pipelining,
        tls,
        strictContentLength,
        maxCachedSessions,
        connect: connect2,
        maxRequestsPerClient,
        localAddress,
        maxResponseSize,
        autoSelectFamily,
        autoSelectFamilyAttemptTimeout,
        // h2
        maxConcurrentStreams,
        allowH2,
        useH2c,
        initialWindowSize,
        connectionWindowSize,
        pingInterval,
        webSocket
      } = {}) {
        if (keepAlive !== void 0) {
          throw new InvalidArgumentError("unsupported keepAlive, use pipelining=0 instead");
        }
        if (socketTimeout !== void 0) {
          throw new InvalidArgumentError("unsupported socketTimeout, use headersTimeout & bodyTimeout instead");
        }
        if (requestTimeout !== void 0) {
          throw new InvalidArgumentError("unsupported requestTimeout, use headersTimeout & bodyTimeout instead");
        }
        if (idleTimeout !== void 0) {
          throw new InvalidArgumentError("unsupported idleTimeout, use keepAliveTimeout instead");
        }
        if (maxKeepAliveTimeout !== void 0) {
          throw new InvalidArgumentError("unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead");
        }
        if (maxHeaderSize != null) {
          if (!Number.isInteger(maxHeaderSize) || maxHeaderSize < 1) {
            throw new InvalidArgumentError("invalid maxHeaderSize");
          }
        } else {
          maxHeaderSize = getDefaultNodeMaxHeaderSize();
        }
        if (socketPath != null && typeof socketPath !== "string") {
          throw new InvalidArgumentError("invalid socketPath");
        }
        if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
          throw new InvalidArgumentError("invalid connectTimeout");
        }
        if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
          throw new InvalidArgumentError("invalid keepAliveTimeout");
        }
        if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
          throw new InvalidArgumentError("invalid keepAliveMaxTimeout");
        }
        if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
          throw new InvalidArgumentError("invalid keepAliveTimeoutThreshold");
        }
        if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
          throw new InvalidArgumentError("headersTimeout must be a positive integer or zero");
        }
        if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
          throw new InvalidArgumentError("bodyTimeout must be a positive integer or zero");
        }
        if (connect2 != null && typeof connect2 !== "function" && typeof connect2 !== "object") {
          throw new InvalidArgumentError("connect must be a function or an object");
        }
        if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
          throw new InvalidArgumentError("maxRequestsPerClient must be a positive number");
        }
        if (localAddress != null && (typeof localAddress !== "string" || net.isIP(localAddress) === 0)) {
          throw new InvalidArgumentError("localAddress must be valid string IP address");
        }
        if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
          throw new InvalidArgumentError("maxResponseSize must be a positive number");
        }
        if (autoSelectFamilyAttemptTimeout != null && (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)) {
          throw new InvalidArgumentError("autoSelectFamilyAttemptTimeout must be a positive number");
        }
        if (allowH2 != null && typeof allowH2 !== "boolean") {
          throw new InvalidArgumentError("allowH2 must be a valid boolean value");
        }
        if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== "number" || maxConcurrentStreams < 1)) {
          throw new InvalidArgumentError("maxConcurrentStreams must be a positive integer, greater than 0");
        }
        if (useH2c != null && typeof useH2c !== "boolean") {
          throw new InvalidArgumentError("useH2c must be a valid boolean value");
        }
        if (initialWindowSize != null && (!Number.isInteger(initialWindowSize) || initialWindowSize < 1)) {
          throw new InvalidArgumentError("initialWindowSize must be a positive integer, greater than 0");
        }
        if (connectionWindowSize != null && (!Number.isInteger(connectionWindowSize) || connectionWindowSize < 1)) {
          throw new InvalidArgumentError("connectionWindowSize must be a positive integer, greater than 0");
        }
        if (pingInterval != null && (typeof pingInterval !== "number" || !Number.isInteger(pingInterval) || pingInterval < 0)) {
          throw new InvalidArgumentError("pingInterval must be a positive integer, greater or equal to 0");
        }
        super({ webSocket });
        if (typeof connect2 !== "function") {
          connect2 = buildConnector({
            ...tls,
            maxCachedSessions,
            allowH2,
            useH2c,
            socketPath,
            timeout: connectTimeout,
            ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
            ...connect2
          });
        } else {
          const customConnect = connect2;
          connect2 = (opts, callback) => customConnect({
            ...opts,
            ...socketPath != null ? { socketPath } : null,
            ...allowH2 != null ? { allowH2 } : null
          }, callback);
        }
        this[kUrl] = util2.parseOrigin(url);
        this[kConnector] = connect2;
        this[kPipelining] = pipelining != null ? pipelining : 1;
        this[kMaxHeadersSize] = maxHeaderSize;
        this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout;
        this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 6e5 : keepAliveMaxTimeout;
        this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold;
        this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout];
        this[kServerName] = null;
        this[kLocalAddress] = localAddress != null ? localAddress : null;
        this[kResuming] = 0;
        this[kNeedDrain] = 0;
        this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ""}\r
`;
        this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 3e5;
        this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 3e5;
        this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength;
        this[kMaxRequests] = maxRequestsPerClient;
        this[kClosedResolve] = null;
        this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1;
        this[kHTTPContext] = null;
        this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100;
        this[kHTTP2InitialWindowSize] = initialWindowSize != null ? initialWindowSize : 262144;
        this[kHTTP2ConnectionWindowSize] = connectionWindowSize != null ? connectionWindowSize : 524288;
        this[kPingInterval] = pingInterval != null ? pingInterval : 6e4;
        this[kQueue] = [];
        this[kRunningIdx] = 0;
        this[kPendingIdx] = 0;
        this[kResume] = (sync) => resume(this, sync);
        this[kOnError] = (err) => onError(this, err);
      }
      get pipelining() {
        return this[kPipelining];
      }
      set pipelining(value) {
        this[kPipelining] = value;
        this[kResume](true);
      }
      get stats() {
        return new ClientStats(this);
      }
      get [kPending]() {
        return this[kQueue].length - this[kPendingIdx];
      }
      get [kRunning]() {
        return this[kPendingIdx] - this[kRunningIdx];
      }
      get [kSize]() {
        return this[kQueue].length - this[kRunningIdx];
      }
      get [kConnected]() {
        return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed;
      }
      get [kBusy]() {
        return Boolean(
          this[kHTTPContext]?.busy(null) || this[kSize] >= (getPipelining(this) || 1) || this[kPending] > 0
        );
      }
      [kConnect](cb) {
        connect(this);
        this.once("connect", cb);
      }
      [kDispatch](opts, handler) {
        const request = new Request2(this[kUrl].origin, opts, handler);
        this[kQueue].push(request);
        if (this[kResuming]) {
        } else if (util2.bodyLength(request.body) == null && util2.isIterable(request.body)) {
          this[kResuming] = 1;
          queueMicrotask(() => resume(this));
        } else {
          this[kResume](true);
        }
        if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
          this[kNeedDrain] = 2;
        }
        return this[kNeedDrain] < 2;
      }
      [kClose]() {
        return new Promise((resolve) => {
          if (this[kSize]) {
            this[kClosedResolve] = resolve;
          } else {
            resolve(null);
          }
        });
      }
      [kDestroy](err) {
        return new Promise((resolve) => {
          const requests = this[kQueue].splice(this[kPendingIdx]);
          for (let i = 0; i < requests.length; i++) {
            const request = requests[i];
            util2.errorRequest(this, request, err);
          }
          const callback = () => {
            if (this[kClosedResolve]) {
              this[kClosedResolve]();
              this[kClosedResolve] = null;
            }
            resolve(null);
          };
          if (this[kHTTPContext]) {
            this[kHTTPContext].destroy(err, callback);
            this[kHTTPContext] = null;
          } else {
            queueMicrotask(callback);
          }
          this[kResume]();
        });
      }
    };
    function onError(client, err) {
      if (client[kRunning] === 0 && err.code !== "UND_ERR_INFO" && err.code !== "UND_ERR_SOCKET") {
        assert8(client[kPendingIdx] === client[kRunningIdx]);
        const requests = client[kQueue].splice(client[kRunningIdx]);
        for (let i = 0; i < requests.length; i++) {
          const request = requests[i];
          util2.errorRequest(client, request, err);
        }
        assert8(client[kSize] === 0);
      }
    }
    function connect(client) {
      assert8(!client[kConnecting]);
      assert8(!client[kHTTPContext]);
      let { host, hostname, protocol, port } = client[kUrl];
      if (hostname[0] === "[") {
        const idx = hostname.indexOf("]");
        assert8(idx !== -1);
        const ip = hostname.substring(1, idx);
        assert8(net.isIPv6(ip));
        hostname = ip;
      }
      client[kConnecting] = true;
      if (channels.beforeConnect.hasSubscribers) {
        channels.beforeConnect.publish({
          connectParams: {
            host,
            hostname,
            protocol,
            port,
            version: client[kHTTPContext]?.version,
            servername: client[kServerName],
            localAddress: client[kLocalAddress]
          },
          connector: client[kConnector]
        });
      }
      try {
        client[kConnector]({
          host,
          hostname,
          protocol,
          port,
          servername: client[kServerName],
          localAddress: client[kLocalAddress]
        }, (err, socket) => {
          if (err) {
            handleConnectError(client, err, { host, hostname, protocol, port });
            client[kResume]();
            return;
          }
          if (client.destroyed) {
            util2.destroy(socket.on("error", noop), new ClientDestroyedError());
            client[kResume]();
            return;
          }
          assert8(socket);
          try {
            client[kHTTPContext] = socket.alpnProtocol === "h2" ? connectH2(client, socket) : connectH1(client, socket);
          } catch (err2) {
            socket.destroy().on("error", noop);
            handleConnectError(client, err2, { host, hostname, protocol, port });
            client[kResume]();
            return;
          }
          client[kConnecting] = false;
          socket[kCounter] = 0;
          socket[kMaxRequests] = client[kMaxRequests];
          socket[kClient] = client;
          socket[kError] = null;
          if (channels.connected.hasSubscribers) {
            channels.connected.publish({
              connectParams: {
                host,
                hostname,
                protocol,
                port,
                version: client[kHTTPContext]?.version,
                servername: client[kServerName],
                localAddress: client[kLocalAddress]
              },
              connector: client[kConnector],
              socket
            });
          }
          client.emit("connect", client[kUrl], [client]);
          client[kResume]();
        });
      } catch (err) {
        handleConnectError(client, err, { host, hostname, protocol, port });
        client[kResume]();
      }
    }
    function handleConnectError(client, err, { host, hostname, protocol, port }) {
      if (client.destroyed) {
        return;
      }
      client[kConnecting] = false;
      if (channels.connectError.hasSubscribers) {
        channels.connectError.publish({
          connectParams: {
            host,
            hostname,
            protocol,
            port,
            version: client[kHTTPContext]?.version,
            servername: client[kServerName],
            localAddress: client[kLocalAddress]
          },
          connector: client[kConnector],
          error: err
        });
      }
      if (err.code === "ERR_TLS_CERT_ALTNAME_INVALID") {
        assert8(client[kRunning] === 0);
        while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
          const request = client[kQueue][client[kPendingIdx]++];
          util2.errorRequest(client, request, err);
        }
      } else {
        onError(client, err);
      }
      client.emit("connectionError", client[kUrl], [client], err);
    }
    function emitDrain(client) {
      client[kNeedDrain] = 0;
      client.emit("drain", client[kUrl], [client]);
    }
    function resume(client, sync) {
      if (client[kResuming] === 2) {
        return;
      }
      client[kResuming] = 2;
      _resume(client, sync);
      client[kResuming] = 0;
      if (client[kRunningIdx] > 256) {
        client[kQueue].splice(0, client[kRunningIdx]);
        client[kPendingIdx] -= client[kRunningIdx];
        client[kRunningIdx] = 0;
      }
    }
    function _resume(client, sync) {
      while (true) {
        if (client.destroyed) {
          assert8(client[kPending] === 0);
          return;
        }
        if (client[kClosedResolve] && !client[kSize]) {
          client[kClosedResolve]();
          client[kClosedResolve] = null;
          return;
        }
        if (client[kHTTPContext]) {
          client[kHTTPContext].resume();
        }
        if (client[kBusy]) {
          client[kNeedDrain] = 2;
        } else if (client[kNeedDrain] === 2) {
          if (sync) {
            client[kNeedDrain] = 1;
            queueMicrotask(() => emitDrain(client));
          } else {
            emitDrain(client);
          }
          continue;
        }
        if (client[kPending] === 0) {
          return;
        }
        if (client[kRunning] >= (getPipelining(client) || 1)) {
          return;
        }
        const request = client[kQueue][client[kPendingIdx]];
        if (request === null) {
          return;
        }
        if (client[kUrl].protocol === "https:" && client[kServerName] !== request.servername) {
          if (client[kRunning] > 0) {
            return;
          }
          client[kServerName] = request.servername;
          client[kHTTPContext]?.destroy(new InformationalError("servername changed"), () => {
            client[kHTTPContext] = null;
            resume(client);
          });
        }
        if (client[kConnecting]) {
          return;
        }
        if (!client[kHTTPContext]) {
          connect(client);
          return;
        }
        if (client[kHTTPContext].destroyed) {
          return;
        }
        if (client[kHTTPContext].busy(request)) {
          return;
        }
        if (!request.aborted && client[kHTTPContext].write(request)) {
          client[kPendingIdx]++;
        } else {
          client[kQueue].splice(client[kPendingIdx], 1);
        }
      }
    }
    module.exports = Client;
  }
});

// node_modules/undici/lib/dispatcher/fixed-queue.js
var require_fixed_queue = __commonJS({
  "node_modules/undici/lib/dispatcher/fixed-queue.js"(exports, module) {
    "use strict";
    var kSize = 2048;
    var kMask = kSize - 1;
    var FixedCircularBuffer = class {
      /** @type {number} */
      bottom = 0;
      /** @type {number} */
      top = 0;
      /** @type {Array<T|undefined>} */
      list = new Array(kSize).fill(void 0);
      /** @type {T|null} */
      next = null;
      /** @returns {boolean} */
      isEmpty() {
        return this.top === this.bottom;
      }
      /** @returns {boolean} */
      isFull() {
        return (this.top + 1 & kMask) === this.bottom;
      }
      /**
       * @param {T} data
       * @returns {void}
       */
      push(data) {
        this.list[this.top] = data;
        this.top = this.top + 1 & kMask;
      }
      /** @returns {T|null} */
      shift() {
        const nextItem = this.list[this.bottom];
        if (nextItem === void 0) {
          return null;
        }
        this.list[this.bottom] = void 0;
        this.bottom = this.bottom + 1 & kMask;
        return nextItem;
      }
    };
    module.exports = class FixedQueue {
      constructor() {
        this.head = this.tail = new FixedCircularBuffer();
      }
      /** @returns {boolean} */
      isEmpty() {
        return this.head.isEmpty();
      }
      /** @param {T} data */
      push(data) {
        if (this.head.isFull()) {
          this.head = this.head.next = new FixedCircularBuffer();
        }
        this.head.push(data);
      }
      /** @returns {T|null} */
      shift() {
        const tail = this.tail;
        const next = tail.shift();
        if (tail.isEmpty() && tail.next !== null) {
          this.tail = tail.next;
          tail.next = null;
        }
        return next;
      }
    };
  }
});

// node_modules/undici/lib/dispatcher/pool-base.js
var require_pool_base = __commonJS({
  "node_modules/undici/lib/dispatcher/pool-base.js"(exports, module) {
    "use strict";
    var { PoolStats } = require_stats();
    var DispatcherBase = require_dispatcher_base();
    var FixedQueue = require_fixed_queue();
    var { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require_symbols();
    var kClients = /* @__PURE__ */ Symbol("clients");
    var kNeedDrain = /* @__PURE__ */ Symbol("needDrain");
    var kQueue = /* @__PURE__ */ Symbol("queue");
    var kClosedResolve = /* @__PURE__ */ Symbol("closed resolve");
    var kOnDrain = /* @__PURE__ */ Symbol("onDrain");
    var kOnConnect = /* @__PURE__ */ Symbol("onConnect");
    var kOnDisconnect = /* @__PURE__ */ Symbol("onDisconnect");
    var kOnConnectionError = /* @__PURE__ */ Symbol("onConnectionError");
    var kGetDispatcher = /* @__PURE__ */ Symbol("get dispatcher");
    var kAddClient = /* @__PURE__ */ Symbol("add client");
    var kRemoveClient = /* @__PURE__ */ Symbol("remove client");
    var PoolBase = class extends DispatcherBase {
      [kQueue] = new FixedQueue();
      [kQueued] = 0;
      [kClients] = [];
      [kNeedDrain] = false;
      [kOnDrain](client, origin, targets) {
        const queue = this[kQueue];
        let needDrain = false;
        while (!needDrain) {
          const item = queue.shift();
          if (!item) {
            break;
          }
          this[kQueued]--;
          needDrain = !client.dispatch(item.opts, item.handler);
        }
        client[kNeedDrain] = needDrain;
        if (!needDrain && this[kNeedDrain]) {
          this[kNeedDrain] = false;
          this.emit("drain", origin, [this, ...targets]);
        }
        if (this[kClosedResolve] && queue.isEmpty()) {
          const closeAll = [];
          for (let i = 0; i < this[kClients].length; i++) {
            const client2 = this[kClients][i];
            if (!client2.destroyed) {
              closeAll.push(client2.close());
            }
          }
          return Promise.all(closeAll).then(this[kClosedResolve]);
        }
      }
      [kOnConnect] = (origin, targets) => {
        this.emit("connect", origin, [this, ...targets]);
      };
      [kOnDisconnect] = (origin, targets, err) => {
        this.emit("disconnect", origin, [this, ...targets], err);
      };
      [kOnConnectionError] = (origin, targets, err) => {
        this.emit("connectionError", origin, [this, ...targets], err);
      };
      get [kBusy]() {
        return this[kNeedDrain];
      }
      get [kConnected]() {
        let ret = 0;
        for (const { [kConnected]: connected } of this[kClients]) {
          ret += connected;
        }
        return ret;
      }
      get [kFree]() {
        let ret = 0;
        for (const { [kConnected]: connected, [kNeedDrain]: needDrain } of this[kClients]) {
          ret += connected && !needDrain;
        }
        return ret;
      }
      get [kPending]() {
        let ret = this[kQueued];
        for (const { [kPending]: pending } of this[kClients]) {
          ret += pending;
        }
        return ret;
      }
      get [kRunning]() {
        let ret = 0;
        for (const { [kRunning]: running } of this[kClients]) {
          ret += running;
        }
        return ret;
      }
      get [kSize]() {
        let ret = this[kQueued];
        for (const { [kSize]: size5 } of this[kClients]) {
          ret += size5;
        }
        return ret;
      }
      get stats() {
        return new PoolStats(this);
      }
      [kClose]() {
        if (this[kQueue].isEmpty()) {
          const closeAll = [];
          for (let i = 0; i < this[kClients].length; i++) {
            const client = this[kClients][i];
            if (!client.destroyed) {
              closeAll.push(client.close());
            }
          }
          return Promise.all(closeAll);
        } else {
          return new Promise((resolve) => {
            this[kClosedResolve] = resolve;
          });
        }
      }
      [kDestroy](err) {
        while (true) {
          const item = this[kQueue].shift();
          if (!item) {
            break;
          }
          item.handler.onResponseError(null, err);
        }
        const destroyAll = new Array(this[kClients].length);
        for (let i = 0; i < this[kClients].length; i++) {
          destroyAll[i] = this[kClients][i].destroy(err);
        }
        return Promise.all(destroyAll);
      }
      [kDispatch](opts, handler) {
        const dispatcher = this[kGetDispatcher]();
        if (!dispatcher) {
          this[kNeedDrain] = true;
          this[kQueue].push({ opts, handler });
          this[kQueued]++;
        } else if (!dispatcher.dispatch(opts, handler)) {
          dispatcher[kNeedDrain] = true;
          this[kNeedDrain] = !this[kGetDispatcher]();
        }
        return !this[kNeedDrain];
      }
      [kAddClient](client) {
        client.on("drain", this[kOnDrain].bind(this, client)).on("connect", this[kOnConnect]).on("disconnect", this[kOnDisconnect]).on("connectionError", this[kOnConnectionError]);
        this[kClients].push(client);
        if (this[kNeedDrain]) {
          queueMicrotask(() => {
            if (this[kNeedDrain]) {
              this[kOnDrain](client, client[kUrl], [client, this]);
            }
          });
        }
        return this;
      }
      [kRemoveClient](client) {
        const idx = this[kClients].indexOf(client);
        if (idx !== -1) {
          this[kClients].splice(idx, 1);
        }
        client.close(() => {
        });
        this[kNeedDrain] = this[kClients].some((dispatcher) => !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true);
      }
    };
    module.exports = {
      PoolBase,
      kClients,
      kNeedDrain,
      kAddClient,
      kRemoveClient,
      kGetDispatcher
    };
  }
});

// node_modules/undici/lib/dispatcher/pool.js
var require_pool = __commonJS({
  "node_modules/undici/lib/dispatcher/pool.js"(exports, module) {
    "use strict";
    var {
      PoolBase,
      kClients,
      kNeedDrain,
      kAddClient,
      kGetDispatcher,
      kRemoveClient
    } = require_pool_base();
    var Client = require_client();
    var {
      InvalidArgumentError
    } = require_errors();
    var util2 = require_util();
    var { kUrl } = require_symbols();
    var buildConnector = require_connect();
    var kOptions = /* @__PURE__ */ Symbol("options");
    var kConnections = /* @__PURE__ */ Symbol("connections");
    var kFactory = /* @__PURE__ */ Symbol("factory");
    function defaultFactory(origin, opts) {
      return new Client(origin, opts);
    }
    var Pool = class extends PoolBase {
      constructor(origin, {
        connections,
        factory = defaultFactory,
        connect,
        connectTimeout,
        tls,
        maxCachedSessions,
        socketPath,
        autoSelectFamily,
        autoSelectFamilyAttemptTimeout,
        allowH2,
        useH2c,
        clientTtl,
        ...options
      } = {}) {
        if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
          throw new InvalidArgumentError("invalid connections");
        }
        if (typeof factory !== "function") {
          throw new InvalidArgumentError("factory must be a function.");
        }
        if (connect != null && typeof connect !== "function" && typeof connect !== "object") {
          throw new InvalidArgumentError("connect must be a function or an object");
        }
        if (typeof connect !== "function") {
          connect = buildConnector({
            ...tls,
            maxCachedSessions,
            allowH2,
            useH2c,
            socketPath,
            timeout: connectTimeout,
            ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
            ...connect
          });
        }
        super(options);
        this[kConnections] = connections || null;
        this[kUrl] = util2.parseOrigin(origin);
        this[kOptions] = { ...util2.deepClone(options), connect, allowH2, useH2c, clientTtl, socketPath };
        this[kFactory] = factory;
        this.on("connect", (origin2, targets) => {
          if (clientTtl != null && clientTtl > 0) {
            for (const target of targets) {
              Object.assign(target, { ttl: Date.now() });
            }
          }
        });
        this.on("connectionError", (origin2, targets, error) => {
          for (const target of targets) {
            const idx = this[kClients].indexOf(target);
            if (idx !== -1) {
              this[kClients].splice(idx, 1);
            }
          }
        });
      }
      [kGetDispatcher]() {
        const clientTtlOption = this[kOptions].clientTtl;
        for (let i = 0; i < this[kClients].length; i++) {
          const client = this[kClients][i];
          if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && Date.now() - client.ttl > clientTtlOption) {
            this[kRemoveClient](client);
            i--;
          } else if (!client[kNeedDrain]) {
            return client;
          }
        }
        if (!this[kConnections] || this[kClients].length < this[kConnections]) {
          const dispatcher = this[kFactory](this[kUrl], this[kOptions]);
          this[kAddClient](dispatcher);
          return dispatcher;
        }
      }
    };
    module.exports = Pool;
  }
});

// node_modules/undici/lib/dispatcher/balanced-pool.js
var require_balanced_pool = __commonJS({
  "node_modules/undici/lib/dispatcher/balanced-pool.js"(exports, module) {
    "use strict";
    var {
      BalancedPoolMissingUpstreamError,
      InvalidArgumentError
    } = require_errors();
    var {
      PoolBase,
      kClients,
      kNeedDrain,
      kAddClient,
      kRemoveClient,
      kGetDispatcher
    } = require_pool_base();
    var Pool = require_pool();
    var { kUrl } = require_symbols();
    var util2 = require_util();
    var kFactory = /* @__PURE__ */ Symbol("factory");
    var kOptions = /* @__PURE__ */ Symbol("options");
    var kGreatestCommonDivisor = /* @__PURE__ */ Symbol("kGreatestCommonDivisor");
    var kCurrentWeight = /* @__PURE__ */ Symbol("kCurrentWeight");
    var kIndex = /* @__PURE__ */ Symbol("kIndex");
    var kWeight = /* @__PURE__ */ Symbol("kWeight");
    var kMaxWeightPerServer = /* @__PURE__ */ Symbol("kMaxWeightPerServer");
    var kErrorPenalty = /* @__PURE__ */ Symbol("kErrorPenalty");
    function getGreatestCommonDivisor(a, b) {
      if (a === 0) return b;
      while (b !== 0) {
        const t = b;
        b = a % b;
        a = t;
      }
      return a;
    }
    function defaultFactory(origin, opts) {
      return new Pool(origin, opts);
    }
    var BalancedPool = class extends PoolBase {
      constructor(upstreams = [], { factory = defaultFactory, ...opts } = {}) {
        if (typeof factory !== "function") {
          throw new InvalidArgumentError("factory must be a function.");
        }
        super();
        this[kOptions] = { ...util2.deepClone(opts) };
        this[kIndex] = -1;
        this[kCurrentWeight] = 0;
        this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100;
        this[kErrorPenalty] = this[kOptions].errorPenalty || 15;
        if (!Array.isArray(upstreams)) {
          upstreams = [upstreams];
        }
        this[kFactory] = factory;
        for (const upstream of upstreams) {
          this.addUpstream(upstream);
        }
        this._updateBalancedPoolStats();
      }
      addUpstream(upstream) {
        const upstreamOrigin = util2.parseOrigin(upstream).origin;
        if (this[kClients].find((pool2) => pool2[kUrl].origin === upstreamOrigin && pool2.closed !== true && pool2.destroyed !== true)) {
          return this;
        }
        const pool = this[kFactory](upstreamOrigin, this[kOptions]);
        this[kAddClient](pool);
        pool.on("connect", () => {
          pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]);
        });
        pool.on("connectionError", () => {
          pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]);
          this._updateBalancedPoolStats();
        });
        pool.on("disconnect", (...args) => {
          const err = args[2];
          if (err && err.code === "UND_ERR_SOCKET") {
            pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]);
            this._updateBalancedPoolStats();
          }
        });
        for (const client of this[kClients]) {
          client[kWeight] = this[kMaxWeightPerServer];
        }
        this._updateBalancedPoolStats();
        return this;
      }
      _updateBalancedPoolStats() {
        let result = 0;
        for (let i = 0; i < this[kClients].length; i++) {
          result = getGreatestCommonDivisor(this[kClients][i][kWeight], result);
        }
        this[kGreatestCommonDivisor] = result;
      }
      removeUpstream(upstream) {
        const upstreamOrigin = util2.parseOrigin(upstream).origin;
        const pool = this[kClients].find((pool2) => pool2[kUrl].origin === upstreamOrigin && pool2.closed !== true && pool2.destroyed !== true);
        if (pool) {
          this[kRemoveClient](pool);
        }
        return this;
      }
      getUpstream(upstream) {
        const upstreamOrigin = util2.parseOrigin(upstream).origin;
        return this[kClients].find((pool) => pool[kUrl].origin === upstreamOrigin && pool.closed !== true && pool.destroyed !== true);
      }
      get upstreams() {
        return this[kClients].filter((dispatcher) => dispatcher.closed !== true && dispatcher.destroyed !== true).map((p) => p[kUrl].origin);
      }
      [kGetDispatcher]() {
        if (this[kClients].length === 0) {
          throw new BalancedPoolMissingUpstreamError();
        }
        let counter = 0;
        let maxWeightIndex = -1;
        while (counter++ < this[kClients].length) {
          this[kIndex] = (this[kIndex] + 1) % this[kClients].length;
          const pool = this[kClients][this[kIndex]];
          if (this[kIndex] === 0) {
            this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor];
            if (this[kCurrentWeight] <= 0) {
              this[kCurrentWeight] = this[kMaxWeightPerServer];
            }
          }
          if (pool[kNeedDrain] || pool.closed === true || pool.destroyed === true) {
            continue;
          }
          if (maxWeightIndex === -1 || pool[kWeight] > this[kClients][maxWeightIndex][kWeight]) {
            maxWeightIndex = this[kIndex];
          }
          if (pool[kWeight] >= this[kCurrentWeight]) {
            return pool;
          }
        }
        if (maxWeightIndex === -1) {
          return;
        }
        this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight];
        this[kIndex] = maxWeightIndex;
        return this[kClients][maxWeightIndex];
      }
    };
    module.exports = BalancedPool;
  }
});

// node_modules/undici/lib/dispatcher/round-robin-pool.js
var require_round_robin_pool = __commonJS({
  "node_modules/undici/lib/dispatcher/round-robin-pool.js"(exports, module) {
    "use strict";
    var {
      PoolBase,
      kClients,
      kNeedDrain,
      kAddClient,
      kGetDispatcher,
      kRemoveClient
    } = require_pool_base();
    var Client = require_client();
    var {
      InvalidArgumentError
    } = require_errors();
    var util2 = require_util();
    var { kUrl } = require_symbols();
    var buildConnector = require_connect();
    var kOptions = /* @__PURE__ */ Symbol("options");
    var kConnections = /* @__PURE__ */ Symbol("connections");
    var kFactory = /* @__PURE__ */ Symbol("factory");
    var kIndex = /* @__PURE__ */ Symbol("index");
    function defaultFactory(origin, opts) {
      return new Client(origin, opts);
    }
    var RoundRobinPool = class extends PoolBase {
      constructor(origin, {
        connections,
        factory = defaultFactory,
        connect,
        connectTimeout,
        tls,
        maxCachedSessions,
        socketPath,
        autoSelectFamily,
        autoSelectFamilyAttemptTimeout,
        allowH2,
        clientTtl,
        ...options
      } = {}) {
        if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
          throw new InvalidArgumentError("invalid connections");
        }
        if (typeof factory !== "function") {
          throw new InvalidArgumentError("factory must be a function.");
        }
        if (connect != null && typeof connect !== "function" && typeof connect !== "object") {
          throw new InvalidArgumentError("connect must be a function or an object");
        }
        if (typeof connect !== "function") {
          connect = buildConnector({
            ...tls,
            maxCachedSessions,
            allowH2,
            socketPath,
            timeout: connectTimeout,
            ...typeof autoSelectFamily === "boolean" ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : void 0,
            ...connect
          });
        }
        super();
        this[kConnections] = connections || null;
        this[kUrl] = util2.parseOrigin(origin);
        this[kOptions] = { ...util2.deepClone(options), connect, allowH2, clientTtl, socketPath };
        this[kFactory] = factory;
        this[kIndex] = -1;
        this.on("connect", (origin2, targets) => {
          if (clientTtl != null && clientTtl > 0) {
            for (const target of targets) {
              Object.assign(target, { ttl: Date.now() });
            }
          }
        });
        this.on("connectionError", (origin2, targets, error) => {
          for (const target of targets) {
            const idx = this[kClients].indexOf(target);
            if (idx !== -1) {
              this[kClients].splice(idx, 1);
            }
          }
        });
      }
      [kGetDispatcher]() {
        const clientTtlOption = this[kOptions].clientTtl;
        if (this[kClients].length === 0) {
          const dispatcher = this[kFactory](this[kUrl], this[kOptions]);
          this[kAddClient](dispatcher);
          return dispatcher;
        }
        let checked = 0;
        while (checked < this[kClients].length) {
          this[kIndex] = (this[kIndex] + 1) % this[kClients].length;
          const client = this[kClients][this[kIndex]];
          if (clientTtlOption != null && clientTtlOption > 0 && client.ttl && Date.now() - client.ttl > clientTtlOption) {
            this[kRemoveClient](client);
            this[kIndex]--;
            continue;
          }
          if (!client[kNeedDrain]) {
            return client;
          }
          checked++;
        }
        if (!this[kConnections] || this[kClients].length < this[kConnections]) {
          const dispatcher = this[kFactory](this[kUrl], this[kOptions]);
          this[kAddClient](dispatcher);
          return dispatcher;
        }
      }
    };
    module.exports = RoundRobinPool;
  }
});

// node_modules/undici/lib/dispatcher/agent.js
var require_agent = __commonJS({
  "node_modules/undici/lib/dispatcher/agent.js"(exports, module) {
    "use strict";
    var { InvalidArgumentError, MaxOriginsReachedError } = require_errors();
    var { kBusy, kClients, kConnected, kRunning, kClose, kDestroy, kDispatch, kUrl } = require_symbols();
    var DispatcherBase = require_dispatcher_base();
    var Pool = require_pool();
    var Client = require_client();
    var util2 = require_util();
    var kOnConnect = /* @__PURE__ */ Symbol("onConnect");
    var kOnDisconnect = /* @__PURE__ */ Symbol("onDisconnect");
    var kOnConnectionError = /* @__PURE__ */ Symbol("onConnectionError");
    var kOnDrain = /* @__PURE__ */ Symbol("onDrain");
    var kFactory = /* @__PURE__ */ Symbol("factory");
    var kOptions = /* @__PURE__ */ Symbol("options");
    var kOrigins = /* @__PURE__ */ Symbol("origins");
    function defaultFactory(origin, opts) {
      return opts && opts.connections === 1 ? new Client(origin, opts) : new Pool(origin, opts);
    }
    var Agent = class extends DispatcherBase {
      constructor({ factory = defaultFactory, maxOrigins = Infinity, connect, ...options } = {}) {
        if (typeof factory !== "function") {
          throw new InvalidArgumentError("factory must be a function.");
        }
        if (connect != null && typeof connect !== "function" && typeof connect !== "object") {
          throw new InvalidArgumentError("connect must be a function or an object");
        }
        if (typeof maxOrigins !== "number" || Number.isNaN(maxOrigins) || maxOrigins <= 0) {
          throw new InvalidArgumentError("maxOrigins must be a number greater than 0");
        }
        super(options);
        if (connect && typeof connect !== "function") {
          connect = { ...connect };
        }
        this[kOptions] = { ...util2.deepClone(options), maxOrigins, connect };
        this[kFactory] = factory;
        this[kClients] = /* @__PURE__ */ new Map();
        this[kOrigins] = /* @__PURE__ */ new Set();
        this[kOnDrain] = (origin, targets) => {
          this.emit("drain", origin, [this, ...targets]);
        };
        this[kOnConnect] = (origin, targets) => {
          this.emit("connect", origin, [this, ...targets]);
        };
        this[kOnDisconnect] = (origin, targets, err) => {
          this.emit("disconnect", origin, [this, ...targets], err);
        };
        this[kOnConnectionError] = (origin, targets, err) => {
          this.emit("connectionError", origin, [this, ...targets], err);
        };
      }
      get [kRunning]() {
        let ret = 0;
        for (const dispatcher of this[kClients].values()) {
          ret += dispatcher[kRunning];
        }
        return ret;
      }
      [kDispatch](opts, handler) {
        let origin;
        if (opts.origin && (typeof opts.origin === "string" || opts.origin instanceof URL)) {
          origin = String(opts.origin);
        } else {
          throw new InvalidArgumentError("opts.origin must be a non-empty string or URL.");
        }
        const allowH2 = opts.allowH2 ?? this[kOptions].allowH2;
        const key = allowH2 === false ? `${origin}#http1-only` : origin;
        if (this[kOrigins].size >= this[kOptions].maxOrigins && !this[kOrigins].has(origin)) {
          throw new MaxOriginsReachedError();
        }
        let dispatcher = this[kClients].get(key);
        if (!dispatcher) {
          dispatcher = this[kFactory](opts.origin, allowH2 === false ? { ...this[kOptions], allowH2: false } : this[kOptions]);
          const closeClientIfUnused = () => {
            if (this[kClients].get(key) !== dispatcher) {
              return;
            }
            if (dispatcher[kConnected] > 0 || dispatcher[kBusy]) {
              return;
            }
            this[kClients].delete(key);
            if (!dispatcher.destroyed) {
              dispatcher.close();
            }
            let hasOrigin = false;
            for (const client of this[kClients].values()) {
              if (client[kUrl].origin === dispatcher[kUrl].origin) {
                hasOrigin = true;
                break;
              }
            }
            if (!hasOrigin) {
              this[kOrigins].delete(dispatcher[kUrl].origin);
            }
          };
          dispatcher.on("drain", this[kOnDrain]).on("connect", this[kOnConnect]).on("disconnect", (origin2, targets, err) => {
            closeClientIfUnused();
            this[kOnDisconnect](origin2, targets, err);
          }).on("connectionError", (origin2, targets, err) => {
            closeClientIfUnused();
            this[kOnConnectionError](origin2, targets, err);
          });
          this[kClients].set(key, dispatcher);
          this[kOrigins].add(origin);
        }
        return dispatcher.dispatch(opts, handler);
      }
      [kClose]() {
        const closePromises = [];
        for (const dispatcher of this[kClients].values()) {
          closePromises.push(dispatcher.close());
        }
        this[kClients].clear();
        return Promise.all(closePromises);
      }
      [kDestroy](err) {
        const destroyPromises = [];
        for (const dispatcher of this[kClients].values()) {
          destroyPromises.push(dispatcher.destroy(err));
        }
        this[kClients].clear();
        return Promise.all(destroyPromises);
      }
      get stats() {
        const allClientStats = {};
        for (const dispatcher of this[kClients].values()) {
          if (dispatcher.stats) {
            allClientStats[dispatcher[kUrl].origin] = dispatcher.stats;
          }
        }
        return allClientStats;
      }
    };
    module.exports = Agent;
  }
});

// node_modules/undici/lib/dispatcher/dispatcher1-wrapper.js
var require_dispatcher1_wrapper = __commonJS({
  "node_modules/undici/lib/dispatcher/dispatcher1-wrapper.js"(exports, module) {
    "use strict";
    var Dispatcher = require_dispatcher();
    var { InvalidArgumentError } = require_errors();
    var { toRawHeaders } = require_util();
    var LegacyHandlerWrapper = class {
      #handler;
      constructor(handler) {
        this.#handler = handler;
      }
      onRequestStart(controller, context) {
        this.#handler.onConnect?.((reason) => controller.abort(reason), context);
      }
      onRequestUpgrade(controller, statusCode, headers, socket) {
        const rawHeaders = controller?.rawHeaders ?? toRawHeaders(headers ?? {});
        this.#handler.onUpgrade?.(statusCode, rawHeaders, socket);
      }
      onResponseStart(controller, statusCode, headers, statusMessage) {
        const rawHeaders = controller?.rawHeaders ?? toRawHeaders(headers ?? {});
        if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) {
          controller.pause();
        }
      }
      onResponseData(controller, chunk) {
        if (this.#handler.onData?.(chunk) === false) {
          controller.pause();
        }
      }
      onResponseEnd(controller, trailers) {
        const rawTrailers = controller?.rawTrailers ?? toRawHeaders(trailers ?? {});
        this.#handler.onComplete?.(rawTrailers);
      }
      onResponseError(_controller, err) {
        if (!this.#handler.onError) {
          throw err;
        }
        this.#handler.onError(err);
      }
      onBodySent(chunk) {
        this.#handler.onBodySent?.(chunk);
      }
      onRequestSent() {
        this.#handler.onRequestSent?.();
      }
      onResponseStarted() {
        this.#handler.onResponseStarted?.();
      }
    };
    var Dispatcher1Wrapper = class _Dispatcher1Wrapper extends Dispatcher {
      #dispatcher;
      constructor(dispatcher) {
        super();
        if (!dispatcher || typeof dispatcher.dispatch !== "function") {
          throw new InvalidArgumentError("Argument dispatcher must implement dispatch");
        }
        this.#dispatcher = dispatcher;
      }
      static wrapHandler(handler) {
        if (!handler || typeof handler !== "object") {
          throw new InvalidArgumentError("handler must be an object");
        }
        if (typeof handler.onRequestStart === "function") {
          return handler;
        }
        return new LegacyHandlerWrapper(handler);
      }
      dispatch(opts, handler) {
        if (opts.allowH2 !== false) {
          opts = { ...opts, allowH2: false };
        }
        return this.#dispatcher.dispatch(opts, _Dispatcher1Wrapper.wrapHandler(handler));
      }
      close(...args) {
        return this.#dispatcher.close(...args);
      }
      destroy(...args) {
        return this.#dispatcher.destroy(...args);
      }
    };
    module.exports = Dispatcher1Wrapper;
  }
});

// node_modules/undici/lib/core/socks5-utils.js
var require_socks5_utils = __commonJS({
  "node_modules/undici/lib/core/socks5-utils.js"(exports, module) {
    "use strict";
    var { Buffer: Buffer2 } = __require("buffer");
    var net = __require("net");
    var { InvalidArgumentError } = require_errors();
    function parseAddress(address2) {
      if (net.isIPv4(address2)) {
        const parts = address2.split(".").map(Number);
        return {
          type: 1,
          // IPv4
          buffer: Buffer2.from(parts)
        };
      }
      if (net.isIPv6(address2)) {
        return {
          type: 4,
          // IPv6
          buffer: parseIPv6(address2)
        };
      }
      const domainBuffer = Buffer2.from(address2, "utf8");
      if (domainBuffer.length > 255) {
        throw new InvalidArgumentError("Domain name too long (max 255 bytes)");
      }
      return {
        type: 3,
        // Domain
        buffer: Buffer2.concat([Buffer2.from([domainBuffer.length]), domainBuffer])
      };
    }
    function parseIPv6(address2) {
      const buffer2 = Buffer2.alloc(16);
      let normalizedAddress = address2;
      if (address2.includes(".")) {
        const lastColonIndex = address2.lastIndexOf(":");
        const ipv4Part = address2.slice(lastColonIndex + 1);
        if (net.isIPv4(ipv4Part)) {
          const octets = ipv4Part.split(".").map(Number);
          const high = (octets[0] << 8 | octets[1]).toString(16);
          const low = (octets[2] << 8 | octets[3]).toString(16);
          normalizedAddress = `${address2.slice(0, lastColonIndex)}:${high}:${low}`;
        }
      }
      const doubleColonIndex = normalizedAddress.indexOf("::");
      if (doubleColonIndex !== -1) {
        const before = normalizedAddress.slice(0, doubleColonIndex);
        const after = normalizedAddress.slice(doubleColonIndex + 2);
        const beforeParts = before === "" ? [] : before.split(":");
        const afterParts = after === "" ? [] : after.split(":");
        let bufferIndex = 0;
        for (const part of beforeParts) {
          buffer2.writeUInt16BE(parseInt(part, 16), bufferIndex);
          bufferIndex += 2;
        }
        bufferIndex = 16 - afterParts.length * 2;
        for (const part of afterParts) {
          buffer2.writeUInt16BE(parseInt(part, 16), bufferIndex);
          bufferIndex += 2;
        }
      } else {
        const parts = normalizedAddress.split(":");
        for (let i = 0; i < parts.length; i++) {
          buffer2.writeUInt16BE(parseInt(parts[i], 16), i * 2);
        }
      }
      return buffer2;
    }
    function buildAddressBuffer(type, addressBuffer, port) {
      const portBuffer = Buffer2.allocUnsafe(2);
      portBuffer.writeUInt16BE(port, 0);
      return Buffer2.concat([
        Buffer2.from([type]),
        addressBuffer,
        portBuffer
      ]);
    }
    function parseResponseAddress(buffer2, offset = 0) {
      if (buffer2.length < offset + 1) {
        throw new InvalidArgumentError("Buffer too small to contain address type");
      }
      const addressType = buffer2[offset];
      let address2;
      let currentOffset = offset + 1;
      switch (addressType) {
        case 1: {
          if (buffer2.length < currentOffset + 6) {
            throw new InvalidArgumentError("Buffer too small for IPv4 address");
          }
          address2 = Array.from(buffer2.subarray(currentOffset, currentOffset + 4)).join(".");
          currentOffset += 4;
          break;
        }
        case 3: {
          if (buffer2.length < currentOffset + 1) {
            throw new InvalidArgumentError("Buffer too small for domain length");
          }
          const domainLength = buffer2[currentOffset];
          currentOffset += 1;
          if (buffer2.length < currentOffset + domainLength + 2) {
            throw new InvalidArgumentError("Buffer too small for domain address");
          }
          address2 = buffer2.subarray(currentOffset, currentOffset + domainLength).toString("utf8");
          currentOffset += domainLength;
          break;
        }
        case 4: {
          if (buffer2.length < currentOffset + 18) {
            throw new InvalidArgumentError("Buffer too small for IPv6 address");
          }
          const parts = [];
          for (let i = 0; i < 8; i++) {
            const value = buffer2.readUInt16BE(currentOffset + i * 2);
            parts.push(value.toString(16));
          }
          address2 = parts.join(":");
          currentOffset += 16;
          break;
        }
        default:
          throw new InvalidArgumentError(`Invalid address type: ${addressType}`);
      }
      if (buffer2.length < currentOffset + 2) {
        throw new InvalidArgumentError("Buffer too small for port");
      }
      const port = buffer2.readUInt16BE(currentOffset);
      currentOffset += 2;
      return {
        address: address2,
        port,
        bytesRead: currentOffset - offset
      };
    }
    function createReplyError(replyCode) {
      const messages = {
        1: "General SOCKS server failure",
        2: "Connection not allowed by ruleset",
        3: "Network unreachable",
        4: "Host unreachable",
        5: "Connection refused",
        6: "TTL expired",
        7: "Command not supported",
        8: "Address type not supported"
      };
      const message = messages[replyCode] || `Unknown SOCKS5 error code: ${replyCode}`;
      const error = new Error(message);
      error.code = `SOCKS5_${replyCode}`;
      return error;
    }
    module.exports = {
      parseAddress,
      parseIPv6,
      buildAddressBuffer,
      parseResponseAddress,
      createReplyError
    };
  }
});

// node_modules/undici/lib/core/socks5-client.js
var require_socks5_client = __commonJS({
  "node_modules/undici/lib/core/socks5-client.js"(exports, module) {
    "use strict";
    var { EventEmitter } = __require("events");
    var { Buffer: Buffer2 } = __require("buffer");
    var { InvalidArgumentError, Socks5ProxyError } = require_errors();
    var { debuglog } = __require("util");
    var { parseAddress } = require_socks5_utils();
    var debug = debuglog("undici:socks5");
    var EMPTY_BUFFER = Buffer2.alloc(0);
    var SOCKS_VERSION = 5;
    var AUTH_METHODS = {
      NO_AUTH: 0,
      GSSAPI: 1,
      USERNAME_PASSWORD: 2,
      NO_ACCEPTABLE: 255
    };
    var COMMANDS = {
      CONNECT: 1,
      BIND: 2,
      UDP_ASSOCIATE: 3
    };
    var ADDRESS_TYPES = {
      IPV4: 1,
      DOMAIN: 3,
      IPV6: 4
    };
    var REPLY_CODES = {
      SUCCEEDED: 0,
      GENERAL_FAILURE: 1,
      CONNECTION_NOT_ALLOWED: 2,
      NETWORK_UNREACHABLE: 3,
      HOST_UNREACHABLE: 4,
      CONNECTION_REFUSED: 5,
      TTL_EXPIRED: 6,
      COMMAND_NOT_SUPPORTED: 7,
      ADDRESS_TYPE_NOT_SUPPORTED: 8
    };
    var STATES = {
      INITIAL: "initial",
      HANDSHAKING: "handshaking",
      AUTHENTICATING: "authenticating",
      AUTHENTICATED: "authenticated",
      CONNECTING: "connecting",
      CONNECTED: "connected",
      ERROR: "error",
      CLOSED: "closed"
    };
    var Socks5Client = class extends EventEmitter {
      constructor(socket, options = {}) {
        super();
        if (!socket) {
          throw new InvalidArgumentError("socket is required");
        }
        this.socket = socket;
        this.options = options;
        this.state = STATES.INITIAL;
        this.buffer = EMPTY_BUFFER;
        this.onSocketData = this.onData.bind(this);
        this.onSocketError = this.onError.bind(this);
        this.onSocketClose = this.onClose.bind(this);
        this.authMethods = [];
        if (options.username && options.password) {
          this.authMethods.push(AUTH_METHODS.USERNAME_PASSWORD);
        }
        this.authMethods.push(AUTH_METHODS.NO_AUTH);
        this.socket.on("data", this.onSocketData);
        this.socket.on("error", this.onSocketError);
        this.socket.on("close", this.onSocketClose);
      }
      /**
       * Handle incoming data from the socket
       */
      onData(data) {
        debug("received data", data.length, "bytes in state", this.state);
        this.buffer = Buffer2.concat([this.buffer, data]);
        try {
          switch (this.state) {
            case STATES.HANDSHAKING:
              this.handleHandshakeResponse();
              break;
            case STATES.AUTHENTICATING:
              this.handleAuthResponse();
              break;
            case STATES.CONNECTING:
              this.handleConnectResponse();
              break;
          }
        } catch (err) {
          this.onError(err);
        }
      }
      /**
       * Handle socket errors
       */
      onError(err) {
        debug("socket error", err);
        this.state = STATES.ERROR;
        this.emit("error", err);
        this.destroy();
      }
      /**
       * Handle socket close
       */
      onClose() {
        debug("socket closed");
        this.state = STATES.CLOSED;
        this.emit("close");
      }
      /**
       * Destroy the client and underlying socket
       */
      destroy() {
        if (this.socket && !this.socket.destroyed) {
          this.socket.destroy();
        }
      }
      markAuthenticated() {
        this.state = STATES.AUTHENTICATED;
        this.emit("authenticated");
      }
      /**
       * Start the SOCKS5 handshake
       */
      handshake() {
        if (this.state !== STATES.INITIAL) {
          throw new InvalidArgumentError("Handshake already started");
        }
        debug("starting handshake with", this.authMethods.length, "auth methods");
        this.state = STATES.HANDSHAKING;
        const request = Buffer2.alloc(2 + this.authMethods.length);
        request[0] = SOCKS_VERSION;
        request[1] = this.authMethods.length;
        this.authMethods.forEach((method, i) => {
          request[2 + i] = method;
        });
        this.socket.write(request);
      }
      /**
       * Handle handshake response from server
       */
      handleHandshakeResponse() {
        if (this.buffer.length < 2) {
          return;
        }
        const version4 = this.buffer[0];
        const method = this.buffer[1];
        if (version4 !== SOCKS_VERSION) {
          throw new Socks5ProxyError(`Invalid SOCKS version: ${version4}`, "UND_ERR_SOCKS5_VERSION");
        }
        if (method === AUTH_METHODS.NO_ACCEPTABLE) {
          throw new Socks5ProxyError("No acceptable authentication method", "UND_ERR_SOCKS5_AUTH_REJECTED");
        }
        this.buffer = this.buffer.subarray(2);
        debug("server selected auth method", method);
        if (method === AUTH_METHODS.NO_AUTH) {
          this.markAuthenticated();
        } else if (method === AUTH_METHODS.USERNAME_PASSWORD) {
          this.state = STATES.AUTHENTICATING;
          this.sendAuthRequest();
        } else {
          throw new Socks5ProxyError(`Unsupported authentication method: ${method}`, "UND_ERR_SOCKS5_AUTH_METHOD");
        }
      }
      /**
       * Send username/password authentication request
       */
      sendAuthRequest() {
        const { username, password } = this.options;
        if (!username || !password) {
          throw new InvalidArgumentError("Username and password required for authentication");
        }
        debug("sending username/password auth");
        const usernameBuffer = Buffer2.from(username);
        const passwordBuffer = Buffer2.from(password);
        if (usernameBuffer.length > 255 || passwordBuffer.length > 255) {
          throw new InvalidArgumentError("Username or password too long");
        }
        const request = Buffer2.alloc(3 + usernameBuffer.length + passwordBuffer.length);
        request[0] = 1;
        request[1] = usernameBuffer.length;
        usernameBuffer.copy(request, 2);
        request[2 + usernameBuffer.length] = passwordBuffer.length;
        passwordBuffer.copy(request, 3 + usernameBuffer.length);
        this.socket.write(request);
      }
      /**
       * Handle authentication response
       */
      handleAuthResponse() {
        if (this.buffer.length < 2) {
          return;
        }
        const version4 = this.buffer[0];
        const status = this.buffer[1];
        if (version4 !== 1) {
          throw new Socks5ProxyError(`Invalid auth sub-negotiation version: ${version4}`, "UND_ERR_SOCKS5_AUTH_VERSION");
        }
        if (status !== 0) {
          throw new Socks5ProxyError("Authentication failed", "UND_ERR_SOCKS5_AUTH_FAILED");
        }
        this.buffer = this.buffer.subarray(2);
        debug("authentication successful");
        this.markAuthenticated();
      }
      /**
       * Send CONNECT command
       * @param {string} address - Target address (IP or domain)
       * @param {number} port - Target port
       */
      connect(address2, port) {
        if (this.state === STATES.CONNECTING || this.state === STATES.CONNECTED) {
          throw new InvalidArgumentError("Connection already in progress");
        }
        if (this.state !== STATES.AUTHENTICATED) {
          throw new InvalidArgumentError("Client must be authenticated before CONNECT");
        }
        debug("connecting to", address2, port);
        this.state = STATES.CONNECTING;
        const request = this.buildConnectRequest(COMMANDS.CONNECT, address2, port);
        this.socket.write(request);
      }
      /**
       * Build a SOCKS5 request
       */
      buildConnectRequest(command, address2, port) {
        const { type: addressType, buffer: addressBuffer } = parseAddress(address2);
        const request = Buffer2.alloc(4 + addressBuffer.length + 2);
        request[0] = SOCKS_VERSION;
        request[1] = command;
        request[2] = 0;
        request[3] = addressType;
        addressBuffer.copy(request, 4);
        request.writeUInt16BE(port, 4 + addressBuffer.length);
        return request;
      }
      /**
       * Handle CONNECT response
       */
      handleConnectResponse() {
        if (this.buffer.length < 4) {
          return;
        }
        const version4 = this.buffer[0];
        const reply = this.buffer[1];
        const addressType = this.buffer[3];
        if (version4 !== SOCKS_VERSION) {
          throw new Socks5ProxyError(`Invalid SOCKS version in reply: ${version4}`, "UND_ERR_SOCKS5_REPLY_VERSION");
        }
        let responseLength = 4;
        if (addressType === ADDRESS_TYPES.IPV4) {
          responseLength += 4 + 2;
        } else if (addressType === ADDRESS_TYPES.DOMAIN) {
          if (this.buffer.length < 5) {
            return;
          }
          responseLength += 1 + this.buffer[4] + 2;
        } else if (addressType === ADDRESS_TYPES.IPV6) {
          responseLength += 16 + 2;
        } else {
          throw new Socks5ProxyError(`Invalid address type in reply: ${addressType}`, "UND_ERR_SOCKS5_ADDR_TYPE");
        }
        if (this.buffer.length < responseLength) {
          return;
        }
        if (reply !== REPLY_CODES.SUCCEEDED) {
          const errorMessage = this.getReplyErrorMessage(reply);
          throw new Socks5ProxyError(`SOCKS5 connection failed: ${errorMessage}`, `UND_ERR_SOCKS5_REPLY_${reply}`);
        }
        let boundAddress;
        let offset = 4;
        if (addressType === ADDRESS_TYPES.IPV4) {
          boundAddress = Array.from(this.buffer.subarray(offset, offset + 4)).join(".");
          offset += 4;
        } else if (addressType === ADDRESS_TYPES.DOMAIN) {
          const domainLength = this.buffer[offset];
          offset += 1;
          boundAddress = this.buffer.subarray(offset, offset + domainLength).toString();
          offset += domainLength;
        } else if (addressType === ADDRESS_TYPES.IPV6) {
          const parts = [];
          for (let i = 0; i < 8; i++) {
            const value = this.buffer.readUInt16BE(offset + i * 2);
            parts.push(value.toString(16));
          }
          boundAddress = parts.join(":");
          offset += 16;
        }
        const boundPort = this.buffer.readUInt16BE(offset);
        this.buffer = EMPTY_BUFFER;
        this.state = STATES.CONNECTED;
        this.socket.removeListener("data", this.onSocketData);
        debug("connected, bound address:", boundAddress, "port:", boundPort);
        this.emit("connected", { address: boundAddress, port: boundPort });
      }
      /**
       * Get human-readable error message for reply code
       */
      getReplyErrorMessage(reply) {
        switch (reply) {
          case REPLY_CODES.GENERAL_FAILURE:
            return "General SOCKS server failure";
          case REPLY_CODES.CONNECTION_NOT_ALLOWED:
            return "Connection not allowed by ruleset";
          case REPLY_CODES.NETWORK_UNREACHABLE:
            return "Network unreachable";
          case REPLY_CODES.HOST_UNREACHABLE:
            return "Host unreachable";
          case REPLY_CODES.CONNECTION_REFUSED:
            return "Connection refused";
          case REPLY_CODES.TTL_EXPIRED:
            return "TTL expired";
          case REPLY_CODES.COMMAND_NOT_SUPPORTED:
            return "Command not supported";
          case REPLY_CODES.ADDRESS_TYPE_NOT_SUPPORTED:
            return "Address type not supported";
          default:
            return `Unknown error code: ${reply}`;
        }
      }
    };
    module.exports = {
      Socks5Client,
      AUTH_METHODS,
      COMMANDS,
      ADDRESS_TYPES,
      REPLY_CODES,
      STATES
    };
  }
});

// node_modules/undici/lib/dispatcher/socks5-proxy-agent.js
var require_socks5_proxy_agent = __commonJS({
  "node_modules/undici/lib/dispatcher/socks5-proxy-agent.js"(exports, module) {
    "use strict";
    var net = __require("net");
    var { URL: URL2 } = __require("url");
    var tls;
    var DispatcherBase = require_dispatcher_base();
    var { InvalidArgumentError } = require_errors();
    var { Socks5Client, STATES } = require_socks5_client();
    var { kDispatch, kClose, kDestroy } = require_symbols();
    var Pool = require_pool();
    var buildConnector = require_connect();
    var { debuglog } = __require("util");
    var debug = debuglog("undici:socks5-proxy");
    var kProxyUrl = /* @__PURE__ */ Symbol("proxy url");
    var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers");
    var kProxyAuth = /* @__PURE__ */ Symbol("proxy auth");
    var kPools = /* @__PURE__ */ Symbol("pools");
    var kConnector = /* @__PURE__ */ Symbol("connector");
    var experimentalWarningEmitted = false;
    var Socks5ProxyAgent = class extends DispatcherBase {
      constructor(proxyUrl, options = {}) {
        super();
        if (!experimentalWarningEmitted) {
          process.emitWarning(
            "SOCKS5 proxy support is experimental and subject to change",
            "ExperimentalWarning"
          );
          experimentalWarningEmitted = true;
        }
        if (!proxyUrl) {
          throw new InvalidArgumentError("Proxy URL is mandatory");
        }
        const url = typeof proxyUrl === "string" ? new URL2(proxyUrl) : proxyUrl;
        if (url.protocol !== "socks5:" && url.protocol !== "socks:") {
          throw new InvalidArgumentError("Proxy URL must use socks5:// or socks:// protocol");
        }
        this[kProxyUrl] = url;
        this[kProxyHeaders] = options.headers || {};
        this[kProxyAuth] = {
          username: options.username || (url.username ? decodeURIComponent(url.username) : null),
          password: options.password || (url.password ? decodeURIComponent(url.password) : null)
        };
        this[kConnector] = options.connect || buildConnector({
          ...options.proxyTls,
          servername: options.proxyTls?.servername || url.hostname
        });
        this[kPools] = /* @__PURE__ */ new Map();
      }
      /**
       * Create a SOCKS5 connection to the proxy
       */
      async createSocks5Connection(targetHost, targetPort) {
        const proxyHost = this[kProxyUrl].hostname;
        const proxyPort = parseInt(this[kProxyUrl].port) || 1080;
        debug("creating SOCKS5 connection to", proxyHost, proxyPort);
        const socketReady = Promise.withResolvers();
        const onSocketConnect = () => {
          socket.removeListener("error", onSocketError);
          socketReady.resolve(socket);
        };
        const onSocketError = (err) => {
          socket.removeListener("connect", onSocketConnect);
          socketReady.reject(err);
        };
        const socket = net.connect({
          host: proxyHost,
          port: proxyPort
        });
        socket.once("connect", onSocketConnect);
        socket.once("error", onSocketError);
        await socketReady.promise;
        const socks5Client = new Socks5Client(socket, this[kProxyAuth]);
        socks5Client.on("error", (err) => {
          debug("SOCKS5 error:", err);
          socket.destroy();
        });
        await socks5Client.handshake();
        const authenticationReady = Promise.withResolvers();
        const authenticationTimeout = setTimeout(() => {
          authenticationReady.reject(new Error("SOCKS5 authentication timeout"));
        }, 5e3);
        const onAuthenticated = () => {
          clearTimeout(authenticationTimeout);
          socks5Client.removeListener("error", onAuthenticationError);
          authenticationReady.resolve();
        };
        const onAuthenticationError = (err) => {
          clearTimeout(authenticationTimeout);
          socks5Client.removeListener("authenticated", onAuthenticated);
          authenticationReady.reject(err);
        };
        if (socks5Client.state === STATES.AUTHENTICATED) {
          clearTimeout(authenticationTimeout);
          authenticationReady.resolve();
        } else {
          socks5Client.once("authenticated", onAuthenticated);
          socks5Client.once("error", onAuthenticationError);
        }
        await authenticationReady.promise;
        await socks5Client.connect(targetHost, targetPort);
        const connectionReady = Promise.withResolvers();
        const connectionTimeout = setTimeout(() => {
          connectionReady.reject(new Error("SOCKS5 connection timeout"));
        }, 5e3);
        const onConnected = (info) => {
          debug("SOCKS5 tunnel established to", targetHost, targetPort, "via", info);
          clearTimeout(connectionTimeout);
          socks5Client.removeListener("error", onConnectionError);
          connectionReady.resolve();
        };
        const onConnectionError = (err) => {
          clearTimeout(connectionTimeout);
          socks5Client.removeListener("connected", onConnected);
          connectionReady.reject(err);
        };
        socks5Client.once("connected", onConnected);
        socks5Client.once("error", onConnectionError);
        await connectionReady.promise;
        return socket;
      }
      /**
       * Dispatch a request through the SOCKS5 proxy
       */
      async [kDispatch](opts, handler) {
        const { origin } = opts;
        debug("dispatching request to", origin, "via SOCKS5");
        try {
          const originKey = String(origin);
          let pool = this[kPools].get(originKey);
          if (!pool || pool.destroyed || pool.closed) {
            pool = new Pool(origin, {
              pipelining: opts.pipelining,
              connections: opts.connections,
              connect: async (connectOpts, callback) => {
                try {
                  const url = new URL2(origin);
                  const targetHost = url.hostname;
                  const targetPort = parseInt(url.port) || (url.protocol === "https:" ? 443 : 80);
                  debug("establishing SOCKS5 connection to", targetHost, targetPort);
                  const socket = await this.createSocks5Connection(targetHost, targetPort);
                  let finalSocket = socket;
                  if (url.protocol === "https:") {
                    if (!tls) {
                      tls = __require("tls");
                    }
                    debug("upgrading to TLS");
                    finalSocket = tls.connect({
                      socket,
                      servername: targetHost,
                      ...connectOpts.tls || {}
                    });
                    const tlsReady = Promise.withResolvers();
                    finalSocket.once("secureConnect", tlsReady.resolve);
                    finalSocket.once("error", tlsReady.reject);
                    await tlsReady.promise;
                  }
                  callback(null, finalSocket);
                } catch (err) {
                  debug("SOCKS5 connection error:", err);
                  callback(err);
                }
              }
            });
            this[kPools].set(originKey, pool);
          }
          return pool[kDispatch](opts, handler);
        } catch (err) {
          debug("dispatch error:", err);
          if (typeof handler.onError === "function") {
            handler.onError(err);
          } else {
            throw err;
          }
        }
      }
      async [kClose]() {
        const closePromises = [];
        for (const pool of this[kPools].values()) {
          closePromises.push(pool.close());
        }
        this[kPools].clear();
        await Promise.all(closePromises);
      }
      async [kDestroy](err) {
        const destroyPromises = [];
        for (const pool of this[kPools].values()) {
          destroyPromises.push(pool.destroy(err));
        }
        this[kPools].clear();
        await Promise.all(destroyPromises);
      }
    };
    module.exports = Socks5ProxyAgent;
  }
});

// node_modules/undici/lib/dispatcher/proxy-agent.js
var require_proxy_agent = __commonJS({
  "node_modules/undici/lib/dispatcher/proxy-agent.js"(exports, module) {
    "use strict";
    var { kProxy, kClose, kDestroy, kDispatch } = require_symbols();
    var Agent = require_agent();
    var Pool = require_pool();
    var DispatcherBase = require_dispatcher_base();
    var { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require_errors();
    var buildConnector = require_connect();
    var Client = require_client();
    var { channels } = require_diagnostics();
    var Socks5ProxyAgent = require_socks5_proxy_agent();
    var kAgent = /* @__PURE__ */ Symbol("proxy agent");
    var kClient = /* @__PURE__ */ Symbol("proxy client");
    var kProxyHeaders = /* @__PURE__ */ Symbol("proxy headers");
    var kRequestTls = /* @__PURE__ */ Symbol("request tls settings");
    var kProxyTls = /* @__PURE__ */ Symbol("proxy tls settings");
    var kConnectEndpoint = /* @__PURE__ */ Symbol("connect endpoint function");
    var kConnectEndpointHTTP1 = /* @__PURE__ */ Symbol("connect endpoint function (http/1.1 only)");
    var kTunnelProxy = /* @__PURE__ */ Symbol("tunnel proxy");
    function defaultProtocolPort(protocol) {
      return protocol === "https:" ? 443 : 80;
    }
    function defaultFactory(origin, opts) {
      return new Pool(origin, opts);
    }
    var noop = () => {
    };
    function defaultAgentFactory(origin, opts) {
      if (opts.connections === 1) {
        return new Client(origin, opts);
      }
      return new Pool(origin, opts);
    }
    var Http1ProxyWrapper = class extends DispatcherBase {
      #client;
      constructor(proxyUrl, { headers = {}, connect, factory }) {
        if (!proxyUrl) {
          throw new InvalidArgumentError("Proxy URL is mandatory");
        }
        super();
        this[kProxyHeaders] = headers;
        if (factory) {
          this.#client = factory(proxyUrl, { connect });
        } else {
          this.#client = new Client(proxyUrl, { connect });
        }
      }
      [kDispatch](opts, handler) {
        const onResponseStart = handler.onResponseStart;
        handler.onResponseStart = function(controller, statusCode, data, statusMessage) {
          if (statusCode === 407) {
            if (typeof handler.onResponseError === "function") {
              handler.onResponseError(controller, new InvalidArgumentError("Proxy Authentication Required (407)"));
            }
            return;
          }
          if (onResponseStart) onResponseStart.call(this, controller, statusCode, data, statusMessage);
        };
        const {
          origin,
          path: path2 = "/",
          headers = {}
        } = opts;
        opts.path = origin + path2;
        if (!("host" in headers) && !("Host" in headers)) {
          const { host } = new URL(origin);
          headers.host = host;
        }
        opts.headers = { ...this[kProxyHeaders], ...headers };
        return this.#client[kDispatch](opts, handler);
      }
      [kClose]() {
        return this.#client.close();
      }
      [kDestroy](err) {
        return this.#client.destroy(err);
      }
    };
    var ProxyAgent = class extends DispatcherBase {
      constructor(opts) {
        if (!opts || typeof opts === "object" && !(opts instanceof URL) && !opts.uri) {
          throw new InvalidArgumentError("Proxy uri is mandatory");
        }
        const { clientFactory = defaultFactory } = opts;
        if (typeof clientFactory !== "function") {
          throw new InvalidArgumentError("Proxy opts.clientFactory must be a function.");
        }
        const { proxyTunnel = true, connectTimeout } = opts;
        super();
        const url = this.#getUrl(opts);
        const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url;
        this[kProxy] = { uri: href, protocol };
        this[kRequestTls] = opts.requestTls;
        this[kProxyTls] = opts.proxyTls;
        this[kProxyHeaders] = opts.headers || {};
        this[kTunnelProxy] = proxyTunnel;
        if (opts.auth && opts.token) {
          throw new InvalidArgumentError("opts.auth cannot be used in combination with opts.token");
        } else if (opts.auth) {
          this[kProxyHeaders]["proxy-authorization"] = `Basic ${opts.auth}`;
        } else if (opts.token) {
          this[kProxyHeaders]["proxy-authorization"] = opts.token;
        } else if (username && password) {
          this[kProxyHeaders]["proxy-authorization"] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString("base64")}`;
        } else if (username) {
          this[kProxyHeaders]["proxy-authorization"] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:`).toString("base64")}`;
        }
        const connect = buildConnector({ timeout: connectTimeout, ...opts.proxyTls });
        this[kConnectEndpoint] = buildConnector({ timeout: connectTimeout, ...opts.requestTls });
        this[kConnectEndpointHTTP1] = buildConnector({ timeout: connectTimeout, ...opts.requestTls, allowH2: false });
        const agentFactory = opts.factory || defaultAgentFactory;
        const factory = (origin2, options) => {
          const { protocol: protocol2 } = new URL(origin2);
          if (this[kProxy].protocol === "socks5:" || this[kProxy].protocol === "socks:") {
            return new Socks5ProxyAgent(this[kProxy].uri, {
              headers: this[kProxyHeaders],
              connect,
              factory: agentFactory,
              username: opts.username || username,
              password: opts.password || password,
              proxyTls: opts.proxyTls
            });
          }
          if (!this[kTunnelProxy] && protocol2 === "http:" && this[kProxy].protocol === "http:") {
            return new Http1ProxyWrapper(this[kProxy].uri, {
              headers: this[kProxyHeaders],
              connect,
              factory: agentFactory
            });
          }
          return agentFactory(origin2, options);
        };
        if (protocol === "socks5:" || protocol === "socks:") {
          this[kClient] = null;
        } else {
          this[kClient] = clientFactory(url, { connect });
        }
        this[kAgent] = new Agent({
          ...opts,
          factory,
          connect: async (opts2, callback) => {
            if (!this[kClient]) {
              callback(new InvalidArgumentError("Cannot establish tunnel connection without a proxy client"));
              return;
            }
            let requestedPath = opts2.host;
            if (!opts2.port) {
              requestedPath += `:${defaultProtocolPort(opts2.protocol)}`;
            }
            try {
              const connectParams = {
                origin,
                port,
                path: requestedPath,
                signal: opts2.signal,
                headers: {
                  ...this[kProxyHeaders],
                  host: opts2.host,
                  ...opts2.connections == null || opts2.connections > 0 ? { "proxy-connection": "keep-alive" } : {}
                },
                servername: this[kProxyTls]?.servername || proxyHostname
              };
              const { socket, statusCode } = await this[kClient].connect(connectParams);
              if (statusCode !== 200) {
                socket.on("error", noop).destroy();
                callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`));
                return;
              }
              if (channels.proxyConnected.hasSubscribers) {
                channels.proxyConnected.publish({
                  socket,
                  connectParams
                });
              }
              if (opts2.protocol !== "https:") {
                callback(null, socket);
                return;
              }
              let servername;
              if (this[kRequestTls]) {
                servername = this[kRequestTls].servername;
              } else {
                servername = opts2.servername;
              }
              const connectEndpoint = opts2.allowH2 === false ? this[kConnectEndpointHTTP1] : this[kConnectEndpoint];
              connectEndpoint({ ...opts2, servername, httpSocket: socket }, callback);
            } catch (err) {
              if (err.code === "ERR_TLS_CERT_ALTNAME_INVALID") {
                callback(new SecureProxyConnectionError(err));
              } else {
                callback(err);
              }
            }
          }
        });
      }
      dispatch(opts, handler) {
        const headers = buildHeaders(opts.headers);
        throwIfProxyAuthIsSent(headers);
        if (headers && !("host" in headers) && !("Host" in headers)) {
          const { host } = new URL(opts.origin);
          headers.host = host;
        }
        return this[kAgent].dispatch(
          {
            ...opts,
            headers
          },
          handler
        );
      }
      /**
       * @param {import('../../types/proxy-agent').ProxyAgent.Options | string | URL} opts
       * @returns {URL}
       */
      #getUrl(opts) {
        if (typeof opts === "string") {
          return new URL(opts);
        } else if (opts instanceof URL) {
          return opts;
        } else {
          return new URL(opts.uri);
        }
      }
      [kClose]() {
        const promises = [this[kAgent].close()];
        if (this[kClient]) {
          promises.push(this[kClient].close());
        }
        return Promise.all(promises);
      }
      [kDestroy]() {
        const promises = [this[kAgent].destroy()];
        if (this[kClient]) {
          promises.push(this[kClient].destroy());
        }
        return Promise.all(promises);
      }
    };
    function buildHeaders(headers) {
      if (Array.isArray(headers)) {
        const headersPair = {};
        for (let i = 0; i < headers.length; i += 2) {
          headersPair[headers[i]] = headers[i + 1];
        }
        return headersPair;
      }
      return headers;
    }
    function throwIfProxyAuthIsSent(headers) {
      const existProxyAuth = headers && Object.keys(headers).find((key) => key.toLowerCase() === "proxy-authorization");
      if (existProxyAuth) {
        throw new InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor");
      }
    }
    module.exports = ProxyAgent;
  }
});

// node_modules/undici/lib/dispatcher/env-http-proxy-agent.js
var require_env_http_proxy_agent = __commonJS({
  "node_modules/undici/lib/dispatcher/env-http-proxy-agent.js"(exports, module) {
    "use strict";
    var DispatcherBase = require_dispatcher_base();
    var { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = require_symbols();
    var ProxyAgent = require_proxy_agent();
    var Agent = require_agent();
    var DEFAULT_PORTS = {
      "http:": 80,
      "https:": 443
    };
    var EnvHttpProxyAgent = class extends DispatcherBase {
      #noProxyValue = null;
      #noProxyEntries = null;
      #opts = null;
      constructor(opts = {}) {
        super();
        this.#opts = opts;
        const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts;
        this[kNoProxyAgent] = new Agent(agentOpts);
        const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY;
        if (HTTP_PROXY) {
          this[kHttpProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTP_PROXY });
        } else {
          this[kHttpProxyAgent] = this[kNoProxyAgent];
        }
        const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY;
        if (HTTPS_PROXY) {
          this[kHttpsProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY });
        } else {
          this[kHttpsProxyAgent] = this[kHttpProxyAgent];
        }
        this.#parseNoProxy();
      }
      [kDispatch](opts, handler) {
        const url = new URL(opts.origin);
        const agent = this.#getProxyAgentForUrl(url);
        return agent.dispatch(opts, handler);
      }
      [kClose]() {
        return Promise.all([
          this[kNoProxyAgent].close(),
          !this[kHttpProxyAgent][kClosed] && this[kHttpProxyAgent].close(),
          !this[kHttpsProxyAgent][kClosed] && this[kHttpsProxyAgent].close()
        ]);
      }
      [kDestroy](err) {
        return Promise.all([
          this[kNoProxyAgent].destroy(err),
          !this[kHttpProxyAgent][kDestroyed] && this[kHttpProxyAgent].destroy(err),
          !this[kHttpsProxyAgent][kDestroyed] && this[kHttpsProxyAgent].destroy(err)
        ]);
      }
      #getProxyAgentForUrl(url) {
        let { protocol, host: hostname, port } = url;
        hostname = hostname.replace(/:\d*$/, "").toLowerCase();
        port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0;
        if (!this.#shouldProxy(hostname, port)) {
          return this[kNoProxyAgent];
        }
        if (protocol === "https:") {
          return this[kHttpsProxyAgent];
        }
        return this[kHttpProxyAgent];
      }
      #shouldProxy(hostname, port) {
        if (this.#noProxyChanged) {
          this.#parseNoProxy();
        }
        if (this.#noProxyEntries.length === 0) {
          return true;
        }
        if (this.#noProxyValue === "*") {
          return false;
        }
        for (let i = 0; i < this.#noProxyEntries.length; i++) {
          const entry = this.#noProxyEntries[i];
          if (entry.port && entry.port !== port) {
            continue;
          }
          if (hostname === entry.hostname) {
            return false;
          }
          if (hostname.slice(-(entry.hostname.length + 1)) === `.${entry.hostname}`) {
            return false;
          }
        }
        return true;
      }
      #parseNoProxy() {
        const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv;
        const noProxySplit = noProxyValue.split(/[,\s]/);
        const noProxyEntries = [];
        for (let i = 0; i < noProxySplit.length; i++) {
          const entry = noProxySplit[i];
          if (!entry) {
            continue;
          }
          const parsed = entry.match(/^(.+):(\d+)$/);
          noProxyEntries.push({
            // strip leading dot or asterisk with dot
            hostname: (parsed ? parsed[1] : entry).replace(/^\*?\./, "").toLowerCase(),
            port: parsed ? Number.parseInt(parsed[2], 10) : 0
          });
        }
        this.#noProxyValue = noProxyValue;
        this.#noProxyEntries = noProxyEntries;
      }
      get #noProxyChanged() {
        if (this.#opts.noProxy !== void 0) {
          return false;
        }
        return this.#noProxyValue !== this.#noProxyEnv;
      }
      get #noProxyEnv() {
        return process.env.no_proxy ?? process.env.NO_PROXY ?? "";
      }
    };
    module.exports = EnvHttpProxyAgent;
  }
});

// node_modules/undici/lib/handler/retry-handler.js
var require_retry_handler = __commonJS({
  "node_modules/undici/lib/handler/retry-handler.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var { kRetryHandlerDefaultRetry } = require_symbols();
    var { RequestRetryError } = require_errors();
    var {
      isDisturbed,
      parseRangeHeader,
      wrapRequestBody
    } = require_util();
    function calculateRetryAfterHeader(retryAfter) {
      const retryTime = new Date(retryAfter).getTime();
      return isNaN(retryTime) ? 0 : retryTime - Date.now();
    }
    var RetryHandler = class _RetryHandler {
      constructor(opts, { dispatch, handler }) {
        const { retryOptions, ...dispatchOpts } = opts;
        const {
          // Retry scoped
          retry: retryFn,
          maxRetries,
          maxTimeout,
          minTimeout,
          timeoutFactor,
          // Response scoped
          methods,
          errorCodes,
          retryAfter,
          statusCodes,
          throwOnError
        } = retryOptions ?? {};
        this.error = null;
        this.dispatch = dispatch;
        this.handler = handler;
        this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) };
        this.retryOpts = {
          throwOnError: throwOnError ?? true,
          retry: retryFn ?? _RetryHandler[kRetryHandlerDefaultRetry],
          retryAfter: retryAfter ?? true,
          maxTimeout: maxTimeout ?? 30 * 1e3,
          // 30s,
          minTimeout: minTimeout ?? 500,
          // .5s
          timeoutFactor: timeoutFactor ?? 2,
          maxRetries: maxRetries ?? 5,
          // What errors we should retry
          methods: methods ?? ["GET", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"],
          // Indicates which errors to retry
          statusCodes: statusCodes ?? [500, 502, 503, 504, 429],
          // List of errors to retry
          errorCodes: errorCodes ?? [
            "ECONNRESET",
            "ECONNREFUSED",
            "ENOTFOUND",
            "ENETDOWN",
            "ENETUNREACH",
            "EHOSTDOWN",
            "EHOSTUNREACH",
            "EPIPE",
            "UND_ERR_SOCKET"
          ]
        };
        this.retryCount = 0;
        this.retryCountCheckpoint = 0;
        this.headersSent = false;
        this.start = 0;
        this.end = null;
        this.etag = null;
      }
      onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err) {
        if (this.retryOpts.throwOnError) {
          if (this.retryOpts.statusCodes.includes(statusCode) === false) {
            this.headersSent = true;
            this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
          } else {
            this.error = err;
          }
          return;
        }
        if (isDisturbed(this.opts.body)) {
          this.headersSent = true;
          this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
          return;
        }
        function shouldRetry2(passedErr) {
          if (passedErr) {
            this.headersSent = true;
            this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
            controller.resume();
            return;
          }
          this.error = err;
          controller.resume();
        }
        controller.pause();
        this.retryOpts.retry(
          err,
          {
            state: { counter: this.retryCount },
            opts: { retryOptions: this.retryOpts, ...this.opts }
          },
          shouldRetry2.bind(this)
        );
      }
      onRequestStart(controller, context) {
        if (!this.headersSent) {
          this.handler.onRequestStart?.(controller, context);
        }
      }
      onRequestUpgrade(controller, statusCode, headers, socket) {
        this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
      }
      static [kRetryHandlerDefaultRetry](err, { state, opts }, cb) {
        const { statusCode, code, headers } = err;
        const { method, retryOptions } = opts;
        const {
          maxRetries,
          minTimeout,
          maxTimeout,
          timeoutFactor,
          statusCodes,
          errorCodes,
          methods
        } = retryOptions;
        const { counter } = state;
        if (code && code !== "UND_ERR_REQ_RETRY" && !errorCodes.includes(code)) {
          cb(err);
          return;
        }
        if (Array.isArray(methods) && !methods.includes(method)) {
          cb(err);
          return;
        }
        if (statusCode != null && Array.isArray(statusCodes) && !statusCodes.includes(statusCode)) {
          cb(err);
          return;
        }
        if (counter > maxRetries) {
          cb(err);
          return;
        }
        let retryAfterHeader = headers?.["retry-after"];
        if (retryAfterHeader) {
          retryAfterHeader = Number(retryAfterHeader);
          retryAfterHeader = Number.isNaN(retryAfterHeader) ? calculateRetryAfterHeader(headers["retry-after"]) : retryAfterHeader * 1e3;
        }
        const retryTimeout = retryAfterHeader > 0 ? Math.min(retryAfterHeader, maxTimeout) : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout);
        setTimeout(() => cb(null), retryTimeout);
      }
      onResponseStart(controller, statusCode, headers, statusMessage) {
        this.error = null;
        this.retryCount += 1;
        if (statusCode >= 300) {
          const err = new RequestRetryError("Request failed", statusCode, {
            headers,
            data: {
              count: this.retryCount
            }
          });
          this.onResponseStartWithRetry(controller, statusCode, headers, statusMessage, err);
          return;
        }
        if (this.headersSent) {
          if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) {
            throw new RequestRetryError("server does not support the range header and the payload was partially consumed", statusCode, {
              headers,
              data: { count: this.retryCount }
            });
          }
          const contentRange = parseRangeHeader(headers["content-range"]);
          if (!contentRange) {
            throw new RequestRetryError("Content-Range mismatch", statusCode, {
              headers,
              data: { count: this.retryCount }
            });
          }
          if (this.etag != null && this.etag !== headers.etag) {
            throw new RequestRetryError("ETag mismatch", statusCode, {
              headers,
              data: { count: this.retryCount }
            });
          }
          const { start, size: size5, end = size5 ? size5 - 1 : null } = contentRange;
          assert8(this.start === start, "content-range mismatch");
          assert8(this.end == null || this.end === end, "content-range mismatch");
          return;
        }
        if (this.end == null) {
          if (statusCode === 206) {
            const range = parseRangeHeader(headers["content-range"]);
            if (range == null) {
              this.headersSent = true;
              this.handler.onResponseStart?.(
                controller,
                statusCode,
                headers,
                statusMessage
              );
              return;
            }
            const { start, size: size5, end = size5 ? size5 - 1 : null } = range;
            assert8(
              start != null && Number.isFinite(start),
              "content-range mismatch"
            );
            assert8(end != null && Number.isFinite(end), "invalid content-length");
            this.start = start;
            this.end = end;
          }
          if (this.end == null) {
            const contentLength = headers["content-length"];
            this.end = contentLength != null ? Number(contentLength) - 1 : null;
          }
          assert8(Number.isFinite(this.start));
          assert8(
            this.end == null || Number.isFinite(this.end),
            "invalid content-length"
          );
          this.resume = true;
          this.etag = headers.etag != null ? headers.etag : null;
          if (this.etag != null && this.etag[0] === "W" && this.etag[1] === "/") {
            this.etag = null;
          }
          this.headersSent = true;
          this.handler.onResponseStart?.(
            controller,
            statusCode,
            headers,
            statusMessage
          );
        } else {
          throw new RequestRetryError("Request failed", statusCode, {
            headers,
            data: { count: this.retryCount }
          });
        }
      }
      onResponseData(controller, chunk) {
        if (this.error) {
          return;
        }
        this.start += chunk.length;
        this.handler.onResponseData?.(controller, chunk);
      }
      onResponseEnd(controller, trailers) {
        if (this.error && this.retryOpts.throwOnError) {
          throw this.error;
        }
        if (!this.error) {
          this.retryCount = 0;
          return this.handler.onResponseEnd?.(controller, trailers);
        }
        this.retry(controller);
      }
      retry(controller) {
        if (this.start !== 0) {
          const headers = { range: `bytes=${this.start}-${this.end ?? ""}` };
          if (this.etag != null) {
            headers["if-match"] = this.etag;
          }
          this.opts = {
            ...this.opts,
            headers: {
              ...this.opts.headers,
              ...headers
            }
          };
        }
        try {
          this.retryCountCheckpoint = this.retryCount;
          this.dispatch(this.opts, this);
        } catch (err) {
          this.handler.onResponseError?.(controller, err);
        }
      }
      onResponseError(controller, err) {
        if (controller?.aborted || isDisturbed(this.opts.body)) {
          this.handler.onResponseError?.(controller, err);
          return;
        }
        function shouldRetry2(returnedErr) {
          if (!returnedErr) {
            this.retry(controller);
            return;
          }
          this.handler?.onResponseError?.(controller, returnedErr);
        }
        if (this.retryCount - this.retryCountCheckpoint > 0) {
          this.retryCount = this.retryCountCheckpoint + (this.retryCount - this.retryCountCheckpoint);
        } else {
          this.retryCount += 1;
        }
        this.retryOpts.retry(
          err,
          {
            state: { counter: this.retryCount },
            opts: { retryOptions: this.retryOpts, ...this.opts }
          },
          shouldRetry2.bind(this)
        );
      }
    };
    module.exports = RetryHandler;
  }
});

// node_modules/undici/lib/dispatcher/retry-agent.js
var require_retry_agent = __commonJS({
  "node_modules/undici/lib/dispatcher/retry-agent.js"(exports, module) {
    "use strict";
    var Dispatcher = require_dispatcher();
    var RetryHandler = require_retry_handler();
    var RetryAgent = class extends Dispatcher {
      #agent = null;
      #options = null;
      constructor(agent, options = {}) {
        super(options);
        this.#agent = agent;
        this.#options = options;
      }
      dispatch(opts, handler) {
        const retry = new RetryHandler({
          ...opts,
          retryOptions: this.#options
        }, {
          dispatch: this.#agent.dispatch.bind(this.#agent),
          handler
        });
        return this.#agent.dispatch(opts, retry);
      }
      close() {
        return this.#agent.close();
      }
      destroy() {
        return this.#agent.destroy();
      }
    };
    module.exports = RetryAgent;
  }
});

// node_modules/undici/lib/dispatcher/h2c-client.js
var require_h2c_client = __commonJS({
  "node_modules/undici/lib/dispatcher/h2c-client.js"(exports, module) {
    "use strict";
    var { InvalidArgumentError } = require_errors();
    var Client = require_client();
    var H2CClient = class extends Client {
      constructor(origin, clientOpts) {
        if (typeof origin === "string") {
          origin = new URL(origin);
        }
        if (origin.protocol !== "http:") {
          throw new InvalidArgumentError(
            "h2c-client: Only h2c protocol is supported"
          );
        }
        const { maxConcurrentStreams, pipelining, ...opts } = clientOpts ?? {};
        const defaultMaxConcurrentStreams = maxConcurrentStreams ?? 100;
        let defaultPipelining = 100;
        if (maxConcurrentStreams != null && (!Number.isInteger(maxConcurrentStreams) || maxConcurrentStreams < 1)) {
          throw new InvalidArgumentError("maxConcurrentStreams must be a positive integer, greater than 0");
        }
        if (pipelining != null && Number.isInteger(pipelining) && pipelining > 0) {
          defaultPipelining = pipelining;
        }
        if (defaultPipelining > defaultMaxConcurrentStreams) {
          throw new InvalidArgumentError(
            "h2c-client: pipelining cannot be greater than maxConcurrentStreams"
          );
        }
        super(origin, {
          ...opts,
          maxConcurrentStreams: defaultMaxConcurrentStreams,
          pipelining: defaultPipelining,
          allowH2: true,
          useH2c: true
        });
      }
    };
    module.exports = H2CClient;
  }
});

// node_modules/undici/lib/api/readable.js
var require_readable = __commonJS({
  "node_modules/undici/lib/api/readable.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var { addAbortListener } = __require("events");
    var { Readable } = __require("stream");
    var { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = require_errors();
    var util2 = require_util();
    var { ReadableStreamFrom } = require_util();
    var kConsume = /* @__PURE__ */ Symbol("kConsume");
    var kReading = /* @__PURE__ */ Symbol("kReading");
    var kBody = /* @__PURE__ */ Symbol("kBody");
    var kAbort = /* @__PURE__ */ Symbol("kAbort");
    var kContentType = /* @__PURE__ */ Symbol("kContentType");
    var kContentLength = /* @__PURE__ */ Symbol("kContentLength");
    var kUsed = /* @__PURE__ */ Symbol("kUsed");
    var kBytesRead = /* @__PURE__ */ Symbol("kBytesRead");
    var noop = () => {
    };
    var BodyReadable = class extends Readable {
      /**
       * @param {object} opts
       * @param {(this: Readable, size: number) => void} opts.resume
       * @param {() => (void | null)} opts.abort
       * @param {string} [opts.contentType = '']
       * @param {number} [opts.contentLength]
       * @param {number} [opts.highWaterMark = 64 * 1024]
       */
      constructor({
        resume,
        abort,
        contentType = "",
        contentLength,
        highWaterMark = 64 * 1024
        // Same as nodejs fs streams.
      }) {
        super({
          autoDestroy: true,
          read: resume,
          highWaterMark
        });
        this._readableState.dataEmitted = false;
        this[kAbort] = abort;
        this[kConsume] = null;
        this[kBytesRead] = 0;
        this[kBody] = null;
        this[kUsed] = false;
        this[kContentType] = contentType;
        this[kContentLength] = Number.isFinite(contentLength) ? contentLength : null;
        this[kReading] = false;
      }
      /**
       * @param {Error|null} err
       * @param {(error:(Error|null)) => void} callback
       * @returns {void}
       */
      _destroy(err, callback) {
        if (!err && !this._readableState.endEmitted) {
          err = new RequestAbortedError();
        }
        if (err) {
          this[kAbort]();
        }
        if (!this[kUsed]) {
          setImmediate(callback, err);
        } else {
          callback(err);
        }
      }
      /**
       * @param {string|symbol} event
       * @param {(...args: any[]) => void} listener
       * @returns {this}
       */
      on(event, listener) {
        if (event === "data" || event === "readable") {
          this[kReading] = true;
          this[kUsed] = true;
        }
        return super.on(event, listener);
      }
      /**
       * @param {string|symbol} event
       * @param {(...args: any[]) => void} listener
       * @returns {this}
       */
      addListener(event, listener) {
        return this.on(event, listener);
      }
      /**
       * @param {string|symbol} event
       * @param {(...args: any[]) => void} listener
       * @returns {this}
       */
      off(event, listener) {
        const ret = super.off(event, listener);
        if (event === "data" || event === "readable") {
          this[kReading] = this.listenerCount("data") > 0 || this.listenerCount("readable") > 0;
        }
        return ret;
      }
      /**
       * @param {string|symbol} event
       * @param {(...args: any[]) => void} listener
       * @returns {this}
       */
      removeListener(event, listener) {
        return this.off(event, listener);
      }
      /**
       * @param {Buffer|null} chunk
       * @returns {boolean}
       */
      push(chunk) {
        if (chunk) {
          this[kBytesRead] += chunk.length;
          if (this[kConsume]) {
            consumePush(this[kConsume], chunk);
            return this[kReading] ? super.push(chunk) : true;
          }
        }
        return super.push(chunk);
      }
      /**
       * Consumes and returns the body as a string.
       *
       * @see https://fetch.spec.whatwg.org/#dom-body-text
       * @returns {Promise<string>}
       */
      text() {
        return consume(this, "text");
      }
      /**
       * Consumes and returns the body as a JavaScript Object.
       *
       * @see https://fetch.spec.whatwg.org/#dom-body-json
       * @returns {Promise<unknown>}
       */
      json() {
        return consume(this, "json");
      }
      /**
       * Consumes and returns the body as a Blob
       *
       * @see https://fetch.spec.whatwg.org/#dom-body-blob
       * @returns {Promise<Blob>}
       */
      blob() {
        return consume(this, "blob");
      }
      /**
       * Consumes and returns the body as an Uint8Array.
       *
       * @see https://fetch.spec.whatwg.org/#dom-body-bytes
       * @returns {Promise<Uint8Array>}
       */
      bytes() {
        return consume(this, "bytes");
      }
      /**
       * Consumes and returns the body as an ArrayBuffer.
       *
       * @see https://fetch.spec.whatwg.org/#dom-body-arraybuffer
       * @returns {Promise<ArrayBuffer>}
       */
      arrayBuffer() {
        return consume(this, "arrayBuffer");
      }
      /**
       * Not implemented
       *
       * @see https://fetch.spec.whatwg.org/#dom-body-formdata
       * @throws {NotSupportedError}
       */
      async formData() {
        throw new NotSupportedError();
      }
      /**
       * Returns true if the body is not null and the body has been consumed.
       * Otherwise, returns false.
       *
       * @see https://fetch.spec.whatwg.org/#dom-body-bodyused
       * @readonly
       * @returns {boolean}
       */
      get bodyUsed() {
        return util2.isDisturbed(this);
      }
      /**
       * @see https://fetch.spec.whatwg.org/#dom-body-body
       * @readonly
       * @returns {ReadableStream}
       */
      get body() {
        if (!this[kBody]) {
          this[kBody] = ReadableStreamFrom(this);
          if (this[kConsume]) {
            this[kBody].getReader();
            assert8(this[kBody].locked);
          }
        }
        return this[kBody];
      }
      /**
       * Dumps the response body by reading `limit` number of bytes.
       * @param {object} opts
       * @param {number} [opts.limit = 131072] Number of bytes to read.
       * @param {AbortSignal} [opts.signal] An AbortSignal to cancel the dump.
       * @returns {Promise<null>}
       */
      dump(opts) {
        const signal = opts?.signal;
        if (signal != null && (typeof signal !== "object" || !("aborted" in signal))) {
          return Promise.reject(new InvalidArgumentError("signal must be an AbortSignal"));
        }
        const limit = opts?.limit && Number.isFinite(opts.limit) ? opts.limit : 128 * 1024;
        if (signal?.aborted) {
          return Promise.reject(signal.reason ?? new AbortError());
        }
        if (this._readableState.closeEmitted) {
          return Promise.resolve(null);
        }
        return new Promise((resolve, reject) => {
          if (this[kContentLength] && this[kContentLength] > limit || this[kBytesRead] > limit) {
            this.destroy(new AbortError());
          }
          if (signal) {
            const onAbort = () => {
              this.destroy(signal.reason ?? new AbortError());
            };
            const abortListener = addAbortListener(signal, onAbort);
            this.on("close", function() {
              abortListener[Symbol.dispose]();
              if (signal.aborted) {
                reject(signal.reason ?? new AbortError());
              } else {
                resolve(null);
              }
            });
          } else {
            this.on("close", resolve);
          }
          this.on("error", noop).on("data", () => {
            if (this[kBytesRead] > limit) {
              this.destroy();
            }
          }).resume();
        });
      }
      /**
       * @param {BufferEncoding} encoding
       * @returns {this}
       */
      setEncoding(encoding) {
        if (Buffer.isEncoding(encoding)) {
          this._readableState.encoding = encoding;
        }
        return this;
      }
    };
    function isLocked(bodyReadable) {
      return bodyReadable[kBody]?.locked === true || bodyReadable[kConsume] !== null;
    }
    function isUnusable(bodyReadable) {
      return util2.isDisturbed(bodyReadable) || isLocked(bodyReadable);
    }
    function consume(stream, type) {
      assert8(!stream[kConsume]);
      return new Promise((resolve, reject) => {
        if (isUnusable(stream)) {
          const rState = stream._readableState;
          if (rState.destroyed && rState.closeEmitted === false) {
            stream.on("error", reject).on("close", () => {
              reject(new TypeError("unusable"));
            });
          } else {
            reject(rState.errored ?? new TypeError("unusable"));
          }
        } else {
          queueMicrotask(() => {
            stream[kConsume] = {
              type,
              stream,
              resolve,
              reject,
              length: 0,
              body: []
            };
            stream.on("error", function(err) {
              consumeFinish(this[kConsume], err);
            }).on("close", function() {
              if (this[kConsume].body !== null) {
                consumeFinish(this[kConsume], new RequestAbortedError());
              }
            });
            consumeStart(stream[kConsume]);
          });
        }
      });
    }
    function consumeStart(consume2) {
      if (consume2.body === null) {
        return;
      }
      const { _readableState: state } = consume2.stream;
      if (state.bufferIndex) {
        const start = state.bufferIndex;
        const end = state.buffer.length;
        for (let n = start; n < end; n++) {
          consumePush(consume2, state.buffer[n]);
        }
      } else {
        for (const chunk of state.buffer) {
          consumePush(consume2, chunk);
        }
      }
      if (state.endEmitted) {
        consumeEnd(this[kConsume], this._readableState.encoding);
      } else {
        consume2.stream.on("end", function() {
          consumeEnd(this[kConsume], this._readableState.encoding);
        });
      }
      consume2.stream.resume();
      while (consume2.stream.read() != null) {
      }
    }
    function chunksDecode(chunks, length, encoding) {
      if (chunks.length === 0 || length === 0) {
        return "";
      }
      const buffer2 = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length);
      const bufferLength = buffer2.length;
      const start = bufferLength > 2 && buffer2[0] === 239 && buffer2[1] === 187 && buffer2[2] === 191 ? 3 : 0;
      if (!encoding || encoding === "utf8" || encoding === "utf-8") {
        return buffer2.utf8Slice(start, bufferLength);
      } else {
        return buffer2.subarray(start, bufferLength).toString(encoding);
      }
    }
    function chunksConcat(chunks, length) {
      if (chunks.length === 0 || length === 0) {
        return new Uint8Array(0);
      }
      if (chunks.length === 1) {
        return new Uint8Array(chunks[0]);
      }
      const buffer2 = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer);
      let offset = 0;
      for (let i = 0; i < chunks.length; ++i) {
        const chunk = chunks[i];
        buffer2.set(chunk, offset);
        offset += chunk.length;
      }
      return buffer2;
    }
    function consumeEnd(consume2, encoding) {
      const { type, body, resolve, stream, length } = consume2;
      try {
        if (type === "text") {
          resolve(chunksDecode(body, length, encoding));
        } else if (type === "json") {
          resolve(JSON.parse(chunksDecode(body, length, encoding)));
        } else if (type === "arrayBuffer") {
          resolve(chunksConcat(body, length).buffer);
        } else if (type === "blob") {
          resolve(new Blob(body, { type: stream[kContentType] }));
        } else if (type === "bytes") {
          resolve(chunksConcat(body, length));
        }
        consumeFinish(consume2);
      } catch (err) {
        stream.destroy(err);
      }
    }
    function consumePush(consume2, chunk) {
      consume2.length += chunk.length;
      consume2.body.push(chunk);
    }
    function consumeFinish(consume2, err) {
      if (consume2.body === null) {
        return;
      }
      if (err) {
        consume2.reject(err);
      } else {
        consume2.resolve();
      }
      consume2.type = null;
      consume2.stream = null;
      consume2.resolve = null;
      consume2.reject = null;
      consume2.length = 0;
      consume2.body = null;
    }
    module.exports = {
      Readable: BodyReadable,
      chunksDecode
    };
  }
});

// node_modules/undici/lib/api/api-request.js
var require_api_request = __commonJS({
  "node_modules/undici/lib/api/api-request.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var { AsyncResource } = __require("async_hooks");
    var { Readable } = require_readable();
    var { InvalidArgumentError, RequestAbortedError } = require_errors();
    var util2 = require_util();
    function noop() {
    }
    var RequestHandler = class extends AsyncResource {
      constructor(opts, callback) {
        if (!opts || typeof opts !== "object") {
          throw new InvalidArgumentError("invalid opts");
        }
        const { signal, method, opaque, body, onInfo, responseHeaders, highWaterMark } = opts;
        try {
          if (typeof callback !== "function") {
            throw new InvalidArgumentError("invalid callback");
          }
          if (highWaterMark != null && (!Number.isFinite(highWaterMark) || highWaterMark < 0)) {
            throw new InvalidArgumentError("invalid highWaterMark");
          }
          if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
            throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
          }
          if (method === "CONNECT") {
            throw new InvalidArgumentError("invalid method");
          }
          if (onInfo && typeof onInfo !== "function") {
            throw new InvalidArgumentError("invalid onInfo callback");
          }
          super("UNDICI_REQUEST");
        } catch (err) {
          if (util2.isStream(body)) {
            util2.destroy(body.on("error", noop), err);
          }
          throw err;
        }
        this.method = method;
        this.responseHeaders = responseHeaders || null;
        this.opaque = opaque || null;
        this.callback = callback;
        this.res = null;
        this.abort = null;
        this.body = body;
        this.trailers = {};
        this.context = null;
        this.controller = null;
        this.onInfo = onInfo || null;
        this.highWaterMark = highWaterMark;
        this.reason = null;
        this.removeAbortListener = null;
        if (signal?.aborted) {
          this.reason = signal.reason ?? new RequestAbortedError();
        } else if (signal) {
          this.removeAbortListener = util2.addAbortListener(signal, () => {
            this.reason = signal.reason ?? new RequestAbortedError();
            if (this.res) {
              util2.destroy(this.res.on("error", noop), this.reason);
            } else if (this.abort) {
              this.abort(this.reason);
            }
          });
        }
      }
      onRequestStart(controller, context) {
        if (this.reason) {
          controller.abort(this.reason);
          return;
        }
        assert8(this.callback);
        this.controller = controller;
        this.abort = (reason) => controller.abort(reason);
        this.context = context;
      }
      onResponseStart(controller, statusCode, headers, statusText) {
        const { callback, opaque, context, responseHeaders, highWaterMark } = this;
        const rawHeaders = controller?.rawHeaders;
        const responseHeaderData = responseHeaders === "raw" ? util2.parseRawHeaders(rawHeaders) : headers;
        if (statusCode < 200) {
          if (this.onInfo) {
            this.onInfo({ statusCode, headers: responseHeaderData });
          }
          return;
        }
        const parsedHeaders = headers;
        const contentType = parsedHeaders?.["content-type"];
        const contentLength = parsedHeaders?.["content-length"];
        const res = new Readable({
          resume: () => controller.resume(),
          abort: (reason) => controller.abort(reason),
          contentType,
          contentLength: this.method !== "HEAD" && contentLength ? Number(contentLength) : null,
          highWaterMark
        });
        if (this.removeAbortListener) {
          res.on("close", this.removeAbortListener);
          this.removeAbortListener = null;
        }
        this.callback = null;
        this.res = res;
        if (callback !== null) {
          try {
            this.runInAsyncScope(callback, null, null, {
              statusCode,
              statusText,
              headers: responseHeaderData,
              trailers: this.trailers,
              opaque,
              body: res,
              context
            });
          } catch (err) {
            this.res = null;
            util2.destroy(res.on("error", noop), err);
            queueMicrotask(() => {
              throw err;
            });
          }
        }
      }
      onResponseData(controller, chunk) {
        if (!this.res) {
          return;
        }
        if (this.res.push(chunk) === false) {
          controller.pause();
        }
      }
      onResponseEnd(_controller, trailers) {
        if (trailers && typeof trailers === "object") {
          for (const key of Object.keys(trailers)) {
            if (key === "__proto__") {
              Object.defineProperty(this.trailers, key, {
                value: trailers[key],
                enumerable: true,
                configurable: true,
                writable: true
              });
            } else {
              this.trailers[key] = trailers[key];
            }
          }
        }
        this.res?.push(null);
      }
      onResponseError(_controller, err) {
        const { res, callback, body, opaque } = this;
        if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err, { opaque });
          });
        }
        if (res) {
          this.res = null;
          queueMicrotask(() => {
            util2.destroy(res.on("error", noop), err);
          });
        }
        if (body) {
          this.body = null;
          if (util2.isStream(body)) {
            body.on("error", noop);
            util2.destroy(body, err);
          }
        }
        if (this.removeAbortListener) {
          this.removeAbortListener();
          this.removeAbortListener = null;
        }
      }
    };
    function request(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve, reject) => {
          request.call(this, opts, (err, data) => {
            return err ? reject(err) : resolve(data);
          });
        });
      }
      try {
        const handler = new RequestHandler(opts, callback);
        this.dispatch(opts, handler);
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    module.exports = request;
    module.exports.RequestHandler = RequestHandler;
  }
});

// node_modules/undici/lib/api/abort-signal.js
var require_abort_signal = __commonJS({
  "node_modules/undici/lib/api/abort-signal.js"(exports, module) {
    "use strict";
    var { addAbortListener } = require_util();
    var { RequestAbortedError } = require_errors();
    var kListener = /* @__PURE__ */ Symbol("kListener");
    var kSignal = /* @__PURE__ */ Symbol("kSignal");
    function abort(self) {
      if (self.abort) {
        self.abort(self[kSignal]?.reason);
      } else {
        self.reason = self[kSignal]?.reason ?? new RequestAbortedError();
      }
      removeSignal(self);
    }
    function addSignal(self, signal) {
      self.reason = null;
      self[kSignal] = null;
      self[kListener] = null;
      if (!signal) {
        return;
      }
      if (signal.aborted) {
        abort(self);
        return;
      }
      self[kSignal] = signal;
      self[kListener] = () => {
        abort(self);
      };
      addAbortListener(self[kSignal], self[kListener]);
    }
    function removeSignal(self) {
      if (!self[kSignal]) {
        return;
      }
      if ("removeEventListener" in self[kSignal]) {
        self[kSignal].removeEventListener("abort", self[kListener]);
      } else {
        self[kSignal].removeListener("abort", self[kListener]);
      }
      self[kSignal] = null;
      self[kListener] = null;
    }
    module.exports = {
      addSignal,
      removeSignal
    };
  }
});

// node_modules/undici/lib/api/api-stream.js
var require_api_stream = __commonJS({
  "node_modules/undici/lib/api/api-stream.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var { finished: finished2 } = __require("stream");
    var { AsyncResource } = __require("async_hooks");
    var { InvalidArgumentError, InvalidReturnValueError } = require_errors();
    var util2 = require_util();
    var { addSignal, removeSignal } = require_abort_signal();
    function noop() {
    }
    var StreamHandler = class extends AsyncResource {
      constructor(opts, factory, callback) {
        if (!opts || typeof opts !== "object") {
          throw new InvalidArgumentError("invalid opts");
        }
        const { signal, method, opaque, body, onInfo, responseHeaders } = opts;
        try {
          if (typeof callback !== "function") {
            throw new InvalidArgumentError("invalid callback");
          }
          if (typeof factory !== "function") {
            throw new InvalidArgumentError("invalid factory");
          }
          if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
            throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
          }
          if (method === "CONNECT") {
            throw new InvalidArgumentError("invalid method");
          }
          if (onInfo && typeof onInfo !== "function") {
            throw new InvalidArgumentError("invalid onInfo callback");
          }
          super("UNDICI_STREAM");
        } catch (err) {
          if (util2.isStream(body)) {
            util2.destroy(body.on("error", noop), err);
          }
          throw err;
        }
        this.responseHeaders = responseHeaders || null;
        this.opaque = opaque || null;
        this.factory = factory;
        this.callback = callback;
        this.res = null;
        this.abort = null;
        this.context = null;
        this.controller = null;
        this.trailers = null;
        this.body = body;
        this.onInfo = onInfo || null;
        if (util2.isStream(body)) {
          body.on("error", (err) => {
            this.onResponseError(this.controller, err);
          });
        }
        addSignal(this, signal);
      }
      onRequestStart(controller, context) {
        if (this.reason) {
          controller.abort(this.reason);
          return;
        }
        assert8(this.callback);
        this.controller = controller;
        this.abort = (reason) => controller.abort(reason);
        this.context = context;
      }
      onResponseStart(controller, statusCode, headers, _statusMessage) {
        const { factory, opaque, context, responseHeaders } = this;
        const rawHeaders = controller?.rawHeaders;
        const responseHeaderData = responseHeaders === "raw" ? util2.parseRawHeaders(rawHeaders) : headers;
        if (statusCode < 200) {
          if (this.onInfo) {
            this.onInfo({ statusCode, headers: responseHeaderData });
          }
          return;
        }
        this.factory = null;
        if (factory === null) {
          return;
        }
        const res = this.runInAsyncScope(factory, null, {
          statusCode,
          headers: responseHeaderData,
          opaque,
          context
        });
        if (!res || typeof res.write !== "function" || typeof res.end !== "function" || typeof res.on !== "function") {
          throw new InvalidReturnValueError("expected Writable");
        }
        finished2(res, { readable: false }, (err) => {
          const { callback, res: res2, opaque: opaque2, trailers, abort } = this;
          this.res = null;
          if (err || !res2?.readable) {
            util2.destroy(res2, err);
          }
          this.callback = null;
          this.runInAsyncScope(callback, null, err || null, { opaque: opaque2, trailers });
          if (err) {
            abort();
          }
        });
        res.on("drain", () => controller.resume());
        this.res = res;
        const needDrain = res.writableNeedDrain !== void 0 ? res.writableNeedDrain : res._writableState?.needDrain;
        if (needDrain === true) {
          controller.pause();
        }
      }
      onResponseData(controller, chunk) {
        const { res } = this;
        if (!res) {
          return;
        }
        if (res.write(chunk) === false) {
          controller.pause();
        }
      }
      onResponseEnd(_controller, trailers) {
        const { res } = this;
        removeSignal(this);
        if (!res) {
          return;
        }
        if (trailers && typeof trailers === "object") {
          this.trailers = trailers;
        }
        res.end();
      }
      onResponseError(_controller, err) {
        const { res, callback, opaque, body } = this;
        removeSignal(this);
        this.factory = null;
        if (res) {
          this.res = null;
          util2.destroy(res, err);
        } else if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err, { opaque });
          });
        }
        if (body) {
          this.body = null;
          util2.destroy(body, err);
        }
      }
    };
    function stream(opts, factory, callback) {
      if (callback === void 0) {
        return new Promise((resolve, reject) => {
          stream.call(this, opts, factory, (err, data) => {
            return err ? reject(err) : resolve(data);
          });
        });
      }
      try {
        const handler = new StreamHandler(opts, factory, callback);
        this.dispatch(opts, handler);
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    module.exports = stream;
  }
});

// node_modules/undici/lib/api/api-pipeline.js
var require_api_pipeline = __commonJS({
  "node_modules/undici/lib/api/api-pipeline.js"(exports, module) {
    "use strict";
    var {
      Readable,
      Duplex,
      PassThrough
    } = __require("stream");
    var assert8 = __require("assert");
    var { AsyncResource } = __require("async_hooks");
    var {
      InvalidArgumentError,
      InvalidReturnValueError,
      RequestAbortedError
    } = require_errors();
    var util2 = require_util();
    var { addSignal, removeSignal } = require_abort_signal();
    function noop() {
    }
    var kResume = /* @__PURE__ */ Symbol("resume");
    var PipelineRequest = class extends Readable {
      constructor() {
        super({ autoDestroy: true });
        this[kResume] = null;
      }
      _read() {
        const { [kResume]: resume } = this;
        if (resume) {
          this[kResume] = null;
          resume();
        }
      }
      _destroy(err, callback) {
        this._read();
        callback(err);
      }
    };
    var PipelineResponse = class extends Readable {
      constructor(resume) {
        super({ autoDestroy: true });
        this[kResume] = resume;
      }
      _read() {
        this[kResume]();
      }
      _destroy(err, callback) {
        if (!err && !this._readableState.endEmitted) {
          err = new RequestAbortedError();
        }
        callback(err);
      }
    };
    var PipelineHandler = class extends AsyncResource {
      constructor(opts, handler) {
        if (!opts || typeof opts !== "object") {
          throw new InvalidArgumentError("invalid opts");
        }
        if (typeof handler !== "function") {
          throw new InvalidArgumentError("invalid handler");
        }
        const { signal, method, opaque, onInfo, responseHeaders } = opts;
        if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
          throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
        }
        if (method === "CONNECT") {
          throw new InvalidArgumentError("invalid method");
        }
        if (onInfo && typeof onInfo !== "function") {
          throw new InvalidArgumentError("invalid onInfo callback");
        }
        super("UNDICI_PIPELINE");
        this.opaque = opaque || null;
        this.responseHeaders = responseHeaders || null;
        this.handler = handler;
        this.abort = null;
        this.context = null;
        this.onInfo = onInfo || null;
        this.req = new PipelineRequest().on("error", noop);
        this.ret = new Duplex({
          readableObjectMode: opts.objectMode,
          autoDestroy: true,
          read: () => {
            const { body } = this;
            if (body?.resume) {
              body.resume();
            }
          },
          write: (chunk, encoding, callback) => {
            const { req } = this;
            if (req.push(chunk, encoding) || req._readableState.destroyed) {
              callback();
            } else {
              req[kResume] = callback;
            }
          },
          destroy: (err, callback) => {
            const { body, req, res, ret, abort } = this;
            if (!err && !ret._readableState.endEmitted) {
              err = new RequestAbortedError();
            }
            if (abort && err) {
              abort();
            }
            util2.destroy(body, err);
            util2.destroy(req, err);
            util2.destroy(res, err);
            removeSignal(this);
            callback(err);
          }
        }).on("prefinish", () => {
          const { req } = this;
          req.push(null);
        });
        this.res = null;
        addSignal(this, signal);
      }
      onRequestStart(controller, context) {
        const { res } = this;
        if (this.reason) {
          controller.abort(this.reason);
          return;
        }
        assert8(!res, "pipeline cannot be retried");
        this.abort = (reason) => controller.abort(reason);
        this.context = context;
      }
      onResponseStart(controller, statusCode, headers, _statusMessage) {
        const { opaque, handler, context } = this;
        if (statusCode < 200) {
          if (this.onInfo) {
            const rawHeaders = controller?.rawHeaders;
            const responseHeaders = this.responseHeaders === "raw" ? util2.parseRawHeaders(rawHeaders) : headers;
            this.onInfo({ statusCode, headers: responseHeaders });
          }
          return;
        }
        this.res = new PipelineResponse(() => controller.resume());
        let body;
        try {
          this.handler = null;
          const rawHeaders = controller?.rawHeaders;
          const responseHeaders = this.responseHeaders === "raw" ? util2.parseRawHeaders(rawHeaders) : headers;
          body = this.runInAsyncScope(handler, null, {
            statusCode,
            headers: responseHeaders,
            opaque,
            body: this.res,
            context
          });
        } catch (err) {
          this.res.on("error", noop);
          throw err;
        }
        if (!body || typeof body.on !== "function") {
          throw new InvalidReturnValueError("expected Readable");
        }
        body.on("data", (chunk) => {
          const { ret, body: body2 } = this;
          if (!ret.push(chunk) && body2.pause) {
            body2.pause();
          }
        }).on("error", (err) => {
          const { ret } = this;
          util2.destroy(ret, err);
        }).on("end", () => {
          const { ret } = this;
          ret.push(null);
        }).on("close", () => {
          const { ret } = this;
          if (!ret._readableState.ended) {
            util2.destroy(ret, new RequestAbortedError());
          }
        });
        this.body = body;
      }
      onResponseData(controller, chunk) {
        const { res } = this;
        if (res.push(chunk) === false) {
          controller.pause();
        }
      }
      onResponseEnd(_controller, _trailers) {
        const { res } = this;
        res.push(null);
      }
      onResponseError(_controller, err) {
        const { ret } = this;
        this.handler = null;
        util2.destroy(ret, err);
      }
    };
    function pipeline(opts, handler) {
      try {
        const pipelineHandler = new PipelineHandler(opts, handler);
        this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler);
        return pipelineHandler.ret;
      } catch (err) {
        return new PassThrough().destroy(err);
      }
    }
    module.exports = pipeline;
  }
});

// node_modules/undici/lib/api/api-upgrade.js
var require_api_upgrade = __commonJS({
  "node_modules/undici/lib/api/api-upgrade.js"(exports, module) {
    "use strict";
    var { InvalidArgumentError, SocketError } = require_errors();
    var { AsyncResource } = __require("async_hooks");
    var assert8 = __require("assert");
    var util2 = require_util();
    var { kHTTP2Stream } = require_symbols();
    var { addSignal, removeSignal } = require_abort_signal();
    var UpgradeHandler = class extends AsyncResource {
      constructor(opts, callback) {
        if (!opts || typeof opts !== "object") {
          throw new InvalidArgumentError("invalid opts");
        }
        if (typeof callback !== "function") {
          throw new InvalidArgumentError("invalid callback");
        }
        const { signal, opaque, responseHeaders } = opts;
        if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
          throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
        }
        super("UNDICI_UPGRADE");
        this.responseHeaders = responseHeaders || null;
        this.opaque = opaque || null;
        this.callback = callback;
        this.abort = null;
        this.context = null;
        addSignal(this, signal);
      }
      onRequestStart(controller, context) {
        if (this.reason) {
          controller.abort(this.reason);
          return;
        }
        assert8(this.callback);
        this.abort = (reason) => controller.abort(reason);
        this.context = context;
      }
      onResponseStart() {
        throw new SocketError("bad upgrade", null);
      }
      onRequestUpgrade(controller, statusCode, headers, socket) {
        const expectedStatusCode = socket[kHTTP2Stream] === true ? 200 : 101;
        if (statusCode !== expectedStatusCode) {
          const socketInfo = socket[kHTTP2Stream] === true ? null : util2.getSocketInfo(socket);
          controller.abort(new SocketError("bad upgrade", socketInfo));
          return;
        }
        const { callback, opaque, context } = this;
        removeSignal(this);
        this.callback = null;
        const rawHeaders = controller?.rawHeaders;
        const responseHeaders = this.responseHeaders === "raw" ? util2.parseRawHeaders(rawHeaders) : headers;
        this.runInAsyncScope(callback, null, null, {
          headers: responseHeaders,
          socket,
          opaque,
          context
        });
      }
      onResponseError(_controller, err) {
        const { callback, opaque } = this;
        removeSignal(this);
        if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err, { opaque });
          });
        }
      }
    };
    function upgrade(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve, reject) => {
          upgrade.call(this, opts, (err, data) => {
            return err ? reject(err) : resolve(data);
          });
        });
      }
      try {
        const upgradeHandler = new UpgradeHandler(opts, callback);
        const upgradeOpts = {
          ...opts,
          method: opts.method || "GET",
          upgrade: opts.protocol || "Websocket"
        };
        this.dispatch(upgradeOpts, upgradeHandler);
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    module.exports = upgrade;
  }
});

// node_modules/undici/lib/api/api-connect.js
var require_api_connect = __commonJS({
  "node_modules/undici/lib/api/api-connect.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var { AsyncResource } = __require("async_hooks");
    var { InvalidArgumentError, SocketError } = require_errors();
    var util2 = require_util();
    var { addSignal, removeSignal } = require_abort_signal();
    var ConnectHandler = class extends AsyncResource {
      constructor(opts, callback) {
        if (!opts || typeof opts !== "object") {
          throw new InvalidArgumentError("invalid opts");
        }
        if (typeof callback !== "function") {
          throw new InvalidArgumentError("invalid callback");
        }
        const { signal, opaque, responseHeaders } = opts;
        if (signal && typeof signal.on !== "function" && typeof signal.addEventListener !== "function") {
          throw new InvalidArgumentError("signal must be an EventEmitter or EventTarget");
        }
        super("UNDICI_CONNECT");
        this.opaque = opaque || null;
        this.responseHeaders = responseHeaders || null;
        this.callback = callback;
        this.abort = null;
        addSignal(this, signal);
      }
      onRequestStart(controller, context) {
        if (this.reason) {
          controller.abort(this.reason);
          return;
        }
        assert8(this.callback);
        this.abort = (reason) => controller.abort(reason);
        this.context = context;
      }
      onResponseStart() {
        throw new SocketError("bad connect", null);
      }
      onRequestUpgrade(controller, statusCode, headers, socket) {
        const { callback, opaque, context } = this;
        removeSignal(this);
        this.callback = null;
        let responseHeaders = headers;
        const rawHeaders = controller?.rawHeaders;
        if (responseHeaders != null) {
          responseHeaders = this.responseHeaders === "raw" ? util2.parseRawHeaders(rawHeaders) : headers;
        }
        this.runInAsyncScope(callback, null, null, {
          statusCode,
          headers: responseHeaders,
          socket,
          opaque,
          context
        });
      }
      onResponseError(_controller, err) {
        const { callback, opaque } = this;
        removeSignal(this);
        if (callback) {
          this.callback = null;
          queueMicrotask(() => {
            this.runInAsyncScope(callback, null, err, { opaque });
          });
        }
      }
    };
    function connect(opts, callback) {
      if (callback === void 0) {
        return new Promise((resolve, reject) => {
          connect.call(this, opts, (err, data) => {
            return err ? reject(err) : resolve(data);
          });
        });
      }
      try {
        const connectHandler = new ConnectHandler(opts, callback);
        const connectOptions = { ...opts, method: "CONNECT" };
        this.dispatch(connectOptions, connectHandler);
      } catch (err) {
        if (typeof callback !== "function") {
          throw err;
        }
        const opaque = opts?.opaque;
        queueMicrotask(() => callback(err, { opaque }));
      }
    }
    module.exports = connect;
  }
});

// node_modules/undici/lib/api/index.js
var require_api = __commonJS({
  "node_modules/undici/lib/api/index.js"(exports, module) {
    "use strict";
    module.exports.request = require_api_request();
    module.exports.stream = require_api_stream();
    module.exports.pipeline = require_api_pipeline();
    module.exports.upgrade = require_api_upgrade();
    module.exports.connect = require_api_connect();
  }
});

// node_modules/undici/lib/mock/mock-errors.js
var require_mock_errors = __commonJS({
  "node_modules/undici/lib/mock/mock-errors.js"(exports, module) {
    "use strict";
    var { UndiciError } = require_errors();
    var kMockNotMatchedError = /* @__PURE__ */ Symbol.for("undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED");
    var MockNotMatchedError = class extends UndiciError {
      constructor(message) {
        super(message);
        this.name = "MockNotMatchedError";
        this.message = message || "The request does not match any registered mock dispatches";
        this.code = "UND_MOCK_ERR_MOCK_NOT_MATCHED";
      }
      static [Symbol.hasInstance](instance) {
        return instance && instance[kMockNotMatchedError] === true;
      }
      get [kMockNotMatchedError]() {
        return true;
      }
    };
    module.exports = {
      MockNotMatchedError
    };
  }
});

// node_modules/undici/lib/mock/mock-symbols.js
var require_mock_symbols = __commonJS({
  "node_modules/undici/lib/mock/mock-symbols.js"(exports, module) {
    "use strict";
    module.exports = {
      kAgent: /* @__PURE__ */ Symbol("agent"),
      kOptions: /* @__PURE__ */ Symbol("options"),
      kFactory: /* @__PURE__ */ Symbol("factory"),
      kDispatches: /* @__PURE__ */ Symbol("dispatches"),
      kDispatchKey: /* @__PURE__ */ Symbol("dispatch key"),
      kDefaultHeaders: /* @__PURE__ */ Symbol("default headers"),
      kDefaultTrailers: /* @__PURE__ */ Symbol("default trailers"),
      kContentLength: /* @__PURE__ */ Symbol("content length"),
      kMockAgent: /* @__PURE__ */ Symbol("mock agent"),
      kMockAgentSet: /* @__PURE__ */ Symbol("mock agent set"),
      kMockAgentGet: /* @__PURE__ */ Symbol("mock agent get"),
      kMockDispatch: /* @__PURE__ */ Symbol("mock dispatch"),
      kClose: /* @__PURE__ */ Symbol("close"),
      kOriginalClose: /* @__PURE__ */ Symbol("original agent close"),
      kOriginalDispatch: /* @__PURE__ */ Symbol("original dispatch"),
      kOrigin: /* @__PURE__ */ Symbol("origin"),
      kIsMockActive: /* @__PURE__ */ Symbol("is mock active"),
      kNetConnect: /* @__PURE__ */ Symbol("net connect"),
      kGetNetConnect: /* @__PURE__ */ Symbol("get net connect"),
      kConnected: /* @__PURE__ */ Symbol("connected"),
      kIgnoreTrailingSlash: /* @__PURE__ */ Symbol("ignore trailing slash"),
      kMockAgentMockCallHistoryInstance: /* @__PURE__ */ Symbol("mock agent mock call history name"),
      kMockAgentRegisterCallHistory: /* @__PURE__ */ Symbol("mock agent register mock call history"),
      kMockAgentAddCallHistoryLog: /* @__PURE__ */ Symbol("mock agent add call history log"),
      kMockAgentIsCallHistoryEnabled: /* @__PURE__ */ Symbol("mock agent is call history enabled"),
      kMockAgentAcceptsNonStandardSearchParameters: /* @__PURE__ */ Symbol("mock agent accepts non standard search parameters"),
      kMockCallHistoryAddLog: /* @__PURE__ */ Symbol("mock call history add log"),
      kTotalDispatchCount: /* @__PURE__ */ Symbol("total dispatch count")
    };
  }
});

// node_modules/undici/lib/mock/mock-utils.js
var require_mock_utils = __commonJS({
  "node_modules/undici/lib/mock/mock-utils.js"(exports, module) {
    "use strict";
    var { MockNotMatchedError } = require_mock_errors();
    var {
      kDispatches,
      kMockAgent,
      kOriginalDispatch,
      kOrigin,
      kGetNetConnect,
      kTotalDispatchCount
    } = require_mock_symbols();
    var { serializePathWithQuery, parseHeaders } = require_util();
    var { STATUS_CODES } = __require("http");
    var {
      types: {
        isPromise
      }
    } = __require("util");
    var { InvalidArgumentError } = require_errors();
    function matchValue(match, value) {
      if (typeof match === "string") {
        return match === value;
      }
      if (match instanceof RegExp) {
        return match.test(value);
      }
      if (typeof match === "function") {
        return match(value) === true;
      }
      return false;
    }
    function lowerCaseEntries(headers) {
      return Object.fromEntries(
        Object.entries(headers).map(([headerName, headerValue]) => {
          return [headerName.toLocaleLowerCase(), headerValue];
        })
      );
    }
    function getHeaderByName(headers, key) {
      if (Array.isArray(headers)) {
        for (let i = 0; i < headers.length; i += 2) {
          if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {
            return headers[i + 1];
          }
        }
        return void 0;
      } else if (typeof headers.get === "function") {
        return headers.get(key);
      } else {
        return lowerCaseEntries(headers)[key.toLocaleLowerCase()];
      }
    }
    function buildHeadersFromArray(headers) {
      const clone = headers.slice();
      const entries = [];
      for (let index2 = 0; index2 < clone.length; index2 += 2) {
        entries.push([clone[index2], clone[index2 + 1]]);
      }
      return Object.fromEntries(entries);
    }
    function matchHeaders(mockDispatch2, headers) {
      if (typeof mockDispatch2.headers === "function") {
        if (Array.isArray(headers)) {
          headers = buildHeadersFromArray(headers);
        }
        return mockDispatch2.headers(headers ? lowerCaseEntries(headers) : {});
      }
      if (typeof mockDispatch2.headers === "undefined") {
        return true;
      }
      if (typeof headers !== "object" || typeof mockDispatch2.headers !== "object") {
        return false;
      }
      for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch2.headers)) {
        const headerValue = getHeaderByName(headers, matchHeaderName);
        if (!matchValue(matchHeaderValue, headerValue)) {
          return false;
        }
      }
      return true;
    }
    function normalizeSearchParams(query) {
      if (typeof query !== "string") {
        return query;
      }
      const originalQp = new URLSearchParams(query);
      const normalizedQp = new URLSearchParams();
      for (let [key, value] of originalQp.entries()) {
        key = key.replace("[]", "");
        const valueRepresentsString = /^(['"]).*\1$/.test(value);
        if (valueRepresentsString) {
          normalizedQp.append(key, value);
          continue;
        }
        if (value.includes(",")) {
          const values = value.split(",");
          for (const v of values) {
            normalizedQp.append(key, v);
          }
          continue;
        }
        normalizedQp.append(key, value);
      }
      return normalizedQp;
    }
    function safeUrl(path2) {
      if (typeof path2 !== "string") {
        return path2;
      }
      const pathSegments = path2.split("?", 3);
      if (pathSegments.length !== 2) {
        return path2;
      }
      const qp = new URLSearchParams(pathSegments.pop());
      qp.sort();
      return [...pathSegments, qp.toString()].join("?");
    }
    function matchKey(mockDispatch2, { path: path2, method, body, headers }) {
      const pathMatch = matchValue(mockDispatch2.path, path2);
      const methodMatch = matchValue(mockDispatch2.method, method);
      const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
      const headersMatch = matchHeaders(mockDispatch2, headers);
      return pathMatch && methodMatch && bodyMatch && headersMatch;
    }
    function getResponseData(data) {
      if (Buffer.isBuffer(data)) {
        return data;
      } else if (data instanceof Uint8Array) {
        return data;
      } else if (data instanceof ArrayBuffer) {
        return data;
      } else if (typeof data === "object") {
        return JSON.stringify(data);
      } else if (data) {
        return data.toString();
      } else {
        return "";
      }
    }
    function getMockDispatch(mockDispatches, key) {
      const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
      const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
      const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
      let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path2, ignoreTrailingSlash }) => {
        return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path2)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path2), resolvedPath);
      });
      if (matchedMockDispatches.length === 0) {
        throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
      }
      matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method));
      if (matchedMockDispatches.length === 0) {
        throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}' on path '${resolvedPath}'`);
      }
      matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== "undefined" ? matchValue(body, key.body) : true);
      if (matchedMockDispatches.length === 0) {
        throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}' on path '${resolvedPath}'`);
      }
      matchedMockDispatches = matchedMockDispatches.filter((mockDispatch2) => matchHeaders(mockDispatch2, key.headers));
      if (matchedMockDispatches.length === 0) {
        const headers = typeof key.headers === "object" ? JSON.stringify(key.headers) : key.headers;
        throw new MockNotMatchedError(`Mock dispatch not matched for headers '${headers}' on path '${resolvedPath}'`);
      }
      return matchedMockDispatches[0];
    }
    function addMockDispatch(mockDispatches, key, data, opts) {
      const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false, ...opts };
      const replyData = typeof data === "function" ? { callback: data } : { ...data };
      const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } };
      mockDispatches.push(newMockDispatch);
      mockDispatches[kTotalDispatchCount] = (mockDispatches[kTotalDispatchCount] || 0) + 1;
      return newMockDispatch;
    }
    function deleteMockDispatch(mockDispatches, key) {
      const index2 = mockDispatches.findIndex((dispatch) => {
        if (!dispatch.consumed) {
          return false;
        }
        return matchKey(dispatch, key);
      });
      if (index2 !== -1) {
        mockDispatches.splice(index2, 1);
      }
    }
    function removeTrailingSlash(path2) {
      while (path2.endsWith("/")) {
        path2 = path2.slice(0, -1);
      }
      if (path2.length === 0) {
        path2 = "/";
      }
      return path2;
    }
    function buildKey(opts) {
      const { path: path2, method, body, headers, query } = opts;
      return {
        path: path2,
        method,
        body,
        headers,
        query
      };
    }
    function generateKeyValues(data) {
      const keys = Object.keys(data);
      const result = [];
      for (let i = 0; i < keys.length; ++i) {
        const key = keys[i];
        const value = data[key];
        const name = Buffer.from(`${key}`);
        if (Array.isArray(value)) {
          for (let j = 0; j < value.length; ++j) {
            result.push(name, Buffer.from(`${value[j]}`));
          }
        } else {
          result.push(name, Buffer.from(`${value}`));
        }
      }
      return result;
    }
    function getStatusText(statusCode) {
      return STATUS_CODES[statusCode] || "unknown";
    }
    async function getResponse(body) {
      const buffers = [];
      for await (const data of body) {
        buffers.push(data);
      }
      return Buffer.concat(buffers).toString("utf8");
    }
    function mockDispatch(opts, handler) {
      const key = buildKey(opts);
      const mockDispatch2 = getMockDispatch(this[kDispatches], key);
      mockDispatch2.timesInvoked++;
      if (mockDispatch2.data.callback) {
        mockDispatch2.data = { ...mockDispatch2.data, ...mockDispatch2.data.callback(opts) };
      }
      const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch2;
      const { timesInvoked, times } = mockDispatch2;
      mockDispatch2.consumed = !persist && timesInvoked >= times;
      mockDispatch2.pending = timesInvoked < times;
      if (error !== null) {
        deleteMockDispatch(this[kDispatches], key);
        handler.onResponseError(null, error);
        return true;
      }
      let aborted = false;
      let timer = null;
      const controller = {
        paused: false,
        rawHeaders: null,
        rawTrailers: null,
        pause() {
          this.paused = true;
        },
        resume() {
          this.paused = false;
        },
        abort: (reason) => {
          if (aborted) {
            return;
          }
          aborted = true;
          if (timer !== null) {
            clearTimeout(timer);
            timer = null;
          }
          handler.onResponseError?.(controller, reason);
        }
      };
      handler.onRequestStart?.(controller, null);
      if (typeof delay === "number" && delay > 0) {
        timer = setTimeout(() => {
          timer = null;
          handleReply(this[kDispatches]);
        }, delay);
      } else {
        handleReply(this[kDispatches]);
      }
      function handleReply(mockDispatches, _data = data) {
        if (aborted) {
          return;
        }
        const optsHeaders = Array.isArray(opts.headers) ? buildHeadersFromArray(opts.headers) : opts.headers;
        const body = typeof _data === "function" ? _data({ ...opts, headers: optsHeaders }) : _data;
        if (isPromise(body)) {
          return body.then((newData) => handleReply(mockDispatches, newData));
        }
        if (aborted) {
          return;
        }
        const responseData = getResponseData(body);
        const responseHeaders = generateKeyValues(headers);
        const responseTrailers = generateKeyValues(trailers);
        controller.rawHeaders = responseHeaders;
        controller.rawTrailers = responseTrailers;
        handler.onResponseStart?.(controller, statusCode, parseHeaders(responseHeaders), getStatusText(statusCode));
        handler.onResponseData?.(controller, Buffer.from(responseData));
        handler.onResponseEnd?.(controller, parseHeaders(responseTrailers));
        deleteMockDispatch(mockDispatches, key);
      }
      return true;
    }
    function buildMockDispatch() {
      const agent = this[kMockAgent];
      const origin = this[kOrigin];
      const originalDispatch = this[kOriginalDispatch];
      return function dispatch(opts, handler) {
        if (agent.isMockActive) {
          try {
            mockDispatch.call(this, opts, handler);
          } catch (error) {
            if (error.code === "UND_MOCK_ERR_MOCK_NOT_MATCHED") {
              const netConnect = agent[kGetNetConnect]();
              const totalInterceptsCount = this[kDispatches][kTotalDispatchCount] || this[kDispatches].length;
              const pendingInterceptsCount = this[kDispatches].filter(({ consumed }) => !consumed).length;
              const interceptsMessage = `, ${pendingInterceptsCount} interceptor(s) remaining out of ${totalInterceptsCount} defined`;
              if (netConnect === false) {
                throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)${interceptsMessage}`);
              }
              if (checkNetConnect(netConnect, origin)) {
                originalDispatch.call(this, opts, handler);
              } else {
                throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)${interceptsMessage}`);
              }
            } else {
              throw error;
            }
          }
        } else {
          originalDispatch.call(this, opts, handler);
        }
      };
    }
    function checkNetConnect(netConnect, origin) {
      const url = new URL(origin);
      if (netConnect === true) {
        return true;
      } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) {
        return true;
      }
      return false;
    }
    function normalizeOrigin(origin) {
      if (typeof origin !== "string" && !(origin instanceof URL)) {
        return origin;
      }
      if (origin instanceof URL) {
        return origin.origin;
      }
      return origin.toLowerCase();
    }
    function buildAndValidateMockOptions(opts) {
      const { agent, ...mockOptions } = opts;
      if ("enableCallHistory" in mockOptions && typeof mockOptions.enableCallHistory !== "boolean") {
        throw new InvalidArgumentError("options.enableCallHistory must to be a boolean");
      }
      if ("acceptNonStandardSearchParameters" in mockOptions && typeof mockOptions.acceptNonStandardSearchParameters !== "boolean") {
        throw new InvalidArgumentError("options.acceptNonStandardSearchParameters must to be a boolean");
      }
      if ("ignoreTrailingSlash" in mockOptions && typeof mockOptions.ignoreTrailingSlash !== "boolean") {
        throw new InvalidArgumentError("options.ignoreTrailingSlash must to be a boolean");
      }
      return mockOptions;
    }
    module.exports = {
      getResponseData,
      getMockDispatch,
      addMockDispatch,
      deleteMockDispatch,
      buildKey,
      generateKeyValues,
      matchValue,
      getResponse,
      getStatusText,
      mockDispatch,
      buildMockDispatch,
      checkNetConnect,
      buildAndValidateMockOptions,
      getHeaderByName,
      buildHeadersFromArray,
      normalizeSearchParams,
      normalizeOrigin
    };
  }
});

// node_modules/undici/lib/mock/mock-interceptor.js
var require_mock_interceptor = __commonJS({
  "node_modules/undici/lib/mock/mock-interceptor.js"(exports, module) {
    "use strict";
    var { getResponseData, buildKey, addMockDispatch } = require_mock_utils();
    var {
      kDispatches,
      kDispatchKey,
      kDefaultHeaders,
      kDefaultTrailers,
      kContentLength,
      kMockDispatch,
      kIgnoreTrailingSlash
    } = require_mock_symbols();
    var { InvalidArgumentError } = require_errors();
    var { serializePathWithQuery } = require_util();
    var MockScope = class {
      constructor(mockDispatch) {
        this[kMockDispatch] = mockDispatch;
      }
      /**
       * Delay a reply by a set amount in ms.
       */
      delay(waitInMs) {
        if (typeof waitInMs !== "number" || !Number.isInteger(waitInMs) || waitInMs <= 0) {
          throw new InvalidArgumentError("waitInMs must be a valid integer > 0");
        }
        this[kMockDispatch].delay = waitInMs;
        return this;
      }
      /**
       * For a defined reply, never mark as consumed.
       */
      persist() {
        this[kMockDispatch].persist = true;
        return this;
      }
      /**
       * Allow one to define a reply for a set amount of matching requests.
       */
      times(repeatTimes) {
        if (typeof repeatTimes !== "number" || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {
          throw new InvalidArgumentError("repeatTimes must be a valid integer > 0");
        }
        this[kMockDispatch].times = repeatTimes;
        return this;
      }
    };
    var MockInterceptor = class {
      constructor(opts, mockDispatches) {
        if (typeof opts !== "object") {
          throw new InvalidArgumentError("opts must be an object");
        }
        if (typeof opts.path === "undefined") {
          throw new InvalidArgumentError("opts.path must be defined");
        }
        if (typeof opts.method === "undefined") {
          opts.method = "GET";
        }
        if (typeof opts.path === "string") {
          if (opts.query) {
            opts.path = serializePathWithQuery(opts.path, opts.query);
          } else {
            const parsedURL = new URL(opts.path, "data://");
            opts.path = parsedURL.pathname + parsedURL.search;
          }
        }
        if (typeof opts.method === "string") {
          opts.method = opts.method.toUpperCase();
        }
        this[kDispatchKey] = buildKey(opts);
        this[kDispatches] = mockDispatches;
        this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false;
        this[kDefaultHeaders] = {};
        this[kDefaultTrailers] = {};
        this[kContentLength] = false;
      }
      createMockScopeDispatchData({ statusCode, data, responseOptions }) {
        const responseData = getResponseData(data);
        const contentLength = this[kContentLength] ? { "content-length": responseData.length } : {};
        const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers };
        const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers };
        return { statusCode, data, headers, trailers };
      }
      validateReplyParameters(replyParameters) {
        if (typeof replyParameters.statusCode === "undefined") {
          throw new InvalidArgumentError("statusCode must be defined");
        }
        if (typeof replyParameters.responseOptions !== "object" || replyParameters.responseOptions === null) {
          throw new InvalidArgumentError("responseOptions must be an object");
        }
      }
      /**
       * Mock an undici request with a defined reply.
       */
      reply(replyOptionsCallbackOrStatusCode) {
        if (typeof replyOptionsCallbackOrStatusCode === "function") {
          const wrappedDefaultsCallback = (opts) => {
            const resolvedData = replyOptionsCallbackOrStatusCode(opts);
            if (typeof resolvedData !== "object" || resolvedData === null) {
              throw new InvalidArgumentError("reply options callback must return an object");
            }
            const replyParameters2 = { data: "", responseOptions: {}, ...resolvedData };
            this.validateReplyParameters(replyParameters2);
            return {
              ...this.createMockScopeDispatchData(replyParameters2)
            };
          };
          const newMockDispatch2 = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] });
          return new MockScope(newMockDispatch2);
        }
        const replyParameters = {
          statusCode: replyOptionsCallbackOrStatusCode,
          data: arguments[1] === void 0 ? "" : arguments[1],
          responseOptions: arguments[2] === void 0 ? {} : arguments[2]
        };
        this.validateReplyParameters(replyParameters);
        const dispatchData = this.createMockScopeDispatchData(replyParameters);
        const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] });
        return new MockScope(newMockDispatch);
      }
      /**
       * Mock an undici request with a defined error.
       */
      replyWithError(error) {
        if (typeof error === "undefined") {
          throw new InvalidArgumentError("error must be defined");
        }
        const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] });
        return new MockScope(newMockDispatch);
      }
      /**
       * Set default reply headers on the interceptor for subsequent replies
       */
      defaultReplyHeaders(headers) {
        if (typeof headers === "undefined") {
          throw new InvalidArgumentError("headers must be defined");
        }
        this[kDefaultHeaders] = headers;
        return this;
      }
      /**
       * Set default reply trailers on the interceptor for subsequent replies
       */
      defaultReplyTrailers(trailers) {
        if (typeof trailers === "undefined") {
          throw new InvalidArgumentError("trailers must be defined");
        }
        this[kDefaultTrailers] = trailers;
        return this;
      }
      /**
       * Set reply content length header for replies on the interceptor
       */
      replyContentLength() {
        this[kContentLength] = true;
        return this;
      }
    };
    module.exports.MockInterceptor = MockInterceptor;
    module.exports.MockScope = MockScope;
  }
});

// node_modules/undici/lib/mock/mock-client.js
var require_mock_client = __commonJS({
  "node_modules/undici/lib/mock/mock-client.js"(exports, module) {
    "use strict";
    var { promisify } = __require("util");
    var Client = require_client();
    var { buildMockDispatch } = require_mock_utils();
    var {
      kDispatches,
      kMockAgent,
      kClose,
      kOriginalClose,
      kOrigin,
      kOriginalDispatch,
      kConnected,
      kIgnoreTrailingSlash
    } = require_mock_symbols();
    var { MockInterceptor } = require_mock_interceptor();
    var Symbols = require_symbols();
    var { InvalidArgumentError } = require_errors();
    var MockClient = class extends Client {
      constructor(origin, opts) {
        if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") {
          throw new InvalidArgumentError("Argument opts.agent must implement Agent");
        }
        super(origin, opts);
        this[kMockAgent] = opts.agent;
        this[kOrigin] = origin;
        this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false;
        this[kDispatches] = [];
        this[kConnected] = 1;
        this[kOriginalDispatch] = this.dispatch;
        this[kOriginalClose] = this.close.bind(this);
        this.dispatch = buildMockDispatch.call(this);
        this.close = this[kClose];
      }
      get [Symbols.kConnected]() {
        return this[kConnected];
      }
      /**
       * Sets up the base interceptor for mocking replies from undici.
       */
      intercept(opts) {
        return new MockInterceptor(
          opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts },
          this[kDispatches]
        );
      }
      cleanMocks() {
        this[kDispatches] = [];
      }
      async [kClose]() {
        await promisify(this[kOriginalClose])();
        this[kConnected] = 0;
        this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
      }
    };
    module.exports = MockClient;
  }
});

// node_modules/undici/lib/mock/mock-call-history.js
var require_mock_call_history = __commonJS({
  "node_modules/undici/lib/mock/mock-call-history.js"(exports, module) {
    "use strict";
    var { kMockCallHistoryAddLog } = require_mock_symbols();
    var { InvalidArgumentError } = require_errors();
    function handleFilterCallsWithOptions(criteria, options, handler, store, allLogs) {
      switch (options.operator) {
        case "OR":
          store.push(...handler(criteria, allLogs));
          return store;
        case "AND":
          return handler(criteria, store);
        default:
          throw new InvalidArgumentError("options.operator must to be a case insensitive string equal to 'OR' or 'AND'");
      }
    }
    function buildAndValidateFilterCallsOptions(options = {}) {
      const finalOptions = {};
      if ("operator" in options) {
        if (typeof options.operator !== "string" || options.operator.toUpperCase() !== "OR" && options.operator.toUpperCase() !== "AND") {
          throw new InvalidArgumentError("options.operator must to be a case insensitive string equal to 'OR' or 'AND'");
        }
        return {
          ...finalOptions,
          operator: options.operator.toUpperCase()
        };
      }
      return finalOptions;
    }
    function makeFilterCalls(parameterName) {
      return (parameterValue, logs) => {
        if (typeof parameterValue === "string" || parameterValue == null) {
          return logs.filter((log) => {
            return log[parameterName] === parameterValue;
          });
        }
        if (parameterValue instanceof RegExp) {
          return logs.filter((log) => {
            return parameterValue.test(log[parameterName]);
          });
        }
        throw new InvalidArgumentError(`${parameterName} parameter should be one of string, regexp, undefined or null`);
      };
    }
    function computeUrlWithMaybeSearchParameters(requestInit) {
      try {
        const url = new URL(requestInit.path, requestInit.origin);
        if (url.search.length !== 0) {
          return url;
        }
        url.search = new URLSearchParams(requestInit.query).toString();
        return url;
      } catch (error) {
        throw new InvalidArgumentError("An error occurred when computing MockCallHistoryLog.url", { cause: error });
      }
    }
    var MockCallHistoryLog = class {
      constructor(requestInit = {}) {
        this.body = requestInit.body;
        this.headers = requestInit.headers;
        this.method = requestInit.method;
        const url = computeUrlWithMaybeSearchParameters(requestInit);
        this.fullUrl = url.toString();
        this.origin = url.origin;
        this.path = url.pathname;
        this.searchParams = Object.fromEntries(url.searchParams);
        this.protocol = url.protocol;
        this.host = url.host;
        this.port = url.port;
        this.hash = url.hash;
      }
      toMap() {
        return /* @__PURE__ */ new Map(
          [
            ["protocol", this.protocol],
            ["host", this.host],
            ["port", this.port],
            ["origin", this.origin],
            ["path", this.path],
            ["hash", this.hash],
            ["searchParams", this.searchParams],
            ["fullUrl", this.fullUrl],
            ["method", this.method],
            ["body", this.body],
            ["headers", this.headers]
          ]
        );
      }
      toString() {
        const options = { betweenKeyValueSeparator: "->", betweenPairSeparator: "|" };
        let result = "";
        this.toMap().forEach((value, key) => {
          if (typeof value === "string" || value === void 0 || value === null) {
            result = `${result}${key}${options.betweenKeyValueSeparator}${value}${options.betweenPairSeparator}`;
          }
          if (typeof value === "object" && value !== null || Array.isArray(value)) {
            result = `${result}${key}${options.betweenKeyValueSeparator}${JSON.stringify(value)}${options.betweenPairSeparator}`;
          }
        });
        return result.slice(0, -1);
      }
    };
    var MockCallHistory = class {
      logs = [];
      calls() {
        return this.logs;
      }
      firstCall() {
        return this.logs.at(0);
      }
      lastCall() {
        return this.logs.at(-1);
      }
      nthCall(number) {
        if (typeof number !== "number") {
          throw new InvalidArgumentError("nthCall must be called with a number");
        }
        if (!Number.isInteger(number)) {
          throw new InvalidArgumentError("nthCall must be called with an integer");
        }
        if (Math.sign(number) !== 1) {
          throw new InvalidArgumentError("nthCall must be called with a positive value. use firstCall or lastCall instead");
        }
        return this.logs.at(number - 1);
      }
      filterCalls(criteria, options) {
        if (this.logs.length === 0) {
          return this.logs;
        }
        if (typeof criteria === "function") {
          return this.logs.filter(criteria);
        }
        if (criteria instanceof RegExp) {
          return this.logs.filter((log) => {
            return criteria.test(log.toString());
          });
        }
        if (typeof criteria === "object" && criteria !== null) {
          if (Object.keys(criteria).length === 0) {
            return this.logs;
          }
          const finalOptions = { operator: "OR", ...buildAndValidateFilterCallsOptions(options) };
          let maybeDuplicatedLogsFiltered = finalOptions.operator === "AND" ? this.logs : [];
          if ("protocol" in criteria) {
            maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.protocol, finalOptions, this.filterCallsByProtocol, maybeDuplicatedLogsFiltered, this.logs);
          }
          if ("host" in criteria) {
            maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.host, finalOptions, this.filterCallsByHost, maybeDuplicatedLogsFiltered, this.logs);
          }
          if ("port" in criteria) {
            maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.port, finalOptions, this.filterCallsByPort, maybeDuplicatedLogsFiltered, this.logs);
          }
          if ("origin" in criteria) {
            maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.origin, finalOptions, this.filterCallsByOrigin, maybeDuplicatedLogsFiltered, this.logs);
          }
          if ("path" in criteria) {
            maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.path, finalOptions, this.filterCallsByPath, maybeDuplicatedLogsFiltered, this.logs);
          }
          if ("hash" in criteria) {
            maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.hash, finalOptions, this.filterCallsByHash, maybeDuplicatedLogsFiltered, this.logs);
          }
          if ("fullUrl" in criteria) {
            maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.fullUrl, finalOptions, this.filterCallsByFullUrl, maybeDuplicatedLogsFiltered, this.logs);
          }
          if ("method" in criteria) {
            maybeDuplicatedLogsFiltered = handleFilterCallsWithOptions(criteria.method, finalOptions, this.filterCallsByMethod, maybeDuplicatedLogsFiltered, this.logs);
          }
          const uniqLogsFiltered = [...new Set(maybeDuplicatedLogsFiltered)];
          return uniqLogsFiltered;
        }
        throw new InvalidArgumentError("criteria parameter should be one of function, regexp, or object");
      }
      filterCallsByProtocol = makeFilterCalls.call(this, "protocol");
      filterCallsByHost = makeFilterCalls.call(this, "host");
      filterCallsByPort = makeFilterCalls.call(this, "port");
      filterCallsByOrigin = makeFilterCalls.call(this, "origin");
      filterCallsByPath = makeFilterCalls.call(this, "path");
      filterCallsByHash = makeFilterCalls.call(this, "hash");
      filterCallsByFullUrl = makeFilterCalls.call(this, "fullUrl");
      filterCallsByMethod = makeFilterCalls.call(this, "method");
      clear() {
        this.logs = [];
      }
      [kMockCallHistoryAddLog](requestInit) {
        const log = new MockCallHistoryLog(requestInit);
        this.logs.push(log);
        return log;
      }
      *[Symbol.iterator]() {
        for (const log of this.calls()) {
          yield log;
        }
      }
    };
    module.exports.MockCallHistory = MockCallHistory;
    module.exports.MockCallHistoryLog = MockCallHistoryLog;
  }
});

// node_modules/undici/lib/mock/mock-pool.js
var require_mock_pool = __commonJS({
  "node_modules/undici/lib/mock/mock-pool.js"(exports, module) {
    "use strict";
    var { promisify } = __require("util");
    var Pool = require_pool();
    var { buildMockDispatch } = require_mock_utils();
    var {
      kDispatches,
      kMockAgent,
      kClose,
      kOriginalClose,
      kOrigin,
      kOriginalDispatch,
      kConnected,
      kIgnoreTrailingSlash
    } = require_mock_symbols();
    var { MockInterceptor } = require_mock_interceptor();
    var Symbols = require_symbols();
    var { InvalidArgumentError } = require_errors();
    var MockPool = class extends Pool {
      constructor(origin, opts) {
        if (!opts || !opts.agent || typeof opts.agent.dispatch !== "function") {
          throw new InvalidArgumentError("Argument opts.agent must implement Agent");
        }
        super(origin, opts);
        this[kMockAgent] = opts.agent;
        this[kOrigin] = origin;
        this[kIgnoreTrailingSlash] = opts.ignoreTrailingSlash ?? false;
        this[kDispatches] = [];
        this[kConnected] = 1;
        this[kOriginalDispatch] = this.dispatch;
        this[kOriginalClose] = this.close.bind(this);
        this.dispatch = buildMockDispatch.call(this);
        this.close = this[kClose];
      }
      get [Symbols.kConnected]() {
        return this[kConnected];
      }
      /**
       * Sets up the base interceptor for mocking replies from undici.
       */
      intercept(opts) {
        return new MockInterceptor(
          opts && { ignoreTrailingSlash: this[kIgnoreTrailingSlash], ...opts },
          this[kDispatches]
        );
      }
      cleanMocks() {
        this[kDispatches] = [];
      }
      async [kClose]() {
        await promisify(this[kOriginalClose])();
        this[kConnected] = 0;
        this[kMockAgent][Symbols.kClients].delete(this[kOrigin]);
      }
    };
    module.exports = MockPool;
  }
});

// node_modules/undici/lib/mock/pending-interceptors-formatter.js
var require_pending_interceptors_formatter = __commonJS({
  "node_modules/undici/lib/mock/pending-interceptors-formatter.js"(exports, module) {
    "use strict";
    var { Transform } = __require("stream");
    var { Console } = __require("console");
    var PERSISTENT = process.versions.icu ? "\u2705" : "Y ";
    var NOT_PERSISTENT = process.versions.icu ? "\u274C" : "N ";
    module.exports = class PendingInterceptorsFormatter {
      constructor({ disableColors } = {}) {
        this.transform = new Transform({
          transform(chunk, _enc, cb) {
            cb(null, chunk);
          }
        });
        this.logger = new Console({
          stdout: this.transform,
          inspectOptions: {
            colors: !disableColors && !process.env.CI
          }
        });
      }
      format(pendingInterceptors) {
        const withPrettyHeaders = pendingInterceptors.map(
          ({ method, path: path2, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
            Method: method,
            Origin: origin,
            Path: path2,
            "Status code": statusCode,
            Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
            Invocations: timesInvoked,
            Remaining: persist ? Infinity : times - timesInvoked
          })
        );
        this.logger.table(withPrettyHeaders);
        return this.transform.read().toString();
      }
    };
  }
});

// node_modules/undici/lib/mock/mock-agent.js
var require_mock_agent = __commonJS({
  "node_modules/undici/lib/mock/mock-agent.js"(exports, module) {
    "use strict";
    var { kClients } = require_symbols();
    var Agent = require_agent();
    var {
      kAgent,
      kMockAgentSet,
      kMockAgentGet,
      kDispatches,
      kIsMockActive,
      kNetConnect,
      kGetNetConnect,
      kOptions,
      kFactory,
      kMockAgentRegisterCallHistory,
      kMockAgentIsCallHistoryEnabled,
      kMockAgentAddCallHistoryLog,
      kMockAgentMockCallHistoryInstance,
      kMockAgentAcceptsNonStandardSearchParameters,
      kMockCallHistoryAddLog,
      kIgnoreTrailingSlash
    } = require_mock_symbols();
    var MockClient = require_mock_client();
    var MockPool = require_mock_pool();
    var { matchValue, normalizeSearchParams, buildAndValidateMockOptions, normalizeOrigin } = require_mock_utils();
    var { InvalidArgumentError, UndiciError } = require_errors();
    var Dispatcher = require_dispatcher();
    var PendingInterceptorsFormatter = require_pending_interceptors_formatter();
    var { MockCallHistory } = require_mock_call_history();
    var MockAgent = class extends Dispatcher {
      constructor(opts = {}) {
        super(opts);
        const mockOptions = buildAndValidateMockOptions(opts);
        this[kNetConnect] = true;
        this[kIsMockActive] = true;
        this[kMockAgentIsCallHistoryEnabled] = mockOptions.enableCallHistory ?? false;
        this[kMockAgentAcceptsNonStandardSearchParameters] = mockOptions.acceptNonStandardSearchParameters ?? false;
        this[kIgnoreTrailingSlash] = mockOptions.ignoreTrailingSlash ?? false;
        if (opts?.agent && typeof opts.agent.dispatch !== "function") {
          throw new InvalidArgumentError("Argument opts.agent must implement Agent");
        }
        const agent = opts?.agent ? opts.agent : new Agent(opts);
        this[kAgent] = agent;
        this[kClients] = agent[kClients];
        this[kOptions] = mockOptions;
        if (this[kMockAgentIsCallHistoryEnabled]) {
          this[kMockAgentRegisterCallHistory]();
        }
      }
      get(origin) {
        const normalizedOrigin = normalizeOrigin(origin);
        const originKey = this[kIgnoreTrailingSlash] ? normalizedOrigin.replace(/\/$/, "") : normalizedOrigin;
        let dispatcher = this[kMockAgentGet](originKey);
        if (!dispatcher) {
          dispatcher = this[kFactory](originKey);
          this[kMockAgentSet](originKey, dispatcher);
        }
        return dispatcher;
      }
      dispatch(opts, handler) {
        opts.origin = normalizeOrigin(opts.origin);
        this.get(opts.origin);
        this[kMockAgentAddCallHistoryLog](opts);
        const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
        const dispatchOpts = { ...opts };
        if (acceptNonStandardSearchParameters && dispatchOpts.path) {
          const [path2, searchParams] = dispatchOpts.path.split("?");
          const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
          dispatchOpts.path = `${path2}?${normalizedSearchParams}`;
        }
        return this[kAgent].dispatch(dispatchOpts, handler);
      }
      async close() {
        this.clearCallHistory();
        await this[kAgent].close();
        this[kClients].clear();
      }
      deactivate() {
        this[kIsMockActive] = false;
      }
      activate() {
        this[kIsMockActive] = true;
      }
      enableNetConnect(matcher) {
        if (typeof matcher === "string" || typeof matcher === "function" || matcher instanceof RegExp) {
          if (Array.isArray(this[kNetConnect])) {
            this[kNetConnect].push(matcher);
          } else {
            this[kNetConnect] = [matcher];
          }
        } else if (typeof matcher === "undefined") {
          this[kNetConnect] = true;
        } else {
          throw new InvalidArgumentError("Unsupported matcher. Must be one of String|Function|RegExp.");
        }
      }
      disableNetConnect() {
        this[kNetConnect] = false;
      }
      enableCallHistory() {
        this[kMockAgentIsCallHistoryEnabled] = true;
        return this;
      }
      disableCallHistory() {
        this[kMockAgentIsCallHistoryEnabled] = false;
        return this;
      }
      getCallHistory() {
        return this[kMockAgentMockCallHistoryInstance];
      }
      clearCallHistory() {
        if (this[kMockAgentMockCallHistoryInstance] !== void 0) {
          this[kMockAgentMockCallHistoryInstance].clear();
        }
      }
      // This is required to bypass issues caused by using global symbols - see:
      // https://github.com/nodejs/undici/issues/1447
      get isMockActive() {
        return this[kIsMockActive];
      }
      [kMockAgentRegisterCallHistory]() {
        if (this[kMockAgentMockCallHistoryInstance] === void 0) {
          this[kMockAgentMockCallHistoryInstance] = new MockCallHistory();
        }
      }
      [kMockAgentAddCallHistoryLog](opts) {
        if (this[kMockAgentIsCallHistoryEnabled]) {
          this[kMockAgentRegisterCallHistory]();
          this[kMockAgentMockCallHistoryInstance][kMockCallHistoryAddLog](opts);
        }
      }
      [kMockAgentSet](origin, dispatcher) {
        this[kClients].set(origin, dispatcher);
      }
      [kFactory](origin) {
        const mockOptions = Object.assign({ agent: this }, this[kOptions]);
        return this[kOptions] && this[kOptions].connections === 1 ? new MockClient(origin, mockOptions) : new MockPool(origin, mockOptions);
      }
      [kMockAgentGet](origin) {
        const dispatcher = this[kClients].get(origin);
        if (dispatcher) {
          return dispatcher;
        }
        if (typeof origin !== "string") {
          const dispatcher2 = this[kFactory]("http://localhost:9999");
          this[kMockAgentSet](origin, dispatcher2);
          return dispatcher2;
        }
        for (const [keyMatcher, nonExplicitDispatcher] of Array.from(this[kClients])) {
          if (nonExplicitDispatcher && typeof keyMatcher !== "string" && matchValue(keyMatcher, origin)) {
            const dispatcher2 = this[kFactory](origin);
            this[kMockAgentSet](origin, dispatcher2);
            dispatcher2[kDispatches] = nonExplicitDispatcher[kDispatches];
            return dispatcher2;
          }
        }
      }
      [kGetNetConnect]() {
        return this[kNetConnect];
      }
      pendingInterceptors() {
        const mockAgentClients = this[kClients];
        return Array.from(mockAgentClients.entries()).flatMap(([origin, dispatcher]) => dispatcher[kDispatches].map((dispatch) => ({ ...dispatch, origin }))).filter(({ pending }) => pending);
      }
      assertNoPendingInterceptors({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
        const pending = this.pendingInterceptors();
        if (pending.length === 0) {
          return;
        }
        throw new UndiciError(
          pending.length === 1 ? `1 interceptor is pending:

${pendingInterceptorsFormatter.format(pending)}`.trim() : `${pending.length} interceptors are pending:

${pendingInterceptorsFormatter.format(pending)}`.trim()
        );
      }
    };
    module.exports = MockAgent;
  }
});

// node_modules/undici/lib/mock/snapshot-utils.js
var require_snapshot_utils = __commonJS({
  "node_modules/undici/lib/mock/snapshot-utils.js"(exports, module) {
    "use strict";
    var { InvalidArgumentError } = require_errors();
    var { runtimeFeatures } = require_runtime_features();
    function createHeaderFilters(matchOptions = {}) {
      const { ignoreHeaders = [], excludeHeaders = [], matchHeaders = [], caseSensitive = false } = matchOptions;
      return {
        ignore: new Set(ignoreHeaders.map((header) => caseSensitive ? header : header.toLowerCase())),
        exclude: new Set(excludeHeaders.map((header) => caseSensitive ? header : header.toLowerCase())),
        match: new Set(matchHeaders.map((header) => caseSensitive ? header : header.toLowerCase()))
      };
    }
    var crypto6 = runtimeFeatures.has("crypto") ? __require("crypto") : null;
    var hashId = crypto6?.hash ? (value) => crypto6.hash("sha256", value, "base64url") : (value) => Buffer.from(value).toString("base64url");
    function isUndiciHeaders(headers) {
      return Array.isArray(headers) && (headers.length & 1) === 0;
    }
    function isUrlExcludedFactory(excludePatterns = []) {
      if (excludePatterns.length === 0) {
        return () => false;
      }
      return function isUrlExcluded(url) {
        let urlLowerCased;
        for (const pattern of excludePatterns) {
          if (typeof pattern === "string") {
            if (!urlLowerCased) {
              urlLowerCased = url.toLowerCase();
            }
            if (urlLowerCased.includes(pattern.toLowerCase())) {
              return true;
            }
          } else if (pattern instanceof RegExp) {
            if (pattern.test(url)) {
              return true;
            }
          }
        }
        return false;
      };
    }
    function normalizeHeaders3(headers) {
      const normalizedHeaders = {};
      if (!headers) return normalizedHeaders;
      if (isUndiciHeaders(headers)) {
        for (let i = 0; i < headers.length; i += 2) {
          const key = headers[i];
          const value = headers[i + 1];
          if (key && value !== void 0) {
            const keyStr = Buffer.isBuffer(key) ? key.toString() : key;
            const valueStr = Buffer.isBuffer(value) ? value.toString() : value;
            normalizedHeaders[keyStr.toLowerCase()] = valueStr;
          }
        }
        return normalizedHeaders;
      }
      if (headers && typeof headers === "object") {
        for (const [key, value] of Object.entries(headers)) {
          if (key && typeof key === "string") {
            normalizedHeaders[key.toLowerCase()] = Array.isArray(value) ? value.join(", ") : String(value);
          }
        }
      }
      return normalizedHeaders;
    }
    var validSnapshotModes = (
      /** @type {const} */
      ["record", "playback", "update"]
    );
    function validateSnapshotMode(mode) {
      if (!validSnapshotModes.includes(mode)) {
        throw new InvalidArgumentError(`Invalid snapshot mode: ${mode}. Must be one of: ${validSnapshotModes.join(", ")}`);
      }
    }
    module.exports = {
      createHeaderFilters,
      hashId,
      isUndiciHeaders,
      normalizeHeaders: normalizeHeaders3,
      isUrlExcludedFactory,
      validateSnapshotMode
    };
  }
});

// node_modules/undici/lib/mock/snapshot-recorder.js
var require_snapshot_recorder = __commonJS({
  "node_modules/undici/lib/mock/snapshot-recorder.js"(exports, module) {
    "use strict";
    var { writeFile: writeFile3, readFile: readFile3, mkdir: mkdir5 } = __require("fs/promises");
    var { dirname: dirname4, resolve } = __require("path");
    var { setTimeout: setTimeout2, clearTimeout: clearTimeout2 } = __require("timers");
    var { InvalidArgumentError, UndiciError } = require_errors();
    var { hashId, isUrlExcludedFactory, normalizeHeaders: normalizeHeaders3, createHeaderFilters } = require_snapshot_utils();
    function formatRequestKey(opts, headerFilters, matchOptions = {}) {
      const url = new URL(opts.path, opts.origin);
      const normalized = opts._normalizedHeaders || normalizeHeaders3(opts.headers);
      if (!opts._normalizedHeaders) {
        opts._normalizedHeaders = normalized;
      }
      return {
        method: opts.method || "GET",
        url: matchOptions.matchQuery !== false ? url.toString() : `${url.origin}${url.pathname}`,
        headers: filterHeadersForMatching(normalized, headerFilters, matchOptions),
        body: matchOptions.matchBody !== false && opts.body ? String(opts.body) : ""
      };
    }
    function filterHeadersForMatching(headers, headerFilters, matchOptions = {}) {
      if (!headers || typeof headers !== "object") return {};
      const {
        caseSensitive = false
      } = matchOptions;
      const filtered = {};
      const { ignore, exclude, match } = headerFilters;
      for (const [key, value] of Object.entries(headers)) {
        const headerKey = caseSensitive ? key : key.toLowerCase();
        if (exclude.has(headerKey)) continue;
        if (ignore.has(headerKey)) continue;
        if (match.size !== 0) {
          if (!match.has(headerKey)) continue;
        }
        filtered[headerKey] = value;
      }
      return filtered;
    }
    function filterHeadersForStorage(headers, headerFilters, matchOptions = {}) {
      if (!headers || typeof headers !== "object") return {};
      const {
        caseSensitive = false
      } = matchOptions;
      const filtered = {};
      const { exclude: excludeSet } = headerFilters;
      for (const [key, value] of Object.entries(headers)) {
        const headerKey = caseSensitive ? key : key.toLowerCase();
        if (excludeSet.has(headerKey)) continue;
        filtered[headerKey] = value;
      }
      return filtered;
    }
    function createRequestHash(formattedRequest) {
      const parts = [
        formattedRequest.method,
        formattedRequest.url
      ];
      if (formattedRequest.headers && typeof formattedRequest.headers === "object") {
        const headerKeys = Object.keys(formattedRequest.headers).sort();
        for (const key of headerKeys) {
          const values = Array.isArray(formattedRequest.headers[key]) ? formattedRequest.headers[key] : [formattedRequest.headers[key]];
          parts.push(key);
          for (const value of values.sort()) {
            parts.push(String(value));
          }
        }
      }
      parts.push(formattedRequest.body);
      const content = parts.join("|");
      return hashId(content);
    }
    var SnapshotRecorder = class {
      /** @type {NodeJS.Timeout | null} */
      #flushTimeout;
      /** @type {import('./snapshot-utils').IsUrlExcluded} */
      #isUrlExcluded;
      /** @type {Map<string, SnapshotEntry>} */
      #snapshots = /* @__PURE__ */ new Map();
      /** @type {string|undefined} */
      #snapshotPath;
      /** @type {number} */
      #maxSnapshots = Infinity;
      /** @type {boolean} */
      #autoFlush = false;
      /** @type {import('./snapshot-utils').HeaderFilters} */
      #headerFilters;
      /**
       * Creates a new SnapshotRecorder instance
       * @param {SnapshotRecorderOptions&SnapshotRecorderMatchOptions} [options={}] - Configuration options for the recorder
       */
      constructor(options = {}) {
        this.#snapshotPath = options.snapshotPath;
        this.#maxSnapshots = options.maxSnapshots || Infinity;
        this.#autoFlush = options.autoFlush || false;
        this.flushInterval = options.flushInterval || 3e4;
        this._flushTimer = null;
        this.matchOptions = {
          matchHeaders: options.matchHeaders || [],
          // empty means match all headers
          ignoreHeaders: options.ignoreHeaders || [],
          excludeHeaders: options.excludeHeaders || [],
          matchBody: options.matchBody !== false,
          // default: true
          matchQuery: options.matchQuery !== false,
          // default: true
          caseSensitive: options.caseSensitive || false
        };
        this.#headerFilters = createHeaderFilters(this.matchOptions);
        this.shouldRecord = options.shouldRecord || (() => true);
        this.shouldPlayback = options.shouldPlayback || (() => true);
        this.#isUrlExcluded = isUrlExcludedFactory(options.excludeUrls);
        if (this.#autoFlush && this.#snapshotPath) {
          this.#startAutoFlush();
        }
      }
      /**
       * Records a request-response interaction
       * @param {SnapshotRequestOptions} requestOpts - Request options
       * @param {SnapshotEntryResponse} response - Response data to record
       * @return {Promise<void>} - Resolves when the recording is complete
       */
      async record(requestOpts, response) {
        if (!this.shouldRecord(requestOpts)) {
          return;
        }
        if (this.isUrlExcluded(requestOpts)) {
          return;
        }
        const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions);
        const hash3 = createRequestHash(request);
        const normalizedHeaders = normalizeHeaders3(response.headers);
        const responseData = {
          statusCode: response.statusCode,
          headers: filterHeadersForStorage(normalizedHeaders, this.#headerFilters, this.matchOptions),
          body: Buffer.isBuffer(response.body) ? response.body.toString("base64") : Buffer.from(String(response.body || "")).toString("base64"),
          trailers: response.trailers
        };
        if (this.#snapshots.size >= this.#maxSnapshots && !this.#snapshots.has(hash3)) {
          const oldestKey = this.#snapshots.keys().next().value;
          this.#snapshots.delete(oldestKey);
        }
        const existingSnapshot = this.#snapshots.get(hash3);
        if (existingSnapshot && existingSnapshot.responses) {
          existingSnapshot.responses.push(responseData);
          existingSnapshot.timestamp = (/* @__PURE__ */ new Date()).toISOString();
        } else {
          this.#snapshots.set(hash3, {
            request,
            responses: [responseData],
            // Always store as array for consistency
            callCount: 0,
            timestamp: (/* @__PURE__ */ new Date()).toISOString()
          });
        }
        if (this.#autoFlush && this.#snapshotPath) {
          this.#scheduleFlush();
        }
      }
      /**
       * Checks if a URL should be excluded from recording/playback
       * @param {SnapshotRequestOptions} requestOpts - Request options to check
       * @returns {boolean} - True if URL is excluded
       */
      isUrlExcluded(requestOpts) {
        const url = new URL(requestOpts.path, requestOpts.origin).toString();
        return this.#isUrlExcluded(url);
      }
      /**
       * Finds a matching snapshot for the given request
       * Returns the appropriate response based on call count for sequential responses
       *
       * @param {SnapshotRequestOptions} requestOpts - Request options to match
       * @returns {SnapshotEntry&Record<'response', SnapshotEntryResponse>|undefined} - Matching snapshot response or undefined if not found
       */
      findSnapshot(requestOpts) {
        if (!this.shouldPlayback(requestOpts)) {
          return void 0;
        }
        if (this.isUrlExcluded(requestOpts)) {
          return void 0;
        }
        const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions);
        const hash3 = createRequestHash(request);
        const snapshot = this.#snapshots.get(hash3);
        if (!snapshot) return void 0;
        const currentCallCount = snapshot.callCount || 0;
        const responseIndex = Math.min(currentCallCount, snapshot.responses.length - 1);
        snapshot.callCount = currentCallCount + 1;
        return {
          ...snapshot,
          response: snapshot.responses[responseIndex]
        };
      }
      /**
       * Loads snapshots from file
       * @param {string} [filePath] - Optional file path to load snapshots from
       * @return {Promise<void>} - Resolves when snapshots are loaded
       */
      async loadSnapshots(filePath) {
        const path2 = filePath || this.#snapshotPath;
        if (!path2) {
          throw new InvalidArgumentError("Snapshot path is required");
        }
        try {
          const data = await readFile3(resolve(path2), "utf8");
          const parsed = JSON.parse(data);
          if (Array.isArray(parsed)) {
            this.#snapshots.clear();
            for (const { hash: hash3, snapshot } of parsed) {
              this.#snapshots.set(hash3, snapshot);
            }
          } else {
            this.#snapshots = new Map(Object.entries(parsed));
          }
        } catch (error) {
          if (error.code === "ENOENT") {
            this.#snapshots.clear();
          } else {
            throw new UndiciError(`Failed to load snapshots from ${path2}`, { cause: error });
          }
        }
      }
      /**
       * Saves snapshots to file
       *
       * @param {string} [filePath] - Optional file path to save snapshots
       * @returns {Promise<void>} - Resolves when snapshots are saved
       */
      async saveSnapshots(filePath) {
        const path2 = filePath || this.#snapshotPath;
        if (!path2) {
          throw new InvalidArgumentError("Snapshot path is required");
        }
        const resolvedPath = resolve(path2);
        await mkdir5(dirname4(resolvedPath), { recursive: true });
        const data = Array.from(this.#snapshots.entries()).map(([hash3, snapshot]) => ({
          hash: hash3,
          snapshot
        }));
        await writeFile3(resolvedPath, JSON.stringify(data, null, 2), { flush: true });
      }
      /**
       * Clears all recorded snapshots
       * @returns {void}
       */
      clear() {
        this.#snapshots.clear();
      }
      /**
       * Gets all recorded snapshots
       * @return {Array<SnapshotEntry>} - Array of all recorded snapshots
       */
      getSnapshots() {
        return Array.from(this.#snapshots.values());
      }
      /**
       * Gets snapshot count
       * @return {number} - Number of recorded snapshots
       */
      size() {
        return this.#snapshots.size;
      }
      /**
       * Resets call counts for all snapshots (useful for test cleanup)
       * @returns {void}
       */
      resetCallCounts() {
        for (const snapshot of this.#snapshots.values()) {
          snapshot.callCount = 0;
        }
      }
      /**
       * Deletes a specific snapshot by request options
       * @param {SnapshotRequestOptions} requestOpts - Request options to match
       * @returns {boolean} - True if snapshot was deleted, false if not found
       */
      deleteSnapshot(requestOpts) {
        const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions);
        const hash3 = createRequestHash(request);
        return this.#snapshots.delete(hash3);
      }
      /**
       * Gets information about a specific snapshot
       * @param {SnapshotRequestOptions} requestOpts - Request options to match
       * @returns {SnapshotInfo|null} - Snapshot information or null if not found
       */
      getSnapshotInfo(requestOpts) {
        const request = formatRequestKey(requestOpts, this.#headerFilters, this.matchOptions);
        const hash3 = createRequestHash(request);
        const snapshot = this.#snapshots.get(hash3);
        if (!snapshot) return null;
        return {
          hash: hash3,
          request: snapshot.request,
          responseCount: snapshot.responses ? snapshot.responses.length : snapshot.response ? 1 : 0,
          // .response for legacy snapshots
          callCount: snapshot.callCount || 0,
          timestamp: snapshot.timestamp
        };
      }
      /**
       * Replaces all snapshots with new data (full replacement)
       * @param {Array<{hash: string; snapshot: SnapshotEntry}>|Record<string, SnapshotEntry>} snapshotData - New snapshot data to replace existing ones
       * @returns {void}
       */
      replaceSnapshots(snapshotData) {
        this.#snapshots.clear();
        if (Array.isArray(snapshotData)) {
          for (const { hash: hash3, snapshot } of snapshotData) {
            this.#snapshots.set(hash3, snapshot);
          }
        } else if (snapshotData && typeof snapshotData === "object") {
          this.#snapshots = new Map(Object.entries(snapshotData));
        }
      }
      /**
       * Starts the auto-flush timer
       * @returns {void}
       */
      #startAutoFlush() {
        return this.#scheduleFlush();
      }
      /**
       * Stops the auto-flush timer
       * @returns {void}
       */
      #stopAutoFlush() {
        if (this.#flushTimeout) {
          clearTimeout2(this.#flushTimeout);
          this.saveSnapshots().catch(() => {
          });
          this.#flushTimeout = null;
        }
      }
      /**
       * Schedules a flush (debounced to avoid excessive writes)
       */
      #scheduleFlush() {
        this.#flushTimeout = setTimeout2(() => {
          this.saveSnapshots().catch(() => {
          });
          if (this.#autoFlush) {
            this.#flushTimeout?.refresh();
          } else {
            this.#flushTimeout = null;
          }
        }, 1e3);
      }
      /**
       * Cleanup method to stop timers
       * @returns {void}
       */
      destroy() {
        this.#stopAutoFlush();
        if (this.#flushTimeout) {
          clearTimeout2(this.#flushTimeout);
          this.#flushTimeout = null;
        }
      }
      /**
       * Async close method that saves all recordings and performs cleanup
       * @returns {Promise<void>}
       */
      async close() {
        if (this.#snapshotPath && this.#snapshots.size !== 0) {
          await this.saveSnapshots();
        }
        this.destroy();
      }
    };
    module.exports = { SnapshotRecorder, formatRequestKey, createRequestHash, filterHeadersForMatching, filterHeadersForStorage, createHeaderFilters };
  }
});

// node_modules/undici/lib/mock/snapshot-agent.js
var require_snapshot_agent = __commonJS({
  "node_modules/undici/lib/mock/snapshot-agent.js"(exports, module) {
    "use strict";
    var Agent = require_agent();
    var MockAgent = require_mock_agent();
    var { SnapshotRecorder } = require_snapshot_recorder();
    var { InvalidArgumentError, UndiciError } = require_errors();
    var util2 = require_util();
    var { validateSnapshotMode } = require_snapshot_utils();
    var kSnapshotRecorder = /* @__PURE__ */ Symbol("kSnapshotRecorder");
    var kSnapshotMode = /* @__PURE__ */ Symbol("kSnapshotMode");
    var kSnapshotPath = /* @__PURE__ */ Symbol("kSnapshotPath");
    var kSnapshotLoaded = /* @__PURE__ */ Symbol("kSnapshotLoaded");
    var kRealAgent = /* @__PURE__ */ Symbol("kRealAgent");
    var warningEmitted = false;
    var SnapshotAgent = class extends MockAgent {
      constructor(opts = {}) {
        if (!warningEmitted) {
          process.emitWarning(
            "SnapshotAgent is experimental and subject to change",
            "ExperimentalWarning"
          );
          warningEmitted = true;
        }
        const {
          mode = "record",
          snapshotPath = null,
          ...mockAgentOpts
        } = opts;
        super(mockAgentOpts);
        validateSnapshotMode(mode);
        if ((mode === "playback" || mode === "update") && !snapshotPath) {
          throw new InvalidArgumentError(`snapshotPath is required when mode is '${mode}'`);
        }
        this[kSnapshotMode] = mode;
        this[kSnapshotPath] = snapshotPath;
        this[kSnapshotRecorder] = new SnapshotRecorder({
          snapshotPath: this[kSnapshotPath],
          mode: this[kSnapshotMode],
          maxSnapshots: opts.maxSnapshots,
          autoFlush: opts.autoFlush,
          flushInterval: opts.flushInterval,
          matchHeaders: opts.matchHeaders,
          ignoreHeaders: opts.ignoreHeaders,
          excludeHeaders: opts.excludeHeaders,
          matchBody: opts.matchBody,
          matchQuery: opts.matchQuery,
          caseSensitive: opts.caseSensitive,
          shouldRecord: opts.shouldRecord,
          shouldPlayback: opts.shouldPlayback,
          excludeUrls: opts.excludeUrls
        });
        this[kSnapshotLoaded] = false;
        if (this[kSnapshotMode] === "record" || this[kSnapshotMode] === "update" || this[kSnapshotMode] === "playback" && opts.excludeUrls && opts.excludeUrls.length > 0) {
          this[kRealAgent] = new Agent(opts);
        }
        if ((this[kSnapshotMode] === "playback" || this[kSnapshotMode] === "update") && this[kSnapshotPath]) {
          this.loadSnapshots().catch(() => {
          });
        }
      }
      dispatch(opts, handler) {
        const mode = this[kSnapshotMode];
        if (this[kSnapshotRecorder].isUrlExcluded(opts)) {
          return this[kRealAgent].dispatch(opts, handler);
        }
        if (mode === "playback" || mode === "update") {
          if (!this[kSnapshotLoaded]) {
            return this.#asyncDispatch(opts, handler);
          }
          const snapshot = this[kSnapshotRecorder].findSnapshot(opts);
          if (snapshot) {
            return this.#replaySnapshot(snapshot, handler);
          } else if (mode === "update") {
            return this.#recordAndReplay(opts, handler);
          } else {
            const error = new UndiciError(`No snapshot found for ${opts.method || "GET"} ${opts.path}`);
            if (handler.onResponseError) {
              handler.onResponseError(null, error);
              return;
            }
            throw error;
          }
        } else if (mode === "record") {
          return this.#recordAndReplay(opts, handler);
        }
      }
      /**
       * Async version of dispatch for when we need to load snapshots first
       */
      async #asyncDispatch(opts, handler) {
        await this.loadSnapshots();
        return this.dispatch(opts, handler);
      }
      /**
       * Records a real request and replays the response
       */
      #recordAndReplay(opts, handler) {
        const responseData = {
          statusCode: null,
          headers: {},
          trailers: {},
          body: []
        };
        const self = this;
        const recordingHandler = {
          onRequestStart(controller, context) {
            return handler.onRequestStart(controller, { ...context, history: this.history });
          },
          onRequestUpgrade(controller, statusCode, headers, socket) {
            return handler.onRequestUpgrade(controller, statusCode, headers, socket);
          },
          onResponseStart(controller, statusCode, headers, statusMessage) {
            responseData.statusCode = statusCode;
            responseData.headers = headers;
            return handler.onResponseStart(controller, statusCode, headers, statusMessage);
          },
          onResponseData(controller, chunk) {
            responseData.body.push(chunk);
            return handler.onResponseData(controller, chunk);
          },
          onResponseEnd(controller, trailers) {
            responseData.trailers = trailers;
            const responseBody = Buffer.concat(responseData.body);
            self[kSnapshotRecorder].record(opts, {
              statusCode: responseData.statusCode,
              headers: responseData.headers,
              body: responseBody,
              trailers: responseData.trailers
            }).then(() => handler.onResponseEnd(controller, trailers)).catch((error) => handler.onResponseError(controller, error));
          },
          onResponseError(controller, error) {
            return handler.onResponseError(controller, error);
          }
        };
        const agent = this[kRealAgent];
        return agent.dispatch(opts, recordingHandler);
      }
      /**
       * Replays a recorded response
       *
       * @param {Object} snapshot - The recorded snapshot to replay.
       * @param {Object} handler - The handler to call with the response data.
       * @returns {void}
       */
      #replaySnapshot(snapshot, handler) {
        try {
          const { response } = snapshot;
          const rawHeaders = response.headers ? util2.toRawHeaders(response.headers) : [];
          const rawTrailers = response.trailers ? util2.toRawHeaders(response.trailers) : [];
          const controller = {
            rawHeaders,
            rawTrailers,
            pause() {
            },
            resume() {
            },
            abort(reason) {
              this.aborted = true;
              this.reason = reason;
            },
            aborted: false,
            paused: false
          };
          handler.onRequestStart(controller);
          handler.onResponseStart(controller, response.statusCode, response.headers, response.statusMessage);
          const body = Buffer.from(response.body, "base64");
          handler.onResponseData(controller, body);
          handler.onResponseEnd(controller, response.trailers);
        } catch (error) {
          handler.onResponseError?.(null, error);
        }
      }
      /**
       * Loads snapshots from file
       *
       * @param {string} [filePath] - Optional file path to load snapshots from.
       * @returns {Promise<void>} - Resolves when snapshots are loaded.
       */
      async loadSnapshots(filePath) {
        await this[kSnapshotRecorder].loadSnapshots(filePath || this[kSnapshotPath]);
        this[kSnapshotLoaded] = true;
        if (this[kSnapshotMode] === "playback") {
          this.#setupMockInterceptors();
        }
      }
      /**
       * Saves snapshots to file
       *
       * @param {string} [filePath] - Optional file path to save snapshots to.
       * @returns {Promise<void>} - Resolves when snapshots are saved.
       */
      async saveSnapshots(filePath) {
        return this[kSnapshotRecorder].saveSnapshots(filePath || this[kSnapshotPath]);
      }
      /**
       * Sets up MockAgent interceptors based on recorded snapshots.
       *
       * This method creates MockAgent interceptors for each recorded snapshot,
       * allowing the SnapshotAgent to fall back to MockAgent's standard intercept
       * mechanism in playback mode. Each interceptor is configured to persist
       * (remain active for multiple requests) and responds with the recorded
       * response data.
       *
       * Called automatically when loading snapshots in playback mode.
       *
       * @returns {void}
       */
      #setupMockInterceptors() {
        for (const snapshot of this[kSnapshotRecorder].getSnapshots()) {
          const { request, responses, response } = snapshot;
          const url = new URL(request.url);
          const mockPool = this.get(url.origin);
          const responseData = responses ? responses[0] : response;
          if (!responseData) continue;
          mockPool.intercept({
            path: url.pathname + url.search,
            method: request.method,
            headers: request.headers,
            body: request.body
          }).reply(responseData.statusCode, responseData.body, {
            headers: responseData.headers,
            trailers: responseData.trailers
          }).persist();
        }
      }
      /**
       * Gets the snapshot recorder
       * @return {SnapshotRecorder} - The snapshot recorder instance
       */
      getRecorder() {
        return this[kSnapshotRecorder];
      }
      /**
       * Gets the current mode
       * @return {import('./snapshot-utils').SnapshotMode} - The current snapshot mode
       */
      getMode() {
        return this[kSnapshotMode];
      }
      /**
       * Clears all snapshots
       * @returns {void}
       */
      clearSnapshots() {
        this[kSnapshotRecorder].clear();
      }
      /**
       * Resets call counts for all snapshots (useful for test cleanup)
       * @returns {void}
       */
      resetCallCounts() {
        this[kSnapshotRecorder].resetCallCounts();
      }
      /**
       * Deletes a specific snapshot by request options
       * @param {import('./snapshot-recorder').SnapshotRequestOptions} requestOpts - Request options to identify the snapshot
       * @return {Promise<boolean>} - Returns true if the snapshot was deleted, false if not found
       */
      deleteSnapshot(requestOpts) {
        return this[kSnapshotRecorder].deleteSnapshot(requestOpts);
      }
      /**
       * Gets information about a specific snapshot
       * @returns {import('./snapshot-recorder').SnapshotInfo|null} - Snapshot information or null if not found
       */
      getSnapshotInfo(requestOpts) {
        return this[kSnapshotRecorder].getSnapshotInfo(requestOpts);
      }
      /**
       * Replaces all snapshots with new data (full replacement)
       * @param {Array<{hash: string; snapshot: import('./snapshot-recorder').SnapshotEntryshotEntry}>|Record<string, import('./snapshot-recorder').SnapshotEntry>} snapshotData - New snapshot data to replace existing snapshots
       * @returns {void}
       */
      replaceSnapshots(snapshotData) {
        this[kSnapshotRecorder].replaceSnapshots(snapshotData);
      }
      /**
       * Closes the agent, saving snapshots and cleaning up resources.
       *
       * @returns {Promise<void>}
       */
      async close() {
        await this[kSnapshotRecorder].close();
        await this[kRealAgent]?.close();
        await super.close();
      }
    };
    module.exports = SnapshotAgent;
  }
});

// node_modules/undici/lib/global.js
var require_global2 = __commonJS({
  "node_modules/undici/lib/global.js"(exports, module) {
    "use strict";
    var globalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.2");
    var legacyGlobalDispatcher = /* @__PURE__ */ Symbol.for("undici.globalDispatcher.1");
    var { InvalidArgumentError } = require_errors();
    var Agent = require_agent();
    var Dispatcher1Wrapper = require_dispatcher1_wrapper();
    if (getGlobalDispatcher() === void 0) {
      setGlobalDispatcher(new Agent());
    }
    function setGlobalDispatcher(agent) {
      if (!agent || typeof agent.dispatch !== "function") {
        throw new InvalidArgumentError("Argument agent must implement Agent");
      }
      Object.defineProperty(globalThis, globalDispatcher, {
        value: agent,
        writable: true,
        enumerable: false,
        configurable: false
      });
      const legacyAgent = agent instanceof Dispatcher1Wrapper ? agent : new Dispatcher1Wrapper(agent);
      Object.defineProperty(globalThis, legacyGlobalDispatcher, {
        value: legacyAgent,
        writable: true,
        enumerable: false,
        configurable: false
      });
    }
    function getGlobalDispatcher() {
      return globalThis[globalDispatcher];
    }
    var installedExports = (
      /** @type {const} */
      [
        "fetch",
        "Headers",
        "Response",
        "Request",
        "FormData",
        "WebSocket",
        "CloseEvent",
        "ErrorEvent",
        "MessageEvent",
        "EventSource"
      ]
    );
    module.exports = {
      setGlobalDispatcher,
      getGlobalDispatcher,
      installedExports
    };
  }
});

// node_modules/undici/lib/handler/decorator-handler.js
var require_decorator_handler = __commonJS({
  "node_modules/undici/lib/handler/decorator-handler.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    module.exports = class DecoratorHandler {
      #handler;
      #onCompleteCalled = false;
      #onErrorCalled = false;
      #onResponseStartCalled = false;
      constructor(handler) {
        if (typeof handler !== "object" || handler === null) {
          throw new TypeError("handler must be an object");
        }
        this.#handler = handler;
      }
      onRequestStart(...args) {
        this.#handler.onRequestStart?.(...args);
      }
      onRequestUpgrade(...args) {
        assert8(!this.#onCompleteCalled);
        assert8(!this.#onErrorCalled);
        return this.#handler.onRequestUpgrade?.(...args);
      }
      onResponseStart(...args) {
        assert8(!this.#onCompleteCalled);
        assert8(!this.#onErrorCalled);
        assert8(!this.#onResponseStartCalled);
        this.#onResponseStartCalled = true;
        return this.#handler.onResponseStart?.(...args);
      }
      onResponseData(...args) {
        assert8(!this.#onCompleteCalled);
        assert8(!this.#onErrorCalled);
        return this.#handler.onResponseData?.(...args);
      }
      onResponseEnd(...args) {
        assert8(!this.#onCompleteCalled);
        assert8(!this.#onErrorCalled);
        this.#onCompleteCalled = true;
        return this.#handler.onResponseEnd?.(...args);
      }
      onResponseError(...args) {
        this.#onErrorCalled = true;
        return this.#handler.onResponseError?.(...args);
      }
      /**
       * @deprecated
       */
      onBodySent() {
      }
    };
  }
});

// node_modules/undici/lib/handler/redirect-handler.js
var require_redirect_handler = __commonJS({
  "node_modules/undici/lib/handler/redirect-handler.js"(exports, module) {
    "use strict";
    var util2 = require_util();
    var assert8 = __require("assert");
    var { InvalidArgumentError } = require_errors();
    var redirectableStatusCodes = [300, 301, 302, 303, 307, 308];
    var noop = () => {
    };
    var RedirectHandler = class _RedirectHandler {
      static buildDispatch(dispatcher, maxRedirections) {
        if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
          throw new InvalidArgumentError("maxRedirections must be a positive number");
        }
        const dispatch = dispatcher.dispatch.bind(dispatcher);
        return (opts, originalHandler) => dispatch(opts, new _RedirectHandler(dispatch, maxRedirections, opts, originalHandler));
      }
      constructor(dispatch, maxRedirections, opts, handler) {
        if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
          throw new InvalidArgumentError("maxRedirections must be a positive number");
        }
        if (opts.throwOnMaxRedirect != null && typeof opts.throwOnMaxRedirect !== "boolean") {
          throw new InvalidArgumentError("throwOnMaxRedirect must be a boolean");
        }
        this.dispatch = dispatch;
        this.location = null;
        const { maxRedirections: _, ...cleanOpts } = opts;
        this.opts = cleanOpts;
        this.opts.body = util2.wrapRequestBody(this.opts.body);
        this.maxRedirections = maxRedirections;
        this.handler = handler;
        this.history = [];
      }
      onRequestStart(controller, context) {
        this.handler.onRequestStart?.(controller, { ...context, history: this.history });
      }
      onRequestUpgrade(controller, statusCode, headers, socket) {
        this.handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
      }
      onResponseStart(controller, statusCode, headers, statusMessage) {
        if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) {
          throw new Error("max redirects");
        }
        if ((statusCode === 301 || statusCode === 302) && this.opts.method === "POST") {
          this.opts.method = "GET";
          if (util2.isStream(this.opts.body)) {
            util2.destroy(this.opts.body.on("error", noop));
          }
          this.opts.body = null;
        }
        if (statusCode === 303 && this.opts.method !== "HEAD") {
          this.opts.method = "GET";
          if (util2.isStream(this.opts.body)) {
            util2.destroy(this.opts.body.on("error", noop));
          }
          this.opts.body = null;
        }
        this.location = this.history.length >= this.maxRedirections || util2.isDisturbed(this.opts.body) || redirectableStatusCodes.indexOf(statusCode) === -1 ? null : headers.location;
        if (this.opts.origin) {
          this.history.push(new URL(this.opts.path, this.opts.origin));
        }
        if (!this.location) {
          this.handler.onResponseStart?.(controller, statusCode, headers, statusMessage);
          return;
        }
        const { origin, pathname, search } = util2.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
        const path2 = search ? `${pathname}${search}` : pathname;
        const redirectUrlString = `${origin}${path2}`;
        for (const historyUrl of this.history) {
          if (historyUrl.toString() === redirectUrlString) {
            throw new InvalidArgumentError(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`);
          }
        }
        this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
        this.opts.path = path2;
        this.opts.origin = origin;
        this.opts.query = null;
      }
      onResponseData(controller, chunk) {
        if (this.location) {
        } else {
          this.handler.onResponseData?.(controller, chunk);
        }
      }
      onResponseEnd(controller, trailers) {
        if (this.location) {
          this.dispatch(this.opts, this);
        } else {
          this.handler.onResponseEnd(controller, trailers);
        }
      }
      onResponseError(controller, error) {
        this.handler.onResponseError?.(controller, error);
      }
    };
    function shouldRemoveHeader(header, removeContent, unknownOrigin) {
      if (header.length === 4) {
        return util2.headerNameToString(header) === "host";
      }
      if (removeContent && util2.headerNameToString(header).startsWith("content-")) {
        return true;
      }
      if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
        const name = util2.headerNameToString(header);
        return name === "authorization" || name === "cookie" || name === "proxy-authorization";
      }
      return false;
    }
    function cleanRequestHeaders(headers, removeContent, unknownOrigin) {
      const ret = [];
      if (Array.isArray(headers)) {
        for (let i = 0; i < headers.length; i += 2) {
          if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {
            ret.push(headers[i], headers[i + 1]);
          }
        }
      } else if (headers && typeof headers === "object") {
        const entries = util2.hasSafeIterator(headers) ? headers : Object.entries(headers);
        for (const [key, value] of entries) {
          if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
            ret.push(key, value);
          }
        }
      } else {
        assert8(headers == null, "headers must be an object or an array");
      }
      return ret;
    }
    module.exports = RedirectHandler;
  }
});

// node_modules/undici/lib/interceptor/redirect.js
var require_redirect = __commonJS({
  "node_modules/undici/lib/interceptor/redirect.js"(exports, module) {
    "use strict";
    var RedirectHandler = require_redirect_handler();
    function createRedirectInterceptor({ maxRedirections: defaultMaxRedirections, throwOnMaxRedirect: defaultThrowOnMaxRedirect } = {}) {
      return (dispatch) => {
        return function Intercept(opts, handler) {
          const { maxRedirections = defaultMaxRedirections, throwOnMaxRedirect = defaultThrowOnMaxRedirect, ...rest } = opts;
          if (maxRedirections == null || maxRedirections === 0) {
            return dispatch(opts, handler);
          }
          const dispatchOpts = { ...rest, throwOnMaxRedirect };
          const redirectHandler = new RedirectHandler(dispatch, maxRedirections, dispatchOpts, handler);
          return dispatch(dispatchOpts, redirectHandler);
        };
      };
    }
    module.exports = createRedirectInterceptor;
  }
});

// node_modules/undici/lib/interceptor/response-error.js
var require_response_error = __commonJS({
  "node_modules/undici/lib/interceptor/response-error.js"(exports, module) {
    "use strict";
    var DecoratorHandler = require_decorator_handler();
    var { ResponseError } = require_errors();
    var ResponseErrorHandler = class extends DecoratorHandler {
      #statusCode;
      #contentType;
      #decoder;
      #headers;
      #body;
      constructor(_opts, { handler }) {
        super(handler);
      }
      #checkContentType(contentType) {
        return (this.#contentType ?? "").indexOf(contentType) === 0;
      }
      onRequestStart(controller, context) {
        this.#statusCode = 0;
        this.#contentType = null;
        this.#decoder = null;
        this.#headers = null;
        this.#body = "";
        return super.onRequestStart(controller, context);
      }
      onResponseStart(controller, statusCode, headers, statusMessage) {
        this.#statusCode = statusCode;
        this.#headers = headers;
        this.#contentType = headers["content-type"];
        if (this.#statusCode < 400) {
          return super.onResponseStart(controller, statusCode, headers, statusMessage);
        }
        if (this.#checkContentType("application/json") || this.#checkContentType("text/plain")) {
          this.#decoder = new TextDecoder("utf-8");
        }
      }
      onResponseData(controller, chunk) {
        if (this.#statusCode < 400) {
          return super.onResponseData(controller, chunk);
        }
        this.#body += this.#decoder?.decode(chunk, { stream: true }) ?? "";
      }
      onResponseEnd(controller, trailers) {
        if (this.#statusCode >= 400) {
          this.#body += this.#decoder?.decode(void 0, { stream: false }) ?? "";
          if (this.#checkContentType("application/json")) {
            try {
              this.#body = JSON.parse(this.#body);
            } catch {
            }
          }
          let err;
          const stackTraceLimit = Error.stackTraceLimit;
          Error.stackTraceLimit = 0;
          try {
            err = new ResponseError("Response Error", this.#statusCode, {
              body: this.#body,
              headers: this.#headers
            });
          } finally {
            Error.stackTraceLimit = stackTraceLimit;
          }
          super.onResponseError(controller, err);
        } else {
          super.onResponseEnd(controller, trailers);
        }
      }
      onResponseError(controller, err) {
        super.onResponseError(controller, err);
      }
    };
    module.exports = () => {
      return (dispatch) => {
        return function Intercept(opts, handler) {
          return dispatch(opts, new ResponseErrorHandler(opts, { handler }));
        };
      };
    };
  }
});

// node_modules/undici/lib/interceptor/retry.js
var require_retry = __commonJS({
  "node_modules/undici/lib/interceptor/retry.js"(exports, module) {
    "use strict";
    var RetryHandler = require_retry_handler();
    module.exports = (globalOpts) => {
      return (dispatch) => {
        return function retryInterceptor(opts, handler) {
          return dispatch(
            opts,
            new RetryHandler(
              { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } },
              {
                handler,
                dispatch
              }
            )
          );
        };
      };
    };
  }
});

// node_modules/undici/lib/interceptor/dump.js
var require_dump = __commonJS({
  "node_modules/undici/lib/interceptor/dump.js"(exports, module) {
    "use strict";
    var { InvalidArgumentError, RequestAbortedError } = require_errors();
    var DecoratorHandler = require_decorator_handler();
    var DumpHandler = class extends DecoratorHandler {
      #maxSize = 1024 * 1024;
      #dumped = false;
      #size = 0;
      #controller = null;
      aborted = false;
      reason = false;
      constructor({ maxSize, signal }, handler) {
        if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) {
          throw new InvalidArgumentError("maxSize must be a number greater than 0");
        }
        super(handler);
        this.#maxSize = maxSize ?? this.#maxSize;
      }
      #abort(reason) {
        this.aborted = true;
        this.reason = reason;
      }
      onRequestStart(controller, context) {
        controller.abort = this.#abort.bind(this);
        this.#controller = controller;
        return super.onRequestStart(controller, context);
      }
      onResponseStart(controller, statusCode, headers, statusMessage) {
        const contentLength = headers["content-length"];
        if (contentLength != null && contentLength > this.#maxSize) {
          throw new RequestAbortedError(
            `Response size (${contentLength}) larger than maxSize (${this.#maxSize})`
          );
        }
        if (this.aborted === true) {
          return true;
        }
        return super.onResponseStart(controller, statusCode, headers, statusMessage);
      }
      onResponseError(controller, err) {
        if (this.#dumped) {
          return;
        }
        err = this.#controller?.reason ?? err;
        super.onResponseError(controller, err);
      }
      onResponseData(controller, chunk) {
        this.#size = this.#size + chunk.length;
        if (this.#size >= this.#maxSize) {
          this.#dumped = true;
          if (this.aborted === true) {
            super.onResponseError(controller, this.reason);
          } else {
            super.onResponseEnd(controller, {});
          }
        }
        return true;
      }
      onResponseEnd(controller, trailers) {
        if (this.#dumped) {
          return;
        }
        if (this.#controller.aborted === true) {
          super.onResponseError(controller, this.reason);
          return;
        }
        super.onResponseEnd(controller, trailers);
      }
    };
    function createDumpInterceptor({ maxSize: defaultMaxSize } = {
      maxSize: 1024 * 1024
    }) {
      return (dispatch) => {
        return function Intercept(opts, handler) {
          const { dumpMaxSize = defaultMaxSize } = opts;
          const dumpHandler = new DumpHandler({ maxSize: dumpMaxSize, signal: opts.signal }, handler);
          return dispatch(opts, dumpHandler);
        };
      };
    }
    module.exports = createDumpInterceptor;
  }
});

// node_modules/undici/lib/interceptor/dns.js
var require_dns = __commonJS({
  "node_modules/undici/lib/interceptor/dns.js"(exports, module) {
    "use strict";
    var { isIP } = __require("net");
    var { lookup } = __require("dns");
    var DecoratorHandler = require_decorator_handler();
    var { InvalidArgumentError, InformationalError } = require_errors();
    var maxInt = Math.pow(2, 31) - 1;
    function hasSafeIterator(headers) {
      const prototype = Object.getPrototypeOf(headers);
      const ownIterator = Object.hasOwn(headers, Symbol.iterator);
      return ownIterator || prototype != null && prototype !== Object.prototype && typeof headers[Symbol.iterator] === "function";
    }
    function isHostHeader(key) {
      return typeof key === "string" && key.toLowerCase() === "host";
    }
    function normalizeHeaders3(headers) {
      if (headers == null) {
        return null;
      }
      if (Array.isArray(headers)) {
        if (headers.length === 0 || !Array.isArray(headers[0])) {
          return headers;
        }
        const normalized = [];
        for (const header of headers) {
          if (Array.isArray(header) && header.length === 2) {
            normalized.push(header[0], header[1]);
          } else {
            normalized.push(header);
          }
        }
        return normalized;
      }
      if (typeof headers === "object" && hasSafeIterator(headers)) {
        const normalized = [];
        for (const header of headers) {
          if (Array.isArray(header) && header.length === 2) {
            normalized.push(header[0], header[1]);
          } else {
            normalized.push(header);
          }
        }
        return normalized;
      }
      return headers;
    }
    function hasHostHeader(headers) {
      if (headers == null) {
        return false;
      }
      if (Array.isArray(headers)) {
        if (headers.length === 0) {
          return false;
        }
        for (let i = 0; i < headers.length; i += 2) {
          if (isHostHeader(headers[i])) {
            return true;
          }
        }
        return false;
      }
      if (typeof headers === "object") {
        for (const key in headers) {
          if (isHostHeader(key)) {
            return true;
          }
        }
      }
      return false;
    }
    function withHostHeader(host, headers) {
      const normalizedHeaders = normalizeHeaders3(headers);
      if (hasHostHeader(normalizedHeaders)) {
        return normalizedHeaders;
      }
      if (Array.isArray(normalizedHeaders)) {
        return ["host", host, ...normalizedHeaders];
      }
      if (normalizedHeaders && typeof normalizedHeaders === "object") {
        return {
          host,
          ...normalizedHeaders
        };
      }
      return { host };
    }
    var DNSStorage = class {
      #maxItems = 0;
      #records = /* @__PURE__ */ new Map();
      constructor(opts) {
        this.#maxItems = opts.maxItems;
      }
      get size() {
        return this.#records.size;
      }
      get(hostname) {
        return this.#records.get(hostname) ?? null;
      }
      set(hostname, records) {
        this.#records.set(hostname, records);
      }
      delete(hostname) {
        this.#records.delete(hostname);
      }
      // Delegate to storage decide can we do more lookups or not
      full() {
        return this.size >= this.#maxItems;
      }
    };
    var DNSInstance = class {
      #maxTTL = 0;
      #maxItems = 0;
      dualStack = true;
      affinity = null;
      lookup = null;
      pick = null;
      storage = null;
      constructor(opts) {
        this.#maxTTL = opts.maxTTL;
        this.#maxItems = opts.maxItems;
        this.dualStack = opts.dualStack;
        this.affinity = opts.affinity;
        this.lookup = opts.lookup ?? this.#defaultLookup;
        this.pick = opts.pick ?? this.#defaultPick;
        this.storage = opts.storage ?? new DNSStorage(opts);
      }
      runLookup(origin, opts, cb) {
        const ips = this.storage.get(origin.hostname);
        if (ips == null && this.storage.full()) {
          cb(null, origin);
          return;
        }
        const newOpts = {
          affinity: this.affinity,
          dualStack: this.dualStack,
          lookup: this.lookup,
          pick: this.pick,
          ...opts.dns,
          maxTTL: this.#maxTTL,
          maxItems: this.#maxItems
        };
        if (ips == null) {
          this.lookup(origin, newOpts, (err, addresses) => {
            if (err || addresses == null || addresses.length === 0) {
              cb(err ?? new InformationalError("No DNS entries found"));
              return;
            }
            this.setRecords(origin, addresses);
            const records = this.storage.get(origin.hostname);
            const ip = this.pick(
              origin,
              records,
              newOpts.affinity
            );
            let port;
            if (typeof ip.port === "number") {
              port = `:${ip.port}`;
            } else if (origin.port !== "") {
              port = `:${origin.port}`;
            } else {
              port = "";
            }
            cb(
              null,
              new URL(`${origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`)
            );
          });
        } else {
          const ip = this.pick(
            origin,
            ips,
            newOpts.affinity
          );
          if (ip == null) {
            this.storage.delete(origin.hostname);
            this.runLookup(origin, opts, cb);
            return;
          }
          let port;
          if (typeof ip.port === "number") {
            port = `:${ip.port}`;
          } else if (origin.port !== "") {
            port = `:${origin.port}`;
          } else {
            port = "";
          }
          cb(
            null,
            new URL(`${origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`)
          );
        }
      }
      #defaultLookup(origin, opts, cb) {
        lookup(
          origin.hostname,
          {
            all: true,
            family: this.dualStack === false ? this.affinity : 0,
            order: "ipv4first"
          },
          (err, addresses) => {
            if (err) {
              return cb(err);
            }
            const results = /* @__PURE__ */ new Map();
            for (const addr of addresses) {
              results.set(`${addr.address}:${addr.family}`, addr);
            }
            cb(null, results.values());
          }
        );
      }
      #defaultPick(origin, hostnameRecords, affinity) {
        let ip = null;
        const { records, offset } = hostnameRecords;
        let family;
        if (this.dualStack) {
          if (affinity == null) {
            if (offset == null || offset === maxInt) {
              hostnameRecords.offset = 0;
              affinity = 4;
            } else {
              hostnameRecords.offset++;
              affinity = (hostnameRecords.offset & 1) === 1 ? 6 : 4;
            }
          }
          if (records[affinity] != null && records[affinity].ips.length > 0) {
            family = records[affinity];
          } else {
            family = records[affinity === 4 ? 6 : 4];
          }
        } else {
          family = records[affinity];
        }
        if (family == null || family.ips.length === 0) {
          return ip;
        }
        if (family.offset == null || family.offset === maxInt) {
          family.offset = 0;
        } else {
          family.offset++;
        }
        const position = family.offset % family.ips.length;
        ip = family.ips[position] ?? null;
        if (ip == null) {
          return ip;
        }
        if (Date.now() - ip.timestamp > ip.ttl) {
          family.ips.splice(position, 1);
          return this.pick(origin, hostnameRecords, affinity);
        }
        return ip;
      }
      pickFamily(origin, ipFamily) {
        const records = this.storage.get(origin.hostname)?.records;
        if (!records) {
          return null;
        }
        const family = records[ipFamily];
        if (!family) {
          return null;
        }
        if (family.offset == null || family.offset === maxInt) {
          family.offset = 0;
        } else {
          family.offset++;
        }
        const position = family.offset % family.ips.length;
        const ip = family.ips[position] ?? null;
        if (ip == null) {
          return ip;
        }
        if (Date.now() - ip.timestamp > ip.ttl) {
          family.ips.splice(position, 1);
        }
        return ip;
      }
      setRecords(origin, addresses) {
        const timestamp = Date.now();
        const records = { records: { 4: null, 6: null } };
        let minTTL = this.#maxTTL;
        for (const record of addresses) {
          record.timestamp = timestamp;
          if (typeof record.ttl === "number") {
            record.ttl = Math.min(record.ttl, this.#maxTTL);
            minTTL = Math.min(minTTL, record.ttl);
          } else {
            record.ttl = this.#maxTTL;
          }
          const familyRecords = records.records[record.family] ?? { ips: [] };
          familyRecords.ips.push(record);
          records.records[record.family] = familyRecords;
        }
        this.storage.set(origin.hostname, records, { ttl: minTTL });
      }
      deleteRecords(origin) {
        this.storage.delete(origin.hostname);
      }
      getHandler(meta, opts) {
        return new DNSDispatchHandler(this, meta, opts);
      }
    };
    var DNSDispatchHandler = class extends DecoratorHandler {
      #state = null;
      #opts = null;
      #dispatch = null;
      #origin = null;
      #controller = null;
      #newOrigin = null;
      #firstTry = true;
      constructor(state, { origin, handler, dispatch, newOrigin }, opts) {
        super(handler);
        this.#origin = origin;
        this.#newOrigin = newOrigin;
        this.#opts = { ...opts };
        this.#state = state;
        this.#dispatch = dispatch;
      }
      onResponseError(controller, err) {
        switch (err.code) {
          case "ETIMEDOUT":
          case "ECONNREFUSED": {
            if (this.#state.dualStack) {
              if (!this.#firstTry) {
                super.onResponseError(controller, err);
                return;
              }
              this.#firstTry = false;
              const otherFamily = this.#newOrigin.hostname[0] === "[" ? 4 : 6;
              const ip = this.#state.pickFamily(this.#origin, otherFamily);
              if (ip == null) {
                super.onResponseError(controller, err);
                return;
              }
              let port;
              if (typeof ip.port === "number") {
                port = `:${ip.port}`;
              } else if (this.#origin.port !== "") {
                port = `:${this.#origin.port}`;
              } else {
                port = "";
              }
              const dispatchOpts = {
                ...this.#opts,
                origin: `${this.#origin.protocol}//${ip.family === 6 ? `[${ip.address}]` : ip.address}${port}`,
                headers: withHostHeader(this.#origin.host, this.#opts.headers)
              };
              this.#dispatch(dispatchOpts, this);
              return;
            }
            super.onResponseError(controller, err);
            break;
          }
          case "ENOTFOUND":
            this.#state.deleteRecords(this.#origin);
            super.onResponseError(controller, err);
            break;
          default:
            super.onResponseError(controller, err);
            break;
        }
      }
    };
    module.exports = (interceptorOpts) => {
      if (interceptorOpts?.maxTTL != null && (typeof interceptorOpts?.maxTTL !== "number" || interceptorOpts?.maxTTL < 0)) {
        throw new InvalidArgumentError("Invalid maxTTL. Must be a positive number");
      }
      if (interceptorOpts?.maxItems != null && (typeof interceptorOpts?.maxItems !== "number" || interceptorOpts?.maxItems < 1)) {
        throw new InvalidArgumentError(
          "Invalid maxItems. Must be a positive number and greater than zero"
        );
      }
      if (interceptorOpts?.affinity != null && interceptorOpts?.affinity !== 4 && interceptorOpts?.affinity !== 6) {
        throw new InvalidArgumentError("Invalid affinity. Must be either 4 or 6");
      }
      if (interceptorOpts?.dualStack != null && typeof interceptorOpts?.dualStack !== "boolean") {
        throw new InvalidArgumentError("Invalid dualStack. Must be a boolean");
      }
      if (interceptorOpts?.lookup != null && typeof interceptorOpts?.lookup !== "function") {
        throw new InvalidArgumentError("Invalid lookup. Must be a function");
      }
      if (interceptorOpts?.pick != null && typeof interceptorOpts?.pick !== "function") {
        throw new InvalidArgumentError("Invalid pick. Must be a function");
      }
      if (interceptorOpts?.storage != null && (typeof interceptorOpts?.storage?.get !== "function" || typeof interceptorOpts?.storage?.set !== "function" || typeof interceptorOpts?.storage?.full !== "function" || typeof interceptorOpts?.storage?.delete !== "function")) {
        throw new InvalidArgumentError("Invalid storage. Must be a object with methods: { get, set, full, delete }");
      }
      const dualStack = interceptorOpts?.dualStack ?? true;
      let affinity;
      if (dualStack) {
        affinity = interceptorOpts?.affinity ?? null;
      } else {
        affinity = interceptorOpts?.affinity ?? 4;
      }
      const opts = {
        maxTTL: interceptorOpts?.maxTTL ?? 1e4,
        // Expressed in ms
        lookup: interceptorOpts?.lookup ?? null,
        pick: interceptorOpts?.pick ?? null,
        dualStack,
        affinity,
        maxItems: interceptorOpts?.maxItems ?? Infinity,
        storage: interceptorOpts?.storage
      };
      const instance = new DNSInstance(opts);
      return (dispatch) => {
        return function dnsInterceptor(origDispatchOpts, handler) {
          const origin = origDispatchOpts.origin.constructor === URL ? origDispatchOpts.origin : new URL(origDispatchOpts.origin);
          if (isIP(origin.hostname) !== 0) {
            return dispatch(origDispatchOpts, handler);
          }
          instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => {
            if (err) {
              return handler.onResponseError(null, err);
            }
            const dispatchOpts = {
              ...origDispatchOpts,
              servername: origin.hostname,
              // For SNI on TLS
              origin: newOrigin.origin,
              headers: withHostHeader(origin.host, origDispatchOpts.headers)
            };
            dispatch(
              dispatchOpts,
              instance.getHandler(
                { origin, dispatch, handler, newOrigin },
                origDispatchOpts
              )
            );
          });
          return true;
        };
      };
    };
  }
});

// node_modules/undici/lib/util/cache.js
var require_cache = __commonJS({
  "node_modules/undici/lib/util/cache.js"(exports, module) {
    "use strict";
    var {
      safeHTTPMethods,
      pathHasQueryOrFragment,
      hasSafeIterator
    } = require_util();
    var { serializePathWithQuery } = require_util();
    function makeCacheKey(opts) {
      if (!opts.origin) {
        throw new Error("opts.origin is undefined");
      }
      let fullPath = opts.path || "/";
      if (opts.query && !pathHasQueryOrFragment(fullPath)) {
        fullPath = serializePathWithQuery(fullPath, opts.query);
      }
      return {
        origin: opts.origin.toString(),
        method: opts.method,
        path: fullPath,
        headers: opts.headers
      };
    }
    function normalizeHeaders3(opts) {
      let headers;
      if (opts.headers == null) {
        headers = {};
      } else if (typeof opts.headers === "object") {
        headers = {};
        if (hasSafeIterator(opts.headers)) {
          for (const x of opts.headers) {
            if (!Array.isArray(x)) {
              throw new Error("opts.headers is not a valid header map");
            }
            const [key, val] = x;
            if (typeof key !== "string" || typeof val !== "string") {
              throw new Error("opts.headers is not a valid header map");
            }
            headers[key.toLowerCase()] = val;
          }
        } else {
          for (const key of Object.keys(opts.headers)) {
            headers[key.toLowerCase()] = opts.headers[key];
          }
        }
      } else {
        throw new Error("opts.headers is not an object");
      }
      return headers;
    }
    function assertCacheKey(key) {
      if (typeof key !== "object") {
        throw new TypeError(`expected key to be object, got ${typeof key}`);
      }
      for (const property of ["origin", "method", "path"]) {
        if (typeof key[property] !== "string") {
          throw new TypeError(`expected key.${property} to be string, got ${typeof key[property]}`);
        }
      }
      if (key.headers !== void 0 && typeof key.headers !== "object") {
        throw new TypeError(`expected headers to be object, got ${typeof key}`);
      }
    }
    function assertCacheValue(value) {
      if (typeof value !== "object") {
        throw new TypeError(`expected value to be object, got ${typeof value}`);
      }
      for (const property of ["statusCode", "cachedAt", "staleAt", "deleteAt"]) {
        if (typeof value[property] !== "number") {
          throw new TypeError(`expected value.${property} to be number, got ${typeof value[property]}`);
        }
      }
      if (typeof value.statusMessage !== "string") {
        throw new TypeError(`expected value.statusMessage to be string, got ${typeof value.statusMessage}`);
      }
      if (value.headers != null && typeof value.headers !== "object") {
        throw new TypeError(`expected value.rawHeaders to be object, got ${typeof value.headers}`);
      }
      if (value.vary !== void 0 && typeof value.vary !== "object") {
        throw new TypeError(`expected value.vary to be object, got ${typeof value.vary}`);
      }
      if (value.etag !== void 0 && typeof value.etag !== "string") {
        throw new TypeError(`expected value.etag to be string, got ${typeof value.etag}`);
      }
    }
    function parseCacheControlHeader(header) {
      const output = {};
      let directives;
      if (Array.isArray(header)) {
        directives = [];
        for (const directive of header) {
          directives.push(...directive.split(","));
        }
      } else {
        directives = header.split(",");
      }
      for (let i = 0; i < directives.length; i++) {
        const directive = directives[i].toLowerCase();
        const keyValueDelimiter = directive.indexOf("=");
        let key;
        let value;
        if (keyValueDelimiter !== -1) {
          key = directive.substring(0, keyValueDelimiter).trimStart();
          value = directive.substring(keyValueDelimiter + 1);
        } else {
          key = directive.trim();
        }
        switch (key) {
          case "min-fresh":
          case "max-stale":
          case "max-age":
          case "s-maxage":
          case "stale-while-revalidate":
          case "stale-if-error": {
            if (value === void 0 || value[0] === " ") {
              continue;
            }
            if (value.length >= 2 && value[0] === '"' && value[value.length - 1] === '"') {
              value = value.substring(1, value.length - 1);
            }
            const parsedValue = parseInt(value, 10);
            if (parsedValue !== parsedValue) {
              continue;
            }
            if (key === "max-age" && key in output && output[key] >= parsedValue) {
              continue;
            }
            output[key] = parsedValue;
            break;
          }
          case "private":
          case "no-cache": {
            if (value) {
              if (value[0] === '"') {
                const headers = [value.substring(1)];
                let foundEndingQuote = value[value.length - 1] === '"';
                if (!foundEndingQuote) {
                  for (let j = i + 1; j < directives.length; j++) {
                    const nextPart = directives[j];
                    const nextPartLength = nextPart.length;
                    headers.push(nextPart.trim());
                    if (nextPartLength !== 0 && nextPart[nextPartLength - 1] === '"') {
                      foundEndingQuote = true;
                      break;
                    }
                  }
                }
                if (foundEndingQuote) {
                  let lastHeader = headers[headers.length - 1];
                  if (lastHeader[lastHeader.length - 1] === '"') {
                    lastHeader = lastHeader.substring(0, lastHeader.length - 1);
                    headers[headers.length - 1] = lastHeader;
                  }
                  if (key in output) {
                    output[key] = output[key].concat(headers);
                  } else {
                    output[key] = headers;
                  }
                }
              } else {
                if (key in output) {
                  output[key] = output[key].concat(value);
                } else {
                  output[key] = [value];
                }
              }
              break;
            }
          }
          // eslint-disable-next-line no-fallthrough
          case "public":
          case "no-store":
          case "must-revalidate":
          case "proxy-revalidate":
          case "immutable":
          case "no-transform":
          case "must-understand":
          case "only-if-cached":
            if (value) {
              continue;
            }
            output[key] = true;
            break;
          default:
            continue;
        }
      }
      return output;
    }
    function parseVaryHeader(varyHeader, headers) {
      if (typeof varyHeader === "string" && varyHeader.includes("*")) {
        return headers;
      }
      const output = (
        /** @type {Record<string, string | string[] | null>} */
        {}
      );
      const varyingHeaders = typeof varyHeader === "string" ? varyHeader.split(",") : varyHeader;
      for (const header of varyingHeaders) {
        const trimmedHeader = header.trim().toLowerCase();
        output[trimmedHeader] = headers[trimmedHeader] ?? null;
      }
      return output;
    }
    function isEtagUsable(etag) {
      if (etag.length <= 2) {
        return false;
      }
      if (etag[0] === '"' && etag[etag.length - 1] === '"') {
        return !(etag[1] === '"' || etag.startsWith('"W/'));
      }
      if (etag.startsWith('W/"') && etag[etag.length - 1] === '"') {
        return etag.length !== 4;
      }
      return false;
    }
    function assertCacheStore(store, name = "CacheStore") {
      if (typeof store !== "object" || store === null) {
        throw new TypeError(`expected type of ${name} to be a CacheStore, got ${store === null ? "null" : typeof store}`);
      }
      for (const fn of ["get", "createWriteStream", "delete"]) {
        if (typeof store[fn] !== "function") {
          throw new TypeError(`${name} needs to have a \`${fn}()\` function`);
        }
      }
    }
    function assertCacheMethods(methods, name = "CacheMethods") {
      if (!Array.isArray(methods)) {
        throw new TypeError(`expected type of ${name} needs to be an array, got ${methods === null ? "null" : typeof methods}`);
      }
      if (methods.length === 0) {
        throw new TypeError(`${name} needs to have at least one method`);
      }
      for (const method of methods) {
        if (!safeHTTPMethods.includes(method)) {
          throw new TypeError(`element of ${name}-array needs to be one of following values: ${safeHTTPMethods.join(", ")}, got ${method}`);
        }
      }
    }
    function makeDeduplicationKey(cacheKey2, excludeHeaders) {
      const headers = {};
      if (cacheKey2.headers) {
        const sortedHeaders = Object.keys(cacheKey2.headers).sort();
        for (const header of sortedHeaders) {
          if (excludeHeaders?.has(header.toLowerCase())) {
            continue;
          }
          headers[header] = cacheKey2.headers[header];
        }
      }
      return JSON.stringify([cacheKey2.origin, cacheKey2.method, cacheKey2.path, headers]);
    }
    module.exports = {
      makeCacheKey,
      normalizeHeaders: normalizeHeaders3,
      assertCacheKey,
      assertCacheValue,
      parseCacheControlHeader,
      parseVaryHeader,
      isEtagUsable,
      assertCacheMethods,
      assertCacheStore,
      makeDeduplicationKey
    };
  }
});

// node_modules/undici/lib/util/date.js
var require_date = __commonJS({
  "node_modules/undici/lib/util/date.js"(exports, module) {
    "use strict";
    function parseHttpDate(date) {
      switch (date[3]) {
        case ",":
          return parseImfDate(date);
        case " ":
          return parseAscTimeDate(date);
        default:
          return parseRfc850Date(date);
      }
    }
    function parseImfDate(date) {
      if (date.length !== 29 || date[4] !== " " || date[7] !== " " || date[11] !== " " || date[16] !== " " || date[19] !== ":" || date[22] !== ":" || date[25] !== " " || date[26] !== "G" || date[27] !== "M" || date[28] !== "T") {
        return void 0;
      }
      let weekday = -1;
      if (date[0] === "S" && date[1] === "u" && date[2] === "n") {
        weekday = 0;
      } else if (date[0] === "M" && date[1] === "o" && date[2] === "n") {
        weekday = 1;
      } else if (date[0] === "T" && date[1] === "u" && date[2] === "e") {
        weekday = 2;
      } else if (date[0] === "W" && date[1] === "e" && date[2] === "d") {
        weekday = 3;
      } else if (date[0] === "T" && date[1] === "h" && date[2] === "u") {
        weekday = 4;
      } else if (date[0] === "F" && date[1] === "r" && date[2] === "i") {
        weekday = 5;
      } else if (date[0] === "S" && date[1] === "a" && date[2] === "t") {
        weekday = 6;
      } else {
        return void 0;
      }
      let day = 0;
      if (date[5] === "0") {
        const code = date.charCodeAt(6);
        if (code < 49 || code > 57) {
          return void 0;
        }
        day = code - 48;
      } else {
        const code1 = date.charCodeAt(5);
        if (code1 < 49 || code1 > 51) {
          return void 0;
        }
        const code2 = date.charCodeAt(6);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        day = (code1 - 48) * 10 + (code2 - 48);
      }
      let monthIdx = -1;
      if (date[8] === "J" && date[9] === "a" && date[10] === "n") {
        monthIdx = 0;
      } else if (date[8] === "F" && date[9] === "e" && date[10] === "b") {
        monthIdx = 1;
      } else if (date[8] === "M" && date[9] === "a") {
        if (date[10] === "r") {
          monthIdx = 2;
        } else if (date[10] === "y") {
          monthIdx = 4;
        } else {
          return void 0;
        }
      } else if (date[8] === "J") {
        if (date[9] === "a" && date[10] === "n") {
          monthIdx = 0;
        } else if (date[9] === "u") {
          if (date[10] === "n") {
            monthIdx = 5;
          } else if (date[10] === "l") {
            monthIdx = 6;
          } else {
            return void 0;
          }
        } else {
          return void 0;
        }
      } else if (date[8] === "A") {
        if (date[9] === "p" && date[10] === "r") {
          monthIdx = 3;
        } else if (date[9] === "u" && date[10] === "g") {
          monthIdx = 7;
        } else {
          return void 0;
        }
      } else if (date[8] === "S" && date[9] === "e" && date[10] === "p") {
        monthIdx = 8;
      } else if (date[8] === "O" && date[9] === "c" && date[10] === "t") {
        monthIdx = 9;
      } else if (date[8] === "N" && date[9] === "o" && date[10] === "v") {
        monthIdx = 10;
      } else if (date[8] === "D" && date[9] === "e" && date[10] === "c") {
        monthIdx = 11;
      } else {
        return void 0;
      }
      const yearDigit1 = date.charCodeAt(12);
      if (yearDigit1 < 48 || yearDigit1 > 57) {
        return void 0;
      }
      const yearDigit2 = date.charCodeAt(13);
      if (yearDigit2 < 48 || yearDigit2 > 57) {
        return void 0;
      }
      const yearDigit3 = date.charCodeAt(14);
      if (yearDigit3 < 48 || yearDigit3 > 57) {
        return void 0;
      }
      const yearDigit4 = date.charCodeAt(15);
      if (yearDigit4 < 48 || yearDigit4 > 57) {
        return void 0;
      }
      const year = (yearDigit1 - 48) * 1e3 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48);
      let hour = 0;
      if (date[17] === "0") {
        const code = date.charCodeAt(18);
        if (code < 48 || code > 57) {
          return void 0;
        }
        hour = code - 48;
      } else {
        const code1 = date.charCodeAt(17);
        if (code1 < 48 || code1 > 50) {
          return void 0;
        }
        const code2 = date.charCodeAt(18);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        if (code1 === 50 && code2 > 51) {
          return void 0;
        }
        hour = (code1 - 48) * 10 + (code2 - 48);
      }
      let minute = 0;
      if (date[20] === "0") {
        const code = date.charCodeAt(21);
        if (code < 48 || code > 57) {
          return void 0;
        }
        minute = code - 48;
      } else {
        const code1 = date.charCodeAt(20);
        if (code1 < 48 || code1 > 53) {
          return void 0;
        }
        const code2 = date.charCodeAt(21);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        minute = (code1 - 48) * 10 + (code2 - 48);
      }
      let second = 0;
      if (date[23] === "0") {
        const code = date.charCodeAt(24);
        if (code < 48 || code > 57) {
          return void 0;
        }
        second = code - 48;
      } else {
        const code1 = date.charCodeAt(23);
        if (code1 < 48 || code1 > 53) {
          return void 0;
        }
        const code2 = date.charCodeAt(24);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        second = (code1 - 48) * 10 + (code2 - 48);
      }
      const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
      return result.getUTCDay() === weekday ? result : void 0;
    }
    function parseAscTimeDate(date) {
      if (date.length !== 24 || date[7] !== " " || date[10] !== " " || date[19] !== " ") {
        return void 0;
      }
      let weekday = -1;
      if (date[0] === "S" && date[1] === "u" && date[2] === "n") {
        weekday = 0;
      } else if (date[0] === "M" && date[1] === "o" && date[2] === "n") {
        weekday = 1;
      } else if (date[0] === "T" && date[1] === "u" && date[2] === "e") {
        weekday = 2;
      } else if (date[0] === "W" && date[1] === "e" && date[2] === "d") {
        weekday = 3;
      } else if (date[0] === "T" && date[1] === "h" && date[2] === "u") {
        weekday = 4;
      } else if (date[0] === "F" && date[1] === "r" && date[2] === "i") {
        weekday = 5;
      } else if (date[0] === "S" && date[1] === "a" && date[2] === "t") {
        weekday = 6;
      } else {
        return void 0;
      }
      let monthIdx = -1;
      if (date[4] === "J" && date[5] === "a" && date[6] === "n") {
        monthIdx = 0;
      } else if (date[4] === "F" && date[5] === "e" && date[6] === "b") {
        monthIdx = 1;
      } else if (date[4] === "M" && date[5] === "a") {
        if (date[6] === "r") {
          monthIdx = 2;
        } else if (date[6] === "y") {
          monthIdx = 4;
        } else {
          return void 0;
        }
      } else if (date[4] === "J") {
        if (date[5] === "a" && date[6] === "n") {
          monthIdx = 0;
        } else if (date[5] === "u") {
          if (date[6] === "n") {
            monthIdx = 5;
          } else if (date[6] === "l") {
            monthIdx = 6;
          } else {
            return void 0;
          }
        } else {
          return void 0;
        }
      } else if (date[4] === "A") {
        if (date[5] === "p" && date[6] === "r") {
          monthIdx = 3;
        } else if (date[5] === "u" && date[6] === "g") {
          monthIdx = 7;
        } else {
          return void 0;
        }
      } else if (date[4] === "S" && date[5] === "e" && date[6] === "p") {
        monthIdx = 8;
      } else if (date[4] === "O" && date[5] === "c" && date[6] === "t") {
        monthIdx = 9;
      } else if (date[4] === "N" && date[5] === "o" && date[6] === "v") {
        monthIdx = 10;
      } else if (date[4] === "D" && date[5] === "e" && date[6] === "c") {
        monthIdx = 11;
      } else {
        return void 0;
      }
      let day = 0;
      if (date[8] === " ") {
        const code = date.charCodeAt(9);
        if (code < 49 || code > 57) {
          return void 0;
        }
        day = code - 48;
      } else {
        const code1 = date.charCodeAt(8);
        if (code1 < 49 || code1 > 51) {
          return void 0;
        }
        const code2 = date.charCodeAt(9);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        day = (code1 - 48) * 10 + (code2 - 48);
      }
      let hour = 0;
      if (date[11] === "0") {
        const code = date.charCodeAt(12);
        if (code < 48 || code > 57) {
          return void 0;
        }
        hour = code - 48;
      } else {
        const code1 = date.charCodeAt(11);
        if (code1 < 48 || code1 > 50) {
          return void 0;
        }
        const code2 = date.charCodeAt(12);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        if (code1 === 50 && code2 > 51) {
          return void 0;
        }
        hour = (code1 - 48) * 10 + (code2 - 48);
      }
      let minute = 0;
      if (date[14] === "0") {
        const code = date.charCodeAt(15);
        if (code < 48 || code > 57) {
          return void 0;
        }
        minute = code - 48;
      } else {
        const code1 = date.charCodeAt(14);
        if (code1 < 48 || code1 > 53) {
          return void 0;
        }
        const code2 = date.charCodeAt(15);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        minute = (code1 - 48) * 10 + (code2 - 48);
      }
      let second = 0;
      if (date[17] === "0") {
        const code = date.charCodeAt(18);
        if (code < 48 || code > 57) {
          return void 0;
        }
        second = code - 48;
      } else {
        const code1 = date.charCodeAt(17);
        if (code1 < 48 || code1 > 53) {
          return void 0;
        }
        const code2 = date.charCodeAt(18);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        second = (code1 - 48) * 10 + (code2 - 48);
      }
      const yearDigit1 = date.charCodeAt(20);
      if (yearDigit1 < 48 || yearDigit1 > 57) {
        return void 0;
      }
      const yearDigit2 = date.charCodeAt(21);
      if (yearDigit2 < 48 || yearDigit2 > 57) {
        return void 0;
      }
      const yearDigit3 = date.charCodeAt(22);
      if (yearDigit3 < 48 || yearDigit3 > 57) {
        return void 0;
      }
      const yearDigit4 = date.charCodeAt(23);
      if (yearDigit4 < 48 || yearDigit4 > 57) {
        return void 0;
      }
      const year = (yearDigit1 - 48) * 1e3 + (yearDigit2 - 48) * 100 + (yearDigit3 - 48) * 10 + (yearDigit4 - 48);
      const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
      return result.getUTCDay() === weekday ? result : void 0;
    }
    function parseRfc850Date(date) {
      let commaIndex = -1;
      let weekday = -1;
      if (date[0] === "S") {
        if (date[1] === "u" && date[2] === "n" && date[3] === "d" && date[4] === "a" && date[5] === "y") {
          weekday = 0;
          commaIndex = 6;
        } else if (date[1] === "a" && date[2] === "t" && date[3] === "u" && date[4] === "r" && date[5] === "d" && date[6] === "a" && date[7] === "y") {
          weekday = 6;
          commaIndex = 8;
        }
      } else if (date[0] === "M" && date[1] === "o" && date[2] === "n" && date[3] === "d" && date[4] === "a" && date[5] === "y") {
        weekday = 1;
        commaIndex = 6;
      } else if (date[0] === "T") {
        if (date[1] === "u" && date[2] === "e" && date[3] === "s" && date[4] === "d" && date[5] === "a" && date[6] === "y") {
          weekday = 2;
          commaIndex = 7;
        } else if (date[1] === "h" && date[2] === "u" && date[3] === "r" && date[4] === "s" && date[5] === "d" && date[6] === "a" && date[7] === "y") {
          weekday = 4;
          commaIndex = 8;
        }
      } else if (date[0] === "W" && date[1] === "e" && date[2] === "d" && date[3] === "n" && date[4] === "e" && date[5] === "s" && date[6] === "d" && date[7] === "a" && date[8] === "y") {
        weekday = 3;
        commaIndex = 9;
      } else if (date[0] === "F" && date[1] === "r" && date[2] === "i" && date[3] === "d" && date[4] === "a" && date[5] === "y") {
        weekday = 5;
        commaIndex = 6;
      } else {
        return void 0;
      }
      if (date[commaIndex] !== "," || date.length - commaIndex - 1 !== 23 || date[commaIndex + 1] !== " " || date[commaIndex + 4] !== "-" || date[commaIndex + 8] !== "-" || date[commaIndex + 11] !== " " || date[commaIndex + 14] !== ":" || date[commaIndex + 17] !== ":" || date[commaIndex + 20] !== " " || date[commaIndex + 21] !== "G" || date[commaIndex + 22] !== "M" || date[commaIndex + 23] !== "T") {
        return void 0;
      }
      let day = 0;
      if (date[commaIndex + 2] === "0") {
        const code = date.charCodeAt(commaIndex + 3);
        if (code < 49 || code > 57) {
          return void 0;
        }
        day = code - 48;
      } else {
        const code1 = date.charCodeAt(commaIndex + 2);
        if (code1 < 49 || code1 > 51) {
          return void 0;
        }
        const code2 = date.charCodeAt(commaIndex + 3);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        day = (code1 - 48) * 10 + (code2 - 48);
      }
      let monthIdx = -1;
      if (date[commaIndex + 5] === "J" && date[commaIndex + 6] === "a" && date[commaIndex + 7] === "n") {
        monthIdx = 0;
      } else if (date[commaIndex + 5] === "F" && date[commaIndex + 6] === "e" && date[commaIndex + 7] === "b") {
        monthIdx = 1;
      } else if (date[commaIndex + 5] === "M" && date[commaIndex + 6] === "a" && date[commaIndex + 7] === "r") {
        monthIdx = 2;
      } else if (date[commaIndex + 5] === "A" && date[commaIndex + 6] === "p" && date[commaIndex + 7] === "r") {
        monthIdx = 3;
      } else if (date[commaIndex + 5] === "M" && date[commaIndex + 6] === "a" && date[commaIndex + 7] === "y") {
        monthIdx = 4;
      } else if (date[commaIndex + 5] === "J" && date[commaIndex + 6] === "u" && date[commaIndex + 7] === "n") {
        monthIdx = 5;
      } else if (date[commaIndex + 5] === "J" && date[commaIndex + 6] === "u" && date[commaIndex + 7] === "l") {
        monthIdx = 6;
      } else if (date[commaIndex + 5] === "A" && date[commaIndex + 6] === "u" && date[commaIndex + 7] === "g") {
        monthIdx = 7;
      } else if (date[commaIndex + 5] === "S" && date[commaIndex + 6] === "e" && date[commaIndex + 7] === "p") {
        monthIdx = 8;
      } else if (date[commaIndex + 5] === "O" && date[commaIndex + 6] === "c" && date[commaIndex + 7] === "t") {
        monthIdx = 9;
      } else if (date[commaIndex + 5] === "N" && date[commaIndex + 6] === "o" && date[commaIndex + 7] === "v") {
        monthIdx = 10;
      } else if (date[commaIndex + 5] === "D" && date[commaIndex + 6] === "e" && date[commaIndex + 7] === "c") {
        monthIdx = 11;
      } else {
        return void 0;
      }
      const yearDigit1 = date.charCodeAt(commaIndex + 9);
      if (yearDigit1 < 48 || yearDigit1 > 57) {
        return void 0;
      }
      const yearDigit2 = date.charCodeAt(commaIndex + 10);
      if (yearDigit2 < 48 || yearDigit2 > 57) {
        return void 0;
      }
      let year = (yearDigit1 - 48) * 10 + (yearDigit2 - 48);
      year += year < 70 ? 2e3 : 1900;
      let hour = 0;
      if (date[commaIndex + 12] === "0") {
        const code = date.charCodeAt(commaIndex + 13);
        if (code < 48 || code > 57) {
          return void 0;
        }
        hour = code - 48;
      } else {
        const code1 = date.charCodeAt(commaIndex + 12);
        if (code1 < 48 || code1 > 50) {
          return void 0;
        }
        const code2 = date.charCodeAt(commaIndex + 13);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        if (code1 === 50 && code2 > 51) {
          return void 0;
        }
        hour = (code1 - 48) * 10 + (code2 - 48);
      }
      let minute = 0;
      if (date[commaIndex + 15] === "0") {
        const code = date.charCodeAt(commaIndex + 16);
        if (code < 48 || code > 57) {
          return void 0;
        }
        minute = code - 48;
      } else {
        const code1 = date.charCodeAt(commaIndex + 15);
        if (code1 < 48 || code1 > 53) {
          return void 0;
        }
        const code2 = date.charCodeAt(commaIndex + 16);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        minute = (code1 - 48) * 10 + (code2 - 48);
      }
      let second = 0;
      if (date[commaIndex + 18] === "0") {
        const code = date.charCodeAt(commaIndex + 19);
        if (code < 48 || code > 57) {
          return void 0;
        }
        second = code - 48;
      } else {
        const code1 = date.charCodeAt(commaIndex + 18);
        if (code1 < 48 || code1 > 53) {
          return void 0;
        }
        const code2 = date.charCodeAt(commaIndex + 19);
        if (code2 < 48 || code2 > 57) {
          return void 0;
        }
        second = (code1 - 48) * 10 + (code2 - 48);
      }
      const result = new Date(Date.UTC(year, monthIdx, day, hour, minute, second));
      return result.getUTCDay() === weekday ? result : void 0;
    }
    module.exports = {
      parseHttpDate
    };
  }
});

// node_modules/undici/lib/handler/cache-handler.js
var require_cache_handler = __commonJS({
  "node_modules/undici/lib/handler/cache-handler.js"(exports, module) {
    "use strict";
    var util2 = require_util();
    var {
      parseCacheControlHeader,
      parseVaryHeader,
      isEtagUsable
    } = require_cache();
    var { parseHttpDate } = require_date();
    function noop() {
    }
    var HEURISTICALLY_CACHEABLE_STATUS_CODES = [
      200,
      203,
      204,
      206,
      300,
      301,
      308,
      404,
      405,
      410,
      414,
      501
    ];
    var NOT_UNDERSTOOD_STATUS_CODES = [
      206
    ];
    var MAX_RESPONSE_AGE = 2147483647e3;
    var CacheHandler = class {
      /**
       * @type {import('../../types/cache-interceptor.d.ts').default.CacheKey}
       */
      #cacheKey;
      /**
       * @type {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions['type']}
       */
      #cacheType;
      /**
       * @type {number | undefined}
       */
      #cacheByDefault;
      /**
       * @type {import('../../types/cache-interceptor.d.ts').default.CacheStore}
       */
      #store;
      /**
       * @type {import('../../types/dispatcher.d.ts').default.DispatchHandler}
       */
      #handler;
      /**
       * @type {import('node:stream').Writable | undefined}
       */
      #writeStream;
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheHandlerOptions} opts
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey
       * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler
       */
      constructor({ store, type, cacheByDefault }, cacheKey2, handler) {
        this.#store = store;
        this.#cacheType = type;
        this.#cacheByDefault = cacheByDefault;
        this.#cacheKey = cacheKey2;
        this.#handler = handler;
      }
      onRequestStart(controller, context) {
        this.#writeStream?.destroy();
        this.#writeStream = void 0;
        this.#handler.onRequestStart?.(controller, context);
      }
      onRequestUpgrade(controller, statusCode, headers, socket) {
        this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
      }
      /**
       * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
       * @param {number} statusCode
       * @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders
       * @param {string} statusMessage
       */
      onResponseStart(controller, statusCode, resHeaders, statusMessage) {
        const downstreamOnHeaders = () => this.#handler.onResponseStart?.(
          controller,
          statusCode,
          resHeaders,
          statusMessage
        );
        const handler = this;
        if (!util2.safeHTTPMethods.includes(this.#cacheKey.method) && statusCode >= 200 && statusCode <= 399) {
          try {
            this.#store.delete(this.#cacheKey)?.catch?.(noop);
          } catch {
          }
          return downstreamOnHeaders();
        }
        const cacheControlHeader = resHeaders["cache-control"];
        const heuristicallyCacheable = resHeaders["last-modified"] && HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode);
        if (!cacheControlHeader && !resHeaders["expires"] && !heuristicallyCacheable && !this.#cacheByDefault) {
          return downstreamOnHeaders();
        }
        const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {};
        if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
          return downstreamOnHeaders();
        }
        const now = Date.now();
        const resAge = resHeaders.age ? getAge(resHeaders.age) : void 0;
        if (resAge && resAge >= MAX_RESPONSE_AGE) {
          return downstreamOnHeaders();
        }
        const resDate = typeof resHeaders.date === "string" ? parseHttpDate(resHeaders.date) : void 0;
        const staleAt = determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives) ?? this.#cacheByDefault;
        if (staleAt === void 0 || resAge && resAge > staleAt) {
          return downstreamOnHeaders();
        }
        const baseTime = resDate ? resDate.getTime() : now;
        const absoluteStaleAt = staleAt + baseTime;
        if (now >= absoluteStaleAt) {
          return downstreamOnHeaders();
        }
        let varyDirectives;
        if (this.#cacheKey.headers && resHeaders.vary) {
          varyDirectives = parseVaryHeader(resHeaders.vary, this.#cacheKey.headers);
          if (!varyDirectives) {
            return downstreamOnHeaders();
          }
        }
        const cachedAt = resAge ? now - resAge : now;
        const deleteAt = determineDeleteAt(baseTime, cachedAt, cacheControlDirectives, absoluteStaleAt);
        const strippedHeaders = stripNecessaryHeaders(resHeaders, cacheControlDirectives);
        const value = {
          statusCode,
          statusMessage,
          headers: strippedHeaders,
          vary: varyDirectives,
          cacheControlDirectives,
          cachedAt,
          staleAt: absoluteStaleAt,
          deleteAt
        };
        if (statusCode === 304) {
          const handle304 = (cachedValue) => {
            if (!cachedValue) {
              return downstreamOnHeaders();
            }
            value.statusCode = cachedValue.statusCode;
            value.statusMessage = cachedValue.statusMessage;
            value.etag = cachedValue.etag;
            value.headers = { ...cachedValue.headers, ...strippedHeaders };
            downstreamOnHeaders();
            this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value);
            if (!this.#writeStream || !cachedValue?.body) {
              return;
            }
            if (typeof cachedValue.body.values === "function") {
              const bodyIterator = cachedValue.body.values();
              const streamCachedBody = () => {
                for (const chunk of bodyIterator) {
                  const full = this.#writeStream.write(chunk) === false;
                  this.#handler.onResponseData?.(controller, chunk);
                  if (full) {
                    break;
                  }
                }
              };
              this.#writeStream.on("error", function() {
                handler.#writeStream = void 0;
                handler.#store.delete(handler.#cacheKey);
              }).on("drain", () => {
                streamCachedBody();
              }).on("close", function() {
                if (handler.#writeStream === this) {
                  handler.#writeStream = void 0;
                }
              });
              streamCachedBody();
            } else if (typeof cachedValue.body.on === "function") {
              cachedValue.body.on("data", (chunk) => {
                this.#writeStream.write(chunk);
                this.#handler.onResponseData?.(controller, chunk);
              }).on("end", () => {
                this.#writeStream.end();
              }).on("error", () => {
                this.#writeStream = void 0;
                this.#store.delete(this.#cacheKey);
              });
              this.#writeStream.on("error", function() {
                handler.#writeStream = void 0;
                handler.#store.delete(handler.#cacheKey);
              }).on("close", function() {
                if (handler.#writeStream === this) {
                  handler.#writeStream = void 0;
                }
              });
            }
          };
          const result = this.#store.get(this.#cacheKey);
          if (result && typeof result.then === "function") {
            result.then(handle304);
          } else {
            handle304(result);
          }
        } else {
          if (typeof resHeaders.etag === "string" && isEtagUsable(resHeaders.etag)) {
            value.etag = resHeaders.etag;
          }
          this.#writeStream = this.#store.createWriteStream(this.#cacheKey, value);
          if (!this.#writeStream) {
            return downstreamOnHeaders();
          }
          this.#writeStream.on("drain", () => controller.resume()).on("error", function() {
            handler.#writeStream = void 0;
            handler.#store.delete(handler.#cacheKey);
          }).on("close", function() {
            if (handler.#writeStream === this) {
              handler.#writeStream = void 0;
            }
            controller.resume();
          });
          downstreamOnHeaders();
        }
      }
      onResponseData(controller, chunk) {
        if (this.#writeStream?.write(chunk) === false) {
          controller.pause();
        }
        this.#handler.onResponseData?.(controller, chunk);
      }
      onResponseEnd(controller, trailers) {
        this.#writeStream?.end();
        this.#handler.onResponseEnd?.(controller, trailers);
      }
      onResponseError(controller, err) {
        this.#writeStream?.destroy(err);
        this.#writeStream = void 0;
        this.#handler.onResponseError?.(controller, err);
      }
    };
    function canCacheResponse(cacheType, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
      if (statusCode < 200 || NOT_UNDERSTOOD_STATUS_CODES.includes(statusCode)) {
        return false;
      }
      if (!HEURISTICALLY_CACHEABLE_STATUS_CODES.includes(statusCode) && !resHeaders["expires"] && !cacheControlDirectives.public && cacheControlDirectives["max-age"] === void 0 && // RFC 9111: a private response directive, if the cache is not shared
      !(cacheControlDirectives.private && cacheType === "private") && !(cacheControlDirectives["s-maxage"] !== void 0 && cacheType === "shared")) {
        return false;
      }
      if (cacheControlDirectives["no-store"]) {
        return false;
      }
      if (cacheType === "shared" && cacheControlDirectives.private === true) {
        return false;
      }
      if (resHeaders.vary?.includes("*")) {
        return false;
      }
      if (reqHeaders?.authorization) {
        if (!cacheControlDirectives.public && !cacheControlDirectives["s-maxage"] && !cacheControlDirectives["must-revalidate"]) {
          return false;
        }
        if (typeof reqHeaders.authorization !== "string") {
          return false;
        }
        if (Array.isArray(cacheControlDirectives["no-cache"]) && cacheControlDirectives["no-cache"].includes("authorization")) {
          return false;
        }
        if (Array.isArray(cacheControlDirectives["private"]) && cacheControlDirectives["private"].includes("authorization")) {
          return false;
        }
      }
      return true;
    }
    function getAge(ageHeader) {
      const age = parseInt(Array.isArray(ageHeader) ? ageHeader[0] : ageHeader);
      return isNaN(age) ? void 0 : age * 1e3;
    }
    function determineStaleAt(cacheType, now, age, resHeaders, responseDate, cacheControlDirectives) {
      if (cacheType === "shared") {
        const sMaxAge = cacheControlDirectives["s-maxage"];
        if (sMaxAge !== void 0) {
          return sMaxAge > 0 ? sMaxAge * 1e3 : void 0;
        }
      }
      const maxAge = cacheControlDirectives["max-age"];
      if (maxAge !== void 0) {
        return maxAge > 0 ? maxAge * 1e3 : void 0;
      }
      if (typeof resHeaders.expires === "string") {
        const expiresDate = parseHttpDate(resHeaders.expires);
        if (expiresDate) {
          if (now >= expiresDate.getTime()) {
            return void 0;
          }
          if (responseDate) {
            if (responseDate >= expiresDate) {
              return void 0;
            }
            if (age !== void 0 && age > expiresDate - responseDate) {
              return void 0;
            }
          }
          return expiresDate.getTime() - now;
        }
      }
      if (typeof resHeaders["last-modified"] === "string") {
        const lastModified = new Date(resHeaders["last-modified"]);
        if (isValidDate(lastModified)) {
          if (lastModified.getTime() >= now) {
            return void 0;
          }
          const responseAge = now - lastModified.getTime();
          return responseAge * 0.1;
        }
      }
      if (cacheControlDirectives.immutable) {
        return 31536e6;
      }
      return void 0;
    }
    function determineDeleteAt(baseTime, cachedAt, cacheControlDirectives, staleAt) {
      let staleWhileRevalidate = -Infinity;
      let staleIfError = -Infinity;
      let immutable = -Infinity;
      if (cacheControlDirectives["stale-while-revalidate"]) {
        staleWhileRevalidate = staleAt + cacheControlDirectives["stale-while-revalidate"] * 1e3;
      }
      if (cacheControlDirectives["stale-if-error"]) {
        staleIfError = staleAt + cacheControlDirectives["stale-if-error"] * 1e3;
      }
      if (cacheControlDirectives.immutable && staleWhileRevalidate === -Infinity && staleIfError === -Infinity) {
        immutable = cachedAt + 31536e6;
      }
      if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity && immutable === -Infinity) {
        const freshnessLifetime = staleAt - baseTime;
        const datePrecisionPadding = Math.min(Math.max(cachedAt - baseTime, 0), 1e3);
        return staleAt + freshnessLifetime + datePrecisionPadding;
      }
      return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable);
    }
    function stripNecessaryHeaders(resHeaders, cacheControlDirectives) {
      const headersToRemove = [
        "connection",
        "proxy-authenticate",
        "proxy-authentication-info",
        "proxy-authorization",
        "proxy-connection",
        "te",
        "transfer-encoding",
        "upgrade",
        // We'll add age back when serving it
        "age"
      ];
      if (resHeaders["connection"]) {
        if (Array.isArray(resHeaders["connection"])) {
          headersToRemove.push(...resHeaders["connection"].map((header) => header.trim()));
        } else {
          headersToRemove.push(...resHeaders["connection"].split(",").map((header) => header.trim()));
        }
      }
      if (Array.isArray(cacheControlDirectives["no-cache"])) {
        headersToRemove.push(...cacheControlDirectives["no-cache"]);
      }
      if (Array.isArray(cacheControlDirectives["private"])) {
        headersToRemove.push(...cacheControlDirectives["private"]);
      }
      let strippedHeaders;
      for (const headerName of headersToRemove) {
        if (resHeaders[headerName]) {
          strippedHeaders ??= { ...resHeaders };
          delete strippedHeaders[headerName];
        }
      }
      return strippedHeaders ?? resHeaders;
    }
    function isValidDate(date) {
      return date instanceof Date && Number.isFinite(date.valueOf());
    }
    module.exports = CacheHandler;
  }
});

// node_modules/undici/lib/cache/memory-cache-store.js
var require_memory_cache_store = __commonJS({
  "node_modules/undici/lib/cache/memory-cache-store.js"(exports, module) {
    "use strict";
    var { Writable } = __require("stream");
    var { EventEmitter } = __require("events");
    var { assertCacheKey, assertCacheValue } = require_cache();
    var MemoryCacheStore = class extends EventEmitter {
      #maxCount = 1024;
      #maxSize = 104857600;
      // 100MB
      #maxEntrySize = 5242880;
      // 5MB
      #size = 0;
      #count = 0;
      #entries = /* @__PURE__ */ new Map();
      #hasEmittedMaxSizeEvent = false;
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.MemoryCacheStoreOpts | undefined} [opts]
       */
      constructor(opts) {
        super();
        if (opts) {
          if (typeof opts !== "object") {
            throw new TypeError("MemoryCacheStore options must be an object");
          }
          if (opts.maxCount !== void 0) {
            if (typeof opts.maxCount !== "number" || !Number.isInteger(opts.maxCount) || opts.maxCount < 0) {
              throw new TypeError("MemoryCacheStore options.maxCount must be a non-negative integer");
            }
            this.#maxCount = opts.maxCount;
          }
          if (opts.maxSize !== void 0) {
            if (typeof opts.maxSize !== "number" || !Number.isInteger(opts.maxSize) || opts.maxSize < 0) {
              throw new TypeError("MemoryCacheStore options.maxSize must be a non-negative integer");
            }
            this.#maxSize = opts.maxSize;
          }
          if (opts.maxEntrySize !== void 0) {
            if (typeof opts.maxEntrySize !== "number" || !Number.isInteger(opts.maxEntrySize) || opts.maxEntrySize < 0) {
              throw new TypeError("MemoryCacheStore options.maxEntrySize must be a non-negative integer");
            }
            this.#maxEntrySize = opts.maxEntrySize;
          }
        }
      }
      /**
       * Get the current size of the cache in bytes
       * @returns {number} The current size of the cache in bytes
       */
      get size() {
        return this.#size;
      }
      /**
       * Check if the cache is full (either max size or max count reached)
       * @returns {boolean} True if the cache is full, false otherwise
       */
      isFull() {
        return this.#size >= this.#maxSize || this.#count >= this.#maxCount;
      }
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} req
       * @returns {import('../../types/cache-interceptor.d.ts').default.GetResult | undefined}
       */
      get(key) {
        assertCacheKey(key);
        const topLevelKey = `${key.origin}:${key.path}`;
        const now = Date.now();
        const entries = this.#entries.get(topLevelKey);
        const entry = entries ? findEntry(key, entries, now) : null;
        return entry == null ? void 0 : {
          statusMessage: entry.statusMessage,
          statusCode: entry.statusCode,
          headers: entry.headers,
          body: entry.body,
          vary: entry.vary ? entry.vary : void 0,
          etag: entry.etag,
          cacheControlDirectives: entry.cacheControlDirectives,
          cachedAt: entry.cachedAt,
          staleAt: entry.staleAt,
          deleteAt: entry.deleteAt
        };
      }
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} val
       * @returns {Writable | undefined}
       */
      createWriteStream(key, val) {
        assertCacheKey(key);
        assertCacheValue(val);
        const topLevelKey = `${key.origin}:${key.path}`;
        const store = this;
        const entry = { ...key, ...val, body: [], size: 0 };
        return new Writable({
          write(chunk, encoding, callback) {
            if (typeof chunk === "string") {
              chunk = Buffer.from(chunk, encoding);
            }
            entry.size += chunk.byteLength;
            if (entry.size > store.#maxEntrySize) {
              this.destroy();
            } else {
              entry.body.push(chunk);
            }
            callback(null);
          },
          final(callback) {
            let entries = store.#entries.get(topLevelKey);
            if (!entries) {
              entries = [];
              store.#entries.set(topLevelKey, entries);
            }
            const previousEntry = findEntry(key, entries, Date.now());
            if (previousEntry) {
              const index2 = entries.indexOf(previousEntry);
              entries.splice(index2, 1, entry);
              store.#size -= previousEntry.size;
            } else {
              entries.push(entry);
              store.#count += 1;
            }
            store.#size += entry.size;
            if (store.#size > store.#maxSize || store.#count > store.#maxCount) {
              if (!store.#hasEmittedMaxSizeEvent) {
                store.emit("maxSizeExceeded", {
                  size: store.#size,
                  maxSize: store.#maxSize,
                  count: store.#count,
                  maxCount: store.#maxCount
                });
                store.#hasEmittedMaxSizeEvent = true;
              }
              for (const [key2, entries2] of store.#entries) {
                for (const entry2 of entries2.splice(0, entries2.length / 2)) {
                  store.#size -= entry2.size;
                  store.#count -= 1;
                }
                if (entries2.length === 0) {
                  store.#entries.delete(key2);
                }
              }
              if (store.#size < store.#maxSize && store.#count < store.#maxCount) {
                store.#hasEmittedMaxSizeEvent = false;
              }
            }
            callback(null);
          }
        });
      }
      /**
       * @param {CacheKey} key
       */
      delete(key) {
        if (typeof key !== "object") {
          throw new TypeError(`expected key to be object, got ${typeof key}`);
        }
        const topLevelKey = `${key.origin}:${key.path}`;
        for (const entry of this.#entries.get(topLevelKey) ?? []) {
          this.#size -= entry.size;
          this.#count -= 1;
        }
        this.#entries.delete(topLevelKey);
      }
    };
    function findEntry(key, entries, now) {
      return entries.find((entry) => entry.deleteAt > now && entry.method === key.method && (entry.vary == null || Object.keys(entry.vary).every((headerName) => {
        if (entry.vary[headerName] === null) {
          return key.headers[headerName] === void 0;
        }
        return entry.vary[headerName] === key.headers[headerName];
      })));
    }
    module.exports = MemoryCacheStore;
  }
});

// node_modules/undici/lib/handler/cache-revalidation-handler.js
var require_cache_revalidation_handler = __commonJS({
  "node_modules/undici/lib/handler/cache-revalidation-handler.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var CacheRevalidationHandler = class {
      #successful = false;
      /**
       * @type {((boolean, any) => void) | null}
       */
      #callback;
      /**
       * @type {(import('../../types/dispatcher.d.ts').default.DispatchHandler)}
       */
      #handler;
      #context;
      /**
       * @type {boolean}
       */
      #allowErrorStatusCodes;
      /**
       * @param {(boolean) => void} callback Function to call if the cached value is valid
       * @param {import('../../types/dispatcher.d.ts').default.DispatchHandlers} handler
       * @param {boolean} allowErrorStatusCodes
       */
      constructor(callback, handler, allowErrorStatusCodes) {
        if (typeof callback !== "function") {
          throw new TypeError("callback must be a function");
        }
        this.#callback = callback;
        this.#handler = handler;
        this.#allowErrorStatusCodes = allowErrorStatusCodes;
      }
      onRequestStart(_, context) {
        this.#successful = false;
        this.#context = context;
      }
      onRequestUpgrade(controller, statusCode, headers, socket) {
        this.#handler.onRequestUpgrade?.(controller, statusCode, headers, socket);
      }
      onResponseStart(controller, statusCode, headers, statusMessage) {
        assert8(this.#callback != null);
        this.#successful = statusCode === 304 || this.#allowErrorStatusCodes && statusCode >= 500 && statusCode <= 504;
        this.#callback(this.#successful, this.#context);
        this.#callback = null;
        if (this.#successful) {
          return true;
        }
        this.#handler.onRequestStart?.(controller, this.#context);
        this.#handler.onResponseStart?.(
          controller,
          statusCode,
          headers,
          statusMessage
        );
      }
      onResponseData(controller, chunk) {
        if (this.#successful) {
          return;
        }
        return this.#handler.onResponseData?.(controller, chunk);
      }
      onResponseEnd(controller, trailers) {
        if (this.#successful) {
          return;
        }
        this.#handler.onResponseEnd?.(controller, trailers);
      }
      onResponseError(controller, err) {
        if (this.#successful) {
          return;
        }
        if (this.#callback) {
          this.#callback(false);
          this.#callback = null;
        }
        if (typeof this.#handler.onResponseError === "function") {
          this.#handler.onResponseError(controller, err);
        } else {
          throw err;
        }
      }
    };
    module.exports = CacheRevalidationHandler;
  }
});

// node_modules/undici/lib/interceptor/cache.js
var require_cache2 = __commonJS({
  "node_modules/undici/lib/interceptor/cache.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var { Readable } = __require("stream");
    var util2 = require_util();
    var CacheHandler = require_cache_handler();
    var MemoryCacheStore = require_memory_cache_store();
    var CacheRevalidationHandler = require_cache_revalidation_handler();
    var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders: normalizeHeaders3, parseCacheControlHeader } = require_cache();
    var { AbortError } = require_errors();
    function assertCacheOrigins(origins, name) {
      if (origins === void 0) return;
      if (!Array.isArray(origins)) {
        throw new TypeError(`expected ${name} to be an array or undefined, got ${typeof origins}`);
      }
      for (let i = 0; i < origins.length; i++) {
        const origin = origins[i];
        if (typeof origin !== "string" && !(origin instanceof RegExp)) {
          throw new TypeError(`expected ${name}[${i}] to be a string or RegExp, got ${typeof origin}`);
        }
      }
    }
    var nop = () => {
    };
    function needsRevalidation(result, cacheControlDirectives, { headers = {} }) {
      if (cacheControlDirectives?.["no-cache"]) {
        return true;
      }
      if (result.cacheControlDirectives?.["no-cache"] && !Array.isArray(result.cacheControlDirectives["no-cache"])) {
        return true;
      }
      if (headers["if-modified-since"] || headers["if-none-match"]) {
        return true;
      }
      return false;
    }
    function isStale(result, cacheControlDirectives) {
      const now = Date.now();
      if (now > result.staleAt) {
        if (cacheControlDirectives?.["max-stale"]) {
          const gracePeriod = result.staleAt + cacheControlDirectives["max-stale"] * 1e3;
          return now > gracePeriod;
        }
        return true;
      }
      if (cacheControlDirectives?.["min-fresh"]) {
        const timeLeftTillStale = result.staleAt - now;
        const threshold = cacheControlDirectives["min-fresh"] * 1e3;
        return timeLeftTillStale <= threshold;
      }
      return false;
    }
    function withinStaleWhileRevalidateWindow(result) {
      const staleWhileRevalidate = result.cacheControlDirectives?.["stale-while-revalidate"];
      if (!staleWhileRevalidate) {
        return false;
      }
      const now = Date.now();
      const staleWhileRevalidateExpiry = result.staleAt + staleWhileRevalidate * 1e3;
      return now <= staleWhileRevalidateExpiry;
    }
    function handleUncachedResponse(dispatch, globalOpts, cacheKey2, handler, opts, reqCacheControl) {
      if (reqCacheControl?.["only-if-cached"]) {
        let aborted = false;
        const controller = {
          paused: false,
          rawHeaders: [],
          rawTrailers: [],
          pause() {
            this.paused = true;
          },
          resume() {
            this.paused = false;
          },
          abort: (reason) => {
            aborted = true;
            handler.onResponseError?.(controller, reason ?? new AbortError());
          }
        };
        try {
          handler.onRequestStart?.(controller, null);
          if (aborted) {
            return;
          }
          handler.onResponseStart?.(controller, 504, {}, "Gateway Timeout");
          if (aborted) {
            return;
          }
          handler.onResponseEnd?.(controller, {});
        } catch (err) {
          if (typeof handler.onResponseError === "function") {
            handler.onResponseError(controller, err);
          }
        }
        return true;
      }
      return dispatch(opts, new CacheHandler(globalOpts, cacheKey2, handler));
    }
    function sendCachedValue(handler, opts, result, age, context, isStale2) {
      const stream = util2.isStream(result.body) ? result.body : Readable.from(result.body ?? []);
      assert8(!stream.destroyed, "stream should not be destroyed");
      assert8(!stream.readableDidRead, "stream should not be readableDidRead");
      const controller = {
        rawHeaders: [],
        rawTrailers: [],
        resume() {
          stream.resume();
        },
        pause() {
          stream.pause();
        },
        get paused() {
          return stream.isPaused();
        },
        get aborted() {
          return stream.destroyed;
        },
        get reason() {
          return stream.errored;
        },
        abort(reason) {
          stream.destroy(reason ?? new AbortError());
        }
      };
      stream.on("error", function(err) {
        if (!this.readableEnded) {
          if (typeof handler.onResponseError === "function") {
            handler.onResponseError(controller, err);
          } else {
            throw err;
          }
        }
      }).on("close", function() {
        if (!this.errored) {
          handler.onResponseEnd?.(controller, {});
        }
      });
      handler.onRequestStart?.(controller, context);
      if (stream.destroyed) {
        return;
      }
      const headers = { ...result.headers, age: String(age) };
      if (isStale2) {
        headers.warning = '110 - "response is stale"';
      }
      controller.rawHeaders = util2.toRawHeaders(headers);
      handler.onResponseStart?.(controller, result.statusCode, headers, result.statusMessage);
      if (opts.method === "HEAD") {
        stream.destroy();
      } else {
        stream.on("data", function(chunk) {
          handler.onResponseData?.(controller, chunk);
        });
      }
    }
    function handleResult2(dispatch, globalOpts, cacheKey2, handler, opts, reqCacheControl, result) {
      if (!result) {
        return handleUncachedResponse(dispatch, globalOpts, cacheKey2, handler, opts, reqCacheControl);
      }
      const now = Date.now();
      if (now > result.deleteAt) {
        return dispatch(opts, new CacheHandler(globalOpts, cacheKey2, handler));
      }
      const age = Math.round((now - result.cachedAt) / 1e3);
      if (reqCacheControl?.["max-age"] && age >= reqCacheControl["max-age"]) {
        return dispatch(opts, handler);
      }
      const stale = isStale(result, reqCacheControl);
      const revalidate = needsRevalidation(result, reqCacheControl, opts);
      if (stale || revalidate) {
        if (util2.isStream(opts.body) && util2.bodyLength(opts.body) !== 0) {
          return dispatch(opts, new CacheHandler(globalOpts, cacheKey2, handler));
        }
        if (!revalidate && withinStaleWhileRevalidateWindow(result)) {
          sendCachedValue(handler, opts, result, age, null, true);
          queueMicrotask(() => {
            const headers2 = {
              ...opts.headers,
              "if-modified-since": new Date(result.cachedAt).toUTCString()
            };
            if (result.etag) {
              headers2["if-none-match"] = result.etag;
            }
            if (result.vary) {
              for (const key in result.vary) {
                if (result.vary[key] != null) {
                  headers2[key] = result.vary[key];
                }
              }
            }
            dispatch(
              {
                ...opts,
                headers: headers2
              },
              new CacheHandler(globalOpts, cacheKey2, {
                // Silent handler that just updates the cache
                onRequestStart() {
                },
                onRequestUpgrade() {
                },
                onResponseStart() {
                },
                onResponseData() {
                },
                onResponseEnd() {
                },
                onResponseError() {
                }
              })
            );
          });
          return true;
        }
        let withinStaleIfErrorThreshold = false;
        const staleIfErrorExpiry = result.cacheControlDirectives["stale-if-error"] ?? reqCacheControl?.["stale-if-error"];
        if (staleIfErrorExpiry) {
          withinStaleIfErrorThreshold = now < result.staleAt + staleIfErrorExpiry * 1e3;
        }
        const headers = {
          ...opts.headers,
          "if-modified-since": new Date(result.cachedAt).toUTCString()
        };
        if (result.etag) {
          headers["if-none-match"] = result.etag;
        }
        if (result.vary) {
          for (const key in result.vary) {
            if (result.vary[key] != null) {
              headers[key] = result.vary[key];
            }
          }
        }
        return dispatch(
          {
            ...opts,
            headers
          },
          new CacheRevalidationHandler(
            (success, context) => {
              if (success) {
                sendCachedValue(handler, opts, result, age, context, stale);
              } else if (util2.isStream(result.body)) {
                result.body.on("error", nop).destroy();
              }
            },
            new CacheHandler(globalOpts, cacheKey2, handler),
            withinStaleIfErrorThreshold
          )
        );
      }
      if (util2.isStream(opts.body)) {
        opts.body.on("error", nop).destroy();
      }
      sendCachedValue(handler, opts, result, age, null, false);
    }
    module.exports = (opts = {}) => {
      const {
        store = new MemoryCacheStore(),
        methods = ["GET"],
        cacheByDefault = void 0,
        type = "shared",
        origins = void 0
      } = opts;
      if (typeof opts !== "object" || opts === null) {
        throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? "null" : typeof opts}`);
      }
      assertCacheStore(store, "opts.store");
      assertCacheMethods(methods, "opts.methods");
      assertCacheOrigins(origins, "opts.origins");
      if (typeof cacheByDefault !== "undefined" && typeof cacheByDefault !== "number") {
        throw new TypeError(`expected opts.cacheByDefault to be number or undefined, got ${typeof cacheByDefault}`);
      }
      if (typeof type !== "undefined" && type !== "shared" && type !== "private") {
        throw new TypeError(`expected opts.type to be shared, private, or undefined, got ${typeof type}`);
      }
      const globalOpts = {
        store,
        methods,
        cacheByDefault,
        type
      };
      const safeMethodsToNotCache = util2.safeHTTPMethods.filter((method) => methods.includes(method) === false);
      return (dispatch) => {
        return (opts2, handler) => {
          if (!opts2.origin || safeMethodsToNotCache.includes(opts2.method)) {
            return dispatch(opts2, handler);
          }
          if (origins !== void 0) {
            const requestOrigin = opts2.origin.toString().toLowerCase();
            let isAllowed = false;
            for (let i = 0; i < origins.length; i++) {
              const allowed = origins[i];
              if (typeof allowed === "string") {
                if (allowed.toLowerCase() === requestOrigin) {
                  isAllowed = true;
                  break;
                }
              } else if (allowed.test(requestOrigin)) {
                isAllowed = true;
                break;
              }
            }
            if (!isAllowed) {
              return dispatch(opts2, handler);
            }
          }
          opts2 = {
            ...opts2,
            headers: normalizeHeaders3(opts2)
          };
          const reqCacheControl = opts2.headers?.["cache-control"] ? parseCacheControlHeader(opts2.headers["cache-control"]) : void 0;
          if (reqCacheControl?.["no-store"]) {
            return dispatch(opts2, handler);
          }
          const cacheKey2 = makeCacheKey(opts2);
          const result = store.get(cacheKey2);
          if (result && typeof result.then === "function") {
            return result.then((result2) => handleResult2(
              dispatch,
              globalOpts,
              cacheKey2,
              handler,
              opts2,
              reqCacheControl,
              result2
            ));
          } else {
            return handleResult2(
              dispatch,
              globalOpts,
              cacheKey2,
              handler,
              opts2,
              reqCacheControl,
              result
            );
          }
        };
      };
    };
  }
});

// node_modules/undici/lib/interceptor/decompress.js
var require_decompress = __commonJS({
  "node_modules/undici/lib/interceptor/decompress.js"(exports, module) {
    "use strict";
    var { createInflate, createGunzip, createBrotliDecompress, createZstdDecompress } = __require("zlib");
    var { pipeline } = __require("stream");
    var DecoratorHandler = require_decorator_handler();
    var supportedEncodings = {
      gzip: createGunzip,
      "x-gzip": createGunzip,
      br: createBrotliDecompress,
      deflate: createInflate,
      compress: createInflate,
      "x-compress": createInflate,
      zstd: createZstdDecompress
    };
    var defaultSkipStatusCodes = (
      /** @type {const} */
      [204, 304]
    );
    var warningEmitted = (
      /** @type {boolean} */
      false
    );
    var DecompressHandler = class extends DecoratorHandler {
      /** @type {Transform[]} */
      #decompressors = [];
      /** @type {Readonly<number[]>} */
      #skipStatusCodes;
      /** @type {boolean} */
      #skipErrorResponses;
      constructor(handler, { skipStatusCodes = defaultSkipStatusCodes, skipErrorResponses = true } = {}) {
        super(handler);
        this.#skipStatusCodes = skipStatusCodes;
        this.#skipErrorResponses = skipErrorResponses;
      }
      /**
       * Determines if decompression should be skipped based on encoding and status code
       * @param {string} contentEncoding - Content-Encoding header value
       * @param {number} statusCode - HTTP status code of the response
       * @returns {boolean} - True if decompression should be skipped
       */
      #shouldSkipDecompression(contentEncoding, statusCode) {
        if (!contentEncoding || statusCode < 200) return true;
        if (this.#skipStatusCodes.includes(statusCode)) return true;
        if (this.#skipErrorResponses && statusCode >= 400) return true;
        return false;
      }
      /**
       * Creates a chain of decompressors for multiple content encodings
       *
       * @param {string} encodings - Comma-separated list of content encodings
       * @returns {Array<DecompressorStream>} - Array of decompressor streams
       * @throws {Error} - If the number of content-encodings exceeds the maximum allowed
       */
      #createDecompressionChain(encodings) {
        const parts = encodings.split(",");
        const maxContentEncodings = 5;
        if (parts.length > maxContentEncodings) {
          throw new Error(`too many content-encodings in response: ${parts.length}, maximum allowed is ${maxContentEncodings}`);
        }
        const decompressors = [];
        for (let i = parts.length - 1; i >= 0; i--) {
          const encoding = parts[i].trim();
          if (!encoding) continue;
          if (!supportedEncodings[encoding]) {
            decompressors.length = 0;
            return decompressors;
          }
          decompressors.push(supportedEncodings[encoding]());
        }
        return decompressors;
      }
      /**
       * Sets up event handlers for a decompressor stream using readable events
       * @param {DecompressorStream} decompressor - The decompressor stream
       * @param {Controller} controller - The controller to coordinate with
       * @returns {void}
       */
      #setupDecompressorEvents(decompressor, controller) {
        decompressor.on("readable", () => {
          let chunk;
          while ((chunk = decompressor.read()) !== null) {
            const result = super.onResponseData(controller, chunk);
            if (result === false) {
              break;
            }
          }
        });
        decompressor.on("error", (error) => {
          super.onResponseError(controller, error);
        });
      }
      /**
       * Sets up event handling for a single decompressor
       * @param {Controller} controller - The controller to handle events
       * @returns {void}
       */
      #setupSingleDecompressor(controller) {
        const decompressor = this.#decompressors[0];
        this.#setupDecompressorEvents(decompressor, controller);
        decompressor.on("end", () => {
          super.onResponseEnd(controller, {});
        });
      }
      /**
       * Sets up event handling for multiple chained decompressors using pipeline
       * @param {Controller} controller - The controller to handle events
       * @returns {void}
       */
      #setupMultipleDecompressors(controller) {
        const lastDecompressor = this.#decompressors[this.#decompressors.length - 1];
        this.#setupDecompressorEvents(lastDecompressor, controller);
        pipeline(this.#decompressors, (err) => {
          if (err) {
            super.onResponseError(controller, err);
            return;
          }
          super.onResponseEnd(controller, {});
        });
      }
      /**
       * Cleans up decompressor references to prevent memory leaks
       * @returns {void}
       */
      #cleanupDecompressors() {
        this.#decompressors.length = 0;
      }
      /**
       * @param {Controller} controller
       * @param {number} statusCode
       * @param {Record<string, string | string[] | undefined>} headers
       * @param {string} statusMessage
       * @returns {void}
       */
      onResponseStart(controller, statusCode, headers, statusMessage) {
        const contentEncoding = headers["content-encoding"];
        if (this.#shouldSkipDecompression(contentEncoding, statusCode)) {
          return super.onResponseStart(controller, statusCode, headers, statusMessage);
        }
        const decompressors = this.#createDecompressionChain(contentEncoding.toLowerCase());
        if (decompressors.length === 0) {
          this.#cleanupDecompressors();
          return super.onResponseStart(controller, statusCode, headers, statusMessage);
        }
        this.#decompressors = decompressors;
        const { "content-encoding": _, "content-length": __, ...newHeaders } = headers;
        if (controller?.rawHeaders) {
          const rawHeaders = controller.rawHeaders;
          if (Array.isArray(rawHeaders)) {
            const filteredHeaders = [];
            for (let i = 0; i < rawHeaders.length; i += 2) {
              const headerName = rawHeaders[i];
              const name = Buffer.isBuffer(headerName) ? headerName.toString("latin1") : `${headerName}`;
              const lowerName = name.toLowerCase();
              if (lowerName === "content-encoding" || lowerName === "content-length") {
                continue;
              }
              filteredHeaders.push(rawHeaders[i], rawHeaders[i + 1]);
            }
            controller.rawHeaders = filteredHeaders;
          } else if (typeof rawHeaders === "object") {
            for (const name of Object.keys(rawHeaders)) {
              const lowerName = name.toLowerCase();
              if (lowerName === "content-encoding" || lowerName === "content-length") {
                delete rawHeaders[name];
              }
            }
          }
        }
        if (this.#decompressors.length === 1) {
          this.#setupSingleDecompressor(controller);
        } else {
          this.#setupMultipleDecompressors(controller);
        }
        return super.onResponseStart(controller, statusCode, newHeaders, statusMessage);
      }
      /**
       * @param {Controller} controller
       * @param {Buffer} chunk
       * @returns {void}
       */
      onResponseData(controller, chunk) {
        if (this.#decompressors.length > 0) {
          this.#decompressors[0].write(chunk);
          return;
        }
        super.onResponseData(controller, chunk);
      }
      /**
       * @param {Controller} controller
       * @param {Record<string, string | string[]> | undefined} trailers
       * @returns {void}
       */
      onResponseEnd(controller, trailers) {
        if (this.#decompressors.length > 0) {
          this.#decompressors[0].end();
          this.#cleanupDecompressors();
          return;
        }
        super.onResponseEnd(controller, trailers);
      }
      /**
       * @param {Controller} controller
       * @param {Error} err
       * @returns {void}
       */
      onResponseError(controller, err) {
        if (this.#decompressors.length > 0) {
          for (const decompressor of this.#decompressors) {
            decompressor.destroy(err);
          }
          this.#cleanupDecompressors();
        }
        super.onResponseError(controller, err);
      }
    };
    function createDecompressInterceptor(options = {}) {
      if (!warningEmitted) {
        process.emitWarning(
          "DecompressInterceptor is experimental and subject to change",
          "ExperimentalWarning"
        );
        warningEmitted = true;
      }
      return (dispatch) => {
        return (opts, handler) => {
          const decompressHandler = new DecompressHandler(handler, options);
          return dispatch(opts, decompressHandler);
        };
      };
    }
    module.exports = createDecompressInterceptor;
  }
});

// node_modules/undici/lib/handler/deduplication-handler.js
var require_deduplication_handler = __commonJS({
  "node_modules/undici/lib/handler/deduplication-handler.js"(exports, module) {
    "use strict";
    var { RequestAbortedError } = require_errors();
    var DEFAULT_MAX_BUFFER_SIZE = 5 * 1024 * 1024;
    var DeduplicationHandler = class {
      /**
       * @type {DispatchHandler}
       */
      #primaryHandler;
      /**
       * @type {WaitingHandler[]}
       */
      #waitingHandlers = [];
      /**
       * @type {number}
       */
      #maxBufferSize = DEFAULT_MAX_BUFFER_SIZE;
      /**
       * @type {number}
       */
      #statusCode = 0;
      /**
       * @type {Record<string, string | string[]>}
       */
      #headers = {};
      /**
       * @type {string}
       */
      #statusMessage = "";
      /**
       * @type {boolean}
       */
      #aborted = false;
      /**
       * @type {boolean}
       */
      #responseStarted = false;
      /**
       * @type {boolean}
       */
      #responseDataStarted = false;
      /**
       * @type {boolean}
       */
      #completed = false;
      /**
       * @type {import('../../types/dispatcher.d.ts').default.DispatchController | null}
       */
      #controller = null;
      /**
       * @type {(() => void) | null}
       */
      #onComplete = null;
      /**
       * @param {DispatchHandler} primaryHandler The primary handler
       * @param {() => void} onComplete Callback when request completes
       * @param {number} [maxBufferSize] Maximum paused buffer size per waiting handler
       */
      constructor(primaryHandler, onComplete, maxBufferSize = DEFAULT_MAX_BUFFER_SIZE) {
        this.#primaryHandler = primaryHandler;
        this.#onComplete = onComplete;
        this.#maxBufferSize = maxBufferSize;
      }
      /**
       * Add a waiting handler that will receive response events.
       * Returns false if deduplication can no longer safely attach this handler.
       *
       * @param {DispatchHandler} handler
       * @returns {boolean}
       */
      addWaitingHandler(handler) {
        if (this.#completed || this.#responseDataStarted) {
          return false;
        }
        const waitingHandler = this.#createWaitingHandler(handler);
        const waitingController = waitingHandler.controller;
        try {
          handler.onRequestStart?.(waitingController, null);
          if (waitingController.aborted) {
            waitingHandler.done = true;
            return true;
          }
          if (this.#responseStarted) {
            handler.onResponseStart?.(
              waitingController,
              this.#statusCode,
              this.#headers,
              this.#statusMessage
            );
          }
        } catch {
          waitingHandler.done = true;
          return true;
        }
        if (!waitingController.aborted) {
          this.#waitingHandlers.push(waitingHandler);
        }
        return true;
      }
      /**
       * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
       * @param {any} context
       */
      onRequestStart(controller, context) {
        this.#controller = controller;
        this.#primaryHandler.onRequestStart?.(controller, context);
      }
      /**
       * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
       * @param {number} statusCode
       * @param {import('../../types/header.d.ts').IncomingHttpHeaders} headers
       * @param {Socket} socket
       */
      onRequestUpgrade(controller, statusCode, headers, socket) {
        this.#primaryHandler.onRequestUpgrade?.(controller, statusCode, headers, socket);
      }
      /**
       * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
       * @param {number} statusCode
       * @param {Record<string, string | string[]>} headers
       * @param {string} statusMessage
       */
      onResponseStart(controller, statusCode, headers, statusMessage) {
        this.#responseStarted = true;
        this.#statusCode = statusCode;
        this.#headers = headers;
        this.#statusMessage = statusMessage;
        this.#primaryHandler.onResponseStart?.(controller, statusCode, headers, statusMessage);
        for (const waitingHandler of this.#waitingHandlers) {
          const { handler, controller: waitingController } = waitingHandler;
          if (waitingHandler.done || waitingController.aborted) {
            waitingHandler.done = true;
            continue;
          }
          try {
            handler.onResponseStart?.(
              waitingController,
              statusCode,
              headers,
              statusMessage
            );
          } catch {
          }
          if (waitingController.aborted) {
            waitingHandler.done = true;
          }
        }
        this.#pruneDoneWaitingHandlers();
      }
      /**
       * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
       * @param {Buffer} chunk
       */
      onResponseData(controller, chunk) {
        if (this.#aborted || this.#completed) {
          return;
        }
        this.#responseDataStarted = true;
        this.#primaryHandler.onResponseData?.(controller, chunk);
        for (const waitingHandler of this.#waitingHandlers) {
          const { handler, controller: waitingController } = waitingHandler;
          if (waitingHandler.done || waitingController.aborted) {
            waitingHandler.done = true;
            continue;
          }
          if (waitingController.paused) {
            this.#bufferWaitingChunk(waitingHandler, chunk);
            continue;
          }
          try {
            handler.onResponseData?.(waitingController, chunk);
          } catch {
          }
          if (waitingController.aborted) {
            waitingHandler.done = true;
            waitingHandler.bufferedChunks = [];
            waitingHandler.bufferedBytes = 0;
          }
        }
        this.#pruneDoneWaitingHandlers();
      }
      /**
       * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
       * @param {object} trailers
       */
      onResponseEnd(controller, trailers) {
        if (this.#aborted || this.#completed) {
          return;
        }
        this.#completed = true;
        this.#primaryHandler.onResponseEnd?.(controller, trailers);
        for (const waitingHandler of this.#waitingHandlers) {
          if (waitingHandler.done || waitingHandler.controller.aborted) {
            waitingHandler.done = true;
            continue;
          }
          this.#flushWaitingHandler(waitingHandler);
          if (waitingHandler.done || waitingHandler.controller.aborted) {
            waitingHandler.done = true;
            continue;
          }
          if (waitingHandler.controller.paused && waitingHandler.bufferedChunks.length > 0) {
            waitingHandler.pendingTrailers = trailers;
            continue;
          }
          try {
            waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, trailers);
          } catch {
          }
          waitingHandler.done = true;
        }
        this.#pruneDoneWaitingHandlers();
        this.#onComplete?.();
      }
      /**
       * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
       * @param {Error} err
       */
      onResponseError(controller, err) {
        if (this.#completed) {
          return;
        }
        this.#aborted = true;
        this.#completed = true;
        this.#primaryHandler.onResponseError?.(controller, err);
        for (const waitingHandler of this.#waitingHandlers) {
          this.#errorWaitingHandler(waitingHandler, err);
        }
        this.#waitingHandlers = [];
        this.#onComplete?.();
      }
      /**
       * @param {DispatchHandler} handler
       * @returns {WaitingHandler}
       */
      #createWaitingHandler(handler) {
        const waitingHandler = {
          handler,
          controller: null,
          bufferedChunks: [],
          bufferedBytes: 0,
          pendingTrailers: null,
          done: false
        };
        const state = {
          aborted: false,
          paused: false,
          reason: null
        };
        waitingHandler.controller = {
          resume: () => {
            if (state.aborted) {
              return;
            }
            state.paused = false;
            this.#flushWaitingHandler(waitingHandler);
            if (this.#completed && waitingHandler.pendingTrailers && waitingHandler.bufferedChunks.length === 0 && !state.paused && !state.aborted) {
              try {
                waitingHandler.handler.onResponseEnd?.(waitingHandler.controller, waitingHandler.pendingTrailers);
              } catch {
              }
              waitingHandler.pendingTrailers = null;
              waitingHandler.done = true;
            }
            this.#pruneDoneWaitingHandlers();
          },
          pause: () => {
            if (!state.aborted) {
              state.paused = true;
            }
          },
          get paused() {
            return state.paused;
          },
          get aborted() {
            return state.aborted;
          },
          get reason() {
            return state.reason;
          },
          abort: (reason) => {
            state.aborted = true;
            state.reason = reason ?? null;
            waitingHandler.done = true;
            waitingHandler.pendingTrailers = null;
            waitingHandler.bufferedChunks = [];
            waitingHandler.bufferedBytes = 0;
          }
        };
        return waitingHandler;
      }
      /**
       * @param {WaitingHandler} waitingHandler
       * @param {Buffer} chunk
       */
      #bufferWaitingChunk(waitingHandler, chunk) {
        if (waitingHandler.done || waitingHandler.controller.aborted) {
          waitingHandler.done = true;
          waitingHandler.bufferedChunks = [];
          waitingHandler.bufferedBytes = 0;
          return;
        }
        const bufferedChunk = Buffer.from(chunk);
        waitingHandler.bufferedChunks.push(bufferedChunk);
        waitingHandler.bufferedBytes += bufferedChunk.length;
        if (waitingHandler.bufferedBytes > this.#maxBufferSize) {
          const err = new RequestAbortedError(`Deduplicated waiting handler exceeded maxBufferSize (${this.#maxBufferSize} bytes) while paused`);
          this.#errorWaitingHandler(waitingHandler, err);
        }
      }
      /**
       * @param {WaitingHandler} waitingHandler
       */
      #flushWaitingHandler(waitingHandler) {
        const { handler, controller } = waitingHandler;
        while (!waitingHandler.done && !controller.aborted && !controller.paused && waitingHandler.bufferedChunks.length > 0) {
          const bufferedChunk = waitingHandler.bufferedChunks.shift();
          waitingHandler.bufferedBytes -= bufferedChunk.length;
          try {
            handler.onResponseData?.(controller, bufferedChunk);
          } catch {
          }
          if (controller.aborted) {
            waitingHandler.done = true;
            waitingHandler.pendingTrailers = null;
            waitingHandler.bufferedChunks = [];
            waitingHandler.bufferedBytes = 0;
            break;
          }
        }
      }
      /**
       * @param {WaitingHandler} waitingHandler
       * @param {Error} err
       */
      #errorWaitingHandler(waitingHandler, err) {
        if (waitingHandler.done) {
          return;
        }
        waitingHandler.done = true;
        waitingHandler.pendingTrailers = null;
        waitingHandler.bufferedChunks = [];
        waitingHandler.bufferedBytes = 0;
        try {
          waitingHandler.controller.abort(err);
          waitingHandler.handler.onResponseError?.(waitingHandler.controller, err);
        } catch {
        }
      }
      #pruneDoneWaitingHandlers() {
        this.#waitingHandlers = this.#waitingHandlers.filter((waitingHandler) => waitingHandler.done === false);
      }
    };
    module.exports = DeduplicationHandler;
  }
});

// node_modules/undici/lib/interceptor/deduplicate.js
var require_deduplicate = __commonJS({
  "node_modules/undici/lib/interceptor/deduplicate.js"(exports, module) {
    "use strict";
    var diagnosticsChannel = __require("diagnostics_channel");
    var util2 = require_util();
    var DeduplicationHandler = require_deduplication_handler();
    var { normalizeHeaders: normalizeHeaders3, makeCacheKey, makeDeduplicationKey } = require_cache();
    var pendingRequestsChannel = diagnosticsChannel.channel("undici:request:pending-requests");
    module.exports = (opts = {}) => {
      const {
        methods = ["GET"],
        skipHeaderNames = [],
        excludeHeaderNames = [],
        maxBufferSize = 5 * 1024 * 1024
      } = opts;
      if (typeof opts !== "object" || opts === null) {
        throw new TypeError(`expected type of opts to be an Object, got ${opts === null ? "null" : typeof opts}`);
      }
      if (!Array.isArray(methods)) {
        throw new TypeError(`expected opts.methods to be an array, got ${typeof methods}`);
      }
      for (const method of methods) {
        if (!util2.safeHTTPMethods.includes(method)) {
          throw new TypeError(`expected opts.methods to only contain safe HTTP methods, got ${method}`);
        }
      }
      if (!Array.isArray(skipHeaderNames)) {
        throw new TypeError(`expected opts.skipHeaderNames to be an array, got ${typeof skipHeaderNames}`);
      }
      if (!Array.isArray(excludeHeaderNames)) {
        throw new TypeError(`expected opts.excludeHeaderNames to be an array, got ${typeof excludeHeaderNames}`);
      }
      if (!Number.isFinite(maxBufferSize) || maxBufferSize <= 0) {
        throw new TypeError(`expected opts.maxBufferSize to be a positive finite number, got ${maxBufferSize}`);
      }
      const skipHeaderNamesSet = new Set(skipHeaderNames.map((name) => name.toLowerCase()));
      const excludeHeaderNamesSet = new Set(excludeHeaderNames.map((name) => name.toLowerCase()));
      const pendingRequests = /* @__PURE__ */ new Map();
      return (dispatch) => {
        return (opts2, handler) => {
          if (!opts2.origin || methods.includes(opts2.method) === false) {
            return dispatch(opts2, handler);
          }
          opts2 = {
            ...opts2,
            headers: normalizeHeaders3(opts2)
          };
          if (skipHeaderNamesSet.size > 0) {
            for (const headerName of Object.keys(opts2.headers)) {
              if (skipHeaderNamesSet.has(headerName.toLowerCase())) {
                return dispatch(opts2, handler);
              }
            }
          }
          const cacheKey2 = makeCacheKey(opts2);
          const dedupeKey = makeDeduplicationKey(cacheKey2, excludeHeaderNamesSet);
          const pendingHandler = pendingRequests.get(dedupeKey);
          if (pendingHandler) {
            if (pendingHandler.addWaitingHandler(handler)) {
              return true;
            }
            return dispatch(opts2, handler);
          }
          const deduplicationHandler = new DeduplicationHandler(
            handler,
            () => {
              pendingRequests.delete(dedupeKey);
              if (pendingRequestsChannel.hasSubscribers) {
                pendingRequestsChannel.publish({ size: pendingRequests.size, key: dedupeKey, type: "removed" });
              }
            },
            maxBufferSize
          );
          pendingRequests.set(dedupeKey, deduplicationHandler);
          if (pendingRequestsChannel.hasSubscribers) {
            pendingRequestsChannel.publish({ size: pendingRequests.size, key: dedupeKey, type: "added" });
          }
          return dispatch(opts2, deduplicationHandler);
        };
      };
    };
  }
});

// node_modules/undici/lib/cache/sqlite-cache-store.js
var require_sqlite_cache_store = __commonJS({
  "node_modules/undici/lib/cache/sqlite-cache-store.js"(exports, module) {
    "use strict";
    var { Writable } = __require("stream");
    var { assertCacheKey, assertCacheValue } = require_cache();
    var DatabaseSync;
    var VERSION2 = 3;
    var MAX_ENTRY_SIZE = 2 * 1e3 * 1e3 * 1e3;
    module.exports = class SqliteCacheStore {
      #maxEntrySize = MAX_ENTRY_SIZE;
      #maxCount = Infinity;
      /**
       * @type {import('node:sqlite').DatabaseSync}
       */
      #db;
      /**
       * @type {import('node:sqlite').StatementSync}
       */
      #getValuesQuery;
      /**
       * @type {import('node:sqlite').StatementSync}
       */
      #updateValueQuery;
      /**
       * @type {import('node:sqlite').StatementSync}
       */
      #insertValueQuery;
      /**
       * @type {import('node:sqlite').StatementSync}
       */
      #deleteExpiredValuesQuery;
      /**
       * @type {import('node:sqlite').StatementSync}
       */
      #deleteByUrlQuery;
      /**
       * @type {import('node:sqlite').StatementSync}
       */
      #countEntriesQuery;
      /**
       * @type {import('node:sqlite').StatementSync | null}
       */
      #deleteOldValuesQuery;
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.SqliteCacheStoreOpts | undefined} opts
       */
      constructor(opts) {
        if (opts) {
          if (typeof opts !== "object") {
            throw new TypeError("SqliteCacheStore options must be an object");
          }
          if (opts.maxEntrySize !== void 0) {
            if (typeof opts.maxEntrySize !== "number" || !Number.isInteger(opts.maxEntrySize) || opts.maxEntrySize < 0) {
              throw new TypeError("SqliteCacheStore options.maxEntrySize must be a non-negative integer");
            }
            if (opts.maxEntrySize > MAX_ENTRY_SIZE) {
              throw new TypeError("SqliteCacheStore options.maxEntrySize must be less than 2gb");
            }
            this.#maxEntrySize = opts.maxEntrySize;
          }
          if (opts.maxCount !== void 0) {
            if (typeof opts.maxCount !== "number" || !Number.isInteger(opts.maxCount) || opts.maxCount < 0) {
              throw new TypeError("SqliteCacheStore options.maxCount must be a non-negative integer");
            }
            this.#maxCount = opts.maxCount;
          }
        }
        if (!DatabaseSync) {
          DatabaseSync = __require("sqlite").DatabaseSync;
        }
        this.#db = new DatabaseSync(opts?.location ?? ":memory:");
        this.#db.exec(`
      PRAGMA journal_mode = WAL;
      PRAGMA synchronous = NORMAL;
      PRAGMA temp_store = memory;
      PRAGMA optimize;

      CREATE TABLE IF NOT EXISTS cacheInterceptorV${VERSION2} (
        -- Data specific to us
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        url TEXT NOT NULL,
        method TEXT NOT NULL,

        -- Data returned to the interceptor
        body BUF NULL,
        deleteAt INTEGER NOT NULL,
        statusCode INTEGER NOT NULL,
        statusMessage TEXT NOT NULL,
        headers TEXT NULL,
        cacheControlDirectives TEXT NULL,
        etag TEXT NULL,
        vary TEXT NULL,
        cachedAt INTEGER NOT NULL,
        staleAt INTEGER NOT NULL
      );

      CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION2}_getValuesQuery ON cacheInterceptorV${VERSION2}(url, method, deleteAt);
      CREATE INDEX IF NOT EXISTS idx_cacheInterceptorV${VERSION2}_deleteByUrlQuery ON cacheInterceptorV${VERSION2}(deleteAt);
    `);
        this.#getValuesQuery = this.#db.prepare(`
      SELECT
        id,
        body,
        deleteAt,
        statusCode,
        statusMessage,
        headers,
        etag,
        cacheControlDirectives,
        vary,
        cachedAt,
        staleAt
      FROM cacheInterceptorV${VERSION2}
      WHERE
        url = ?
        AND method = ?
      ORDER BY
        deleteAt ASC
    `);
        this.#updateValueQuery = this.#db.prepare(`
      UPDATE cacheInterceptorV${VERSION2} SET
        body = ?,
        deleteAt = ?,
        statusCode = ?,
        statusMessage = ?,
        headers = ?,
        etag = ?,
        cacheControlDirectives = ?,
        vary = ?,
        cachedAt = ?,
        staleAt = ?
      WHERE
        id = ?
    `);
        this.#insertValueQuery = this.#db.prepare(`
      INSERT INTO cacheInterceptorV${VERSION2} (
        url,
        method,
        body,
        deleteAt,
        statusCode,
        statusMessage,
        headers,
        etag,
        cacheControlDirectives,
        vary,
        cachedAt,
        staleAt
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `);
        this.#deleteByUrlQuery = this.#db.prepare(
          `DELETE FROM cacheInterceptorV${VERSION2} WHERE url = ?`
        );
        this.#countEntriesQuery = this.#db.prepare(
          `SELECT COUNT(*) AS total FROM cacheInterceptorV${VERSION2}`
        );
        this.#deleteExpiredValuesQuery = this.#db.prepare(
          `DELETE FROM cacheInterceptorV${VERSION2} WHERE deleteAt <= ?`
        );
        this.#deleteOldValuesQuery = this.#maxCount === Infinity ? null : this.#db.prepare(`
        DELETE FROM cacheInterceptorV${VERSION2}
        WHERE id IN (
          SELECT
            id
          FROM cacheInterceptorV${VERSION2}
          ORDER BY cachedAt ASC
          LIMIT ?
        )
      `);
      }
      close() {
        this.#db.close();
      }
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
       * @returns {(import('../../types/cache-interceptor.d.ts').default.GetResult & { body?: Buffer }) | undefined}
       */
      get(key) {
        assertCacheKey(key);
        const value = this.#findValue(key);
        return value ? {
          body: value.body ? Buffer.from(value.body.buffer, value.body.byteOffset, value.body.byteLength) : void 0,
          statusCode: value.statusCode,
          statusMessage: value.statusMessage,
          headers: value.headers ? JSON.parse(value.headers) : void 0,
          etag: value.etag ? value.etag : void 0,
          vary: value.vary ? JSON.parse(value.vary) : void 0,
          cacheControlDirectives: value.cacheControlDirectives ? JSON.parse(value.cacheControlDirectives) : void 0,
          cachedAt: value.cachedAt,
          staleAt: value.staleAt,
          deleteAt: value.deleteAt
        } : void 0;
      }
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue & { body: null | Buffer | Array<Buffer>}} value
       */
      set(key, value) {
        assertCacheKey(key);
        const url = this.#makeValueUrl(key);
        const body = Array.isArray(value.body) ? Buffer.concat(value.body) : value.body;
        const size5 = body?.byteLength;
        if (size5 && size5 > this.#maxEntrySize) {
          return;
        }
        const existingValue = this.#findValue(key, true);
        if (existingValue) {
          this.#updateValueQuery.run(
            body,
            value.deleteAt,
            value.statusCode,
            value.statusMessage,
            value.headers ? JSON.stringify(value.headers) : null,
            value.etag ? value.etag : null,
            value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null,
            value.vary ? JSON.stringify(value.vary) : null,
            value.cachedAt,
            value.staleAt,
            existingValue.id
          );
        } else {
          this.#insertValueQuery.run(
            url,
            key.method,
            body,
            value.deleteAt,
            value.statusCode,
            value.statusMessage,
            value.headers ? JSON.stringify(value.headers) : null,
            value.etag ? value.etag : null,
            value.cacheControlDirectives ? JSON.stringify(value.cacheControlDirectives) : null,
            value.vary ? JSON.stringify(value.vary) : null,
            value.cachedAt,
            value.staleAt
          );
          this.#prune();
        }
      }
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheValue} value
       * @returns {Writable | undefined}
       */
      createWriteStream(key, value) {
        assertCacheKey(key);
        assertCacheValue(value);
        let size5 = 0;
        const body = [];
        const store = this;
        return new Writable({
          decodeStrings: true,
          write(chunk, encoding, callback) {
            size5 += chunk.byteLength;
            if (size5 <= store.#maxEntrySize) {
              body.push(chunk);
            } else {
              this.destroy();
            }
            callback();
          },
          final(callback) {
            store.set(key, { ...value, body });
            callback();
          }
        });
      }
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
       */
      delete(key) {
        if (typeof key !== "object") {
          throw new TypeError(`expected key to be object, got ${typeof key}`);
        }
        this.#deleteByUrlQuery.run(this.#makeValueUrl(key));
      }
      #prune() {
        if (Number.isFinite(this.#maxCount) && this.size <= this.#maxCount) {
          return 0;
        }
        {
          const removed = this.#deleteExpiredValuesQuery.run(Date.now()).changes;
          if (removed) {
            return removed;
          }
        }
        {
          const removed = this.#deleteOldValuesQuery?.run(Math.max(Math.floor(this.#maxCount * 0.1), 1)).changes;
          if (removed) {
            return removed;
          }
        }
        return 0;
      }
      /**
       * Counts the number of rows in the cache
       * @returns {Number}
       */
      get size() {
        const { total } = this.#countEntriesQuery.get();
        return total;
      }
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
       * @returns {string}
       */
      #makeValueUrl(key) {
        return `${key.origin}/${key.path}`;
      }
      /**
       * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} key
       * @param {boolean} [canBeExpired=false]
       * @returns {SqliteStoreValue | undefined}
       */
      #findValue(key, canBeExpired = false) {
        const url = this.#makeValueUrl(key);
        const { headers, method } = key;
        const values = this.#getValuesQuery.all(url, method);
        if (values.length === 0) {
          return void 0;
        }
        const now = Date.now();
        for (const value of values) {
          if (now >= value.deleteAt && !canBeExpired) {
            continue;
          }
          let matches = true;
          if (value.vary) {
            const vary = JSON.parse(value.vary);
            for (const header in vary) {
              if (!headerValueEquals(headers[header], vary[header])) {
                matches = false;
                break;
              }
            }
          }
          if (matches) {
            return value;
          }
        }
        return void 0;
      }
    };
    function headerValueEquals(lhs, rhs) {
      if (lhs == null && rhs == null) {
        return true;
      }
      if (lhs == null && rhs != null || lhs != null && rhs == null) {
        return false;
      }
      if (Array.isArray(lhs) && Array.isArray(rhs)) {
        if (lhs.length !== rhs.length) {
          return false;
        }
        return lhs.every((x, i) => x === rhs[i]);
      }
      return lhs === rhs;
    }
  }
});

// node_modules/undici/lib/web/fetch/headers.js
var require_headers = __commonJS({
  "node_modules/undici/lib/web/fetch/headers.js"(exports, module) {
    "use strict";
    var { kConstruct } = require_symbols();
    var { kEnumerableProperty } = require_util();
    var {
      iteratorMixin,
      isValidHeaderName,
      isValidHeaderValue
    } = require_util2();
    var { webidl } = require_webidl();
    var assert8 = __require("assert");
    var util2 = __require("util");
    function isHTTPWhiteSpaceCharCode(code) {
      return code === 10 || code === 13 || code === 9 || code === 32;
    }
    function headerValueNormalize(potentialValue) {
      let i = 0;
      let j = potentialValue.length;
      while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j;
      while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i;
      return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j);
    }
    function fill(headers, object) {
      if (Array.isArray(object)) {
        for (let i = 0; i < object.length; ++i) {
          const header = object[i];
          if (header.length !== 2) {
            throw webidl.errors.exception({
              header: "Headers constructor",
              message: `expected name/value pair to be length 2, found ${header.length}.`
            });
          }
          appendHeader(headers, header[0], header[1]);
        }
      } else if (typeof object === "object" && object !== null) {
        const keys = Object.keys(object);
        for (let i = 0; i < keys.length; ++i) {
          appendHeader(headers, keys[i], object[keys[i]]);
        }
      } else {
        throw webidl.errors.conversionFailed({
          prefix: "Headers constructor",
          argument: "Argument 1",
          types: ["sequence<sequence<ByteString>>", "record<ByteString, ByteString>"]
        });
      }
    }
    function appendHeader(headers, name, value) {
      value = headerValueNormalize(value);
      if (!isValidHeaderName(name)) {
        throw webidl.errors.invalidArgument({
          prefix: "Headers.append",
          value: name,
          type: "header name"
        });
      } else if (!isValidHeaderValue(value)) {
        throw webidl.errors.invalidArgument({
          prefix: "Headers.append",
          value,
          type: "header value"
        });
      }
      if (getHeadersGuard(headers) === "immutable") {
        throw new TypeError("immutable");
      }
      return getHeadersList(headers).append(name, value, false);
    }
    function headersListSortAndCombine(target) {
      const headersList = getHeadersList(target);
      if (!headersList) {
        return [];
      }
      if (headersList.sortedMap) {
        return headersList.sortedMap;
      }
      const headers = [];
      const names = headersList.toSortedArray();
      const cookies = headersList.cookies;
      if (cookies === null || cookies.length === 1) {
        return headersList.sortedMap = names;
      }
      for (let i = 0; i < names.length; ++i) {
        const { 0: name, 1: value } = names[i];
        if (name === "set-cookie") {
          for (let j = 0; j < cookies.length; ++j) {
            headers.push([name, cookies[j]]);
          }
        } else {
          headers.push([name, value]);
        }
      }
      return headersList.sortedMap = headers;
    }
    function compareHeaderName(a, b) {
      return a[0] < b[0] ? -1 : 1;
    }
    var HeadersList = class _HeadersList {
      /** @type {[string, string][]|null} */
      cookies = null;
      sortedMap;
      headersMap;
      constructor(init) {
        if (init instanceof _HeadersList) {
          this.headersMap = new Map(init.headersMap);
          this.sortedMap = init.sortedMap;
          this.cookies = init.cookies === null ? null : [...init.cookies];
        } else {
          this.headersMap = new Map(init);
          this.sortedMap = null;
        }
      }
      /**
       * @see https://fetch.spec.whatwg.org/#header-list-contains
       * @param {string} name
       * @param {boolean} isLowerCase
       */
      contains(name, isLowerCase) {
        return this.headersMap.has(isLowerCase ? name : name.toLowerCase());
      }
      clear() {
        this.headersMap.clear();
        this.sortedMap = null;
        this.cookies = null;
      }
      /**
       * @see https://fetch.spec.whatwg.org/#concept-header-list-append
       * @param {string} name
       * @param {string} value
       * @param {boolean} isLowerCase
       */
      append(name, value, isLowerCase) {
        this.sortedMap = null;
        const lowercaseName = isLowerCase ? name : name.toLowerCase();
        const exists = this.headersMap.get(lowercaseName);
        if (exists) {
          const delimiter = lowercaseName === "cookie" ? "; " : ", ";
          this.headersMap.set(lowercaseName, {
            name: exists.name,
            value: `${exists.value}${delimiter}${value}`
          });
        } else {
          this.headersMap.set(lowercaseName, { name, value });
        }
        if (lowercaseName === "set-cookie") {
          (this.cookies ??= []).push(value);
        }
      }
      /**
       * @see https://fetch.spec.whatwg.org/#concept-header-list-set
       * @param {string} name
       * @param {string} value
       * @param {boolean} isLowerCase
       */
      set(name, value, isLowerCase) {
        this.sortedMap = null;
        const lowercaseName = isLowerCase ? name : name.toLowerCase();
        if (lowercaseName === "set-cookie") {
          this.cookies = [value];
        }
        this.headersMap.set(lowercaseName, { name, value });
      }
      /**
       * @see https://fetch.spec.whatwg.org/#concept-header-list-delete
       * @param {string} name
       * @param {boolean} isLowerCase
       */
      delete(name, isLowerCase) {
        this.sortedMap = null;
        if (!isLowerCase) name = name.toLowerCase();
        if (name === "set-cookie") {
          this.cookies = null;
        }
        this.headersMap.delete(name);
      }
      /**
       * @see https://fetch.spec.whatwg.org/#concept-header-list-get
       * @param {string} name
       * @param {boolean} isLowerCase
       * @returns {string | null}
       */
      get(name, isLowerCase) {
        return this.headersMap.get(isLowerCase ? name : name.toLowerCase())?.value ?? null;
      }
      *[Symbol.iterator]() {
        for (const { 0: name, 1: { value } } of this.headersMap) {
          yield [name, value];
        }
      }
      get entries() {
        const headers = {};
        if (this.headersMap.size !== 0) {
          for (const { name, value } of this.headersMap.values()) {
            headers[name] = value;
          }
        }
        return headers;
      }
      rawValues() {
        return this.headersMap.values();
      }
      get entriesList() {
        const headers = [];
        if (this.headersMap.size !== 0) {
          for (const { 0: lowerName, 1: { name, value } } of this.headersMap) {
            if (lowerName === "set-cookie") {
              for (const cookie of this.cookies) {
                headers.push([name, cookie]);
              }
            } else {
              headers.push([name, value]);
            }
          }
        }
        return headers;
      }
      // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set
      toSortedArray() {
        const size5 = this.headersMap.size;
        const array = new Array(size5);
        if (size5 <= 32) {
          if (size5 === 0) {
            return array;
          }
          const iterator = this.headersMap[Symbol.iterator]();
          const firstValue = iterator.next().value;
          array[0] = [firstValue[0], firstValue[1].value];
          assert8(firstValue[1].value !== null);
          for (let i = 1, j = 0, right = 0, left = 0, pivot = 0, x, value; i < size5; ++i) {
            value = iterator.next().value;
            x = array[i] = [value[0], value[1].value];
            assert8(x[1] !== null);
            left = 0;
            right = i;
            while (left < right) {
              pivot = left + (right - left >> 1);
              if (array[pivot][0] <= x[0]) {
                left = pivot + 1;
              } else {
                right = pivot;
              }
            }
            if (i !== pivot) {
              j = i;
              while (j > left) {
                array[j] = array[--j];
              }
              array[left] = x;
            }
          }
          if (!iterator.next().done) {
            throw new TypeError("Unreachable");
          }
          return array;
        } else {
          let i = 0;
          for (const { 0: name, 1: { value } } of this.headersMap) {
            array[i++] = [name, value];
            assert8(value !== null);
          }
          return array.sort(compareHeaderName);
        }
      }
    };
    var Headers = class _Headers {
      #guard;
      /**
       * @type {HeadersList}
       */
      #headersList;
      /**
       * @param {HeadersInit|Symbol} [init]
       * @returns
       */
      constructor(init = void 0) {
        webidl.util.markAsUncloneable(this);
        if (init === kConstruct) {
          return;
        }
        this.#headersList = new HeadersList();
        this.#guard = "none";
        if (init !== void 0) {
          init = webidl.converters.HeadersInit(init, "Headers constructor", "init");
          fill(this, init);
        }
      }
      // https://fetch.spec.whatwg.org/#dom-headers-append
      append(name, value) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 2, "Headers.append");
        const prefix = "Headers.append";
        name = webidl.converters.ByteString(name, prefix, "name");
        value = webidl.converters.ByteString(value, prefix, "value");
        return appendHeader(this, name, value);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-delete
      delete(name) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 1, "Headers.delete");
        const prefix = "Headers.delete";
        name = webidl.converters.ByteString(name, prefix, "name");
        if (!isValidHeaderName(name)) {
          throw webidl.errors.invalidArgument({
            prefix: "Headers.delete",
            value: name,
            type: "header name"
          });
        }
        if (this.#guard === "immutable") {
          throw new TypeError("immutable");
        }
        if (!this.#headersList.contains(name, false)) {
          return;
        }
        this.#headersList.delete(name, false);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-get
      get(name) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 1, "Headers.get");
        const prefix = "Headers.get";
        name = webidl.converters.ByteString(name, prefix, "name");
        if (!isValidHeaderName(name)) {
          throw webidl.errors.invalidArgument({
            prefix,
            value: name,
            type: "header name"
          });
        }
        return this.#headersList.get(name, false);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-has
      has(name) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 1, "Headers.has");
        const prefix = "Headers.has";
        name = webidl.converters.ByteString(name, prefix, "name");
        if (!isValidHeaderName(name)) {
          throw webidl.errors.invalidArgument({
            prefix,
            value: name,
            type: "header name"
          });
        }
        return this.#headersList.contains(name, false);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-set
      set(name, value) {
        webidl.brandCheck(this, _Headers);
        webidl.argumentLengthCheck(arguments, 2, "Headers.set");
        const prefix = "Headers.set";
        name = webidl.converters.ByteString(name, prefix, "name");
        value = webidl.converters.ByteString(value, prefix, "value");
        value = headerValueNormalize(value);
        if (!isValidHeaderName(name)) {
          throw webidl.errors.invalidArgument({
            prefix,
            value: name,
            type: "header name"
          });
        } else if (!isValidHeaderValue(value)) {
          throw webidl.errors.invalidArgument({
            prefix,
            value,
            type: "header value"
          });
        }
        if (this.#guard === "immutable") {
          throw new TypeError("immutable");
        }
        this.#headersList.set(name, value, false);
      }
      // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
      getSetCookie() {
        webidl.brandCheck(this, _Headers);
        const list = this.#headersList.cookies;
        if (list) {
          return [...list];
        }
        return [];
      }
      [util2.inspect.custom](depth, options) {
        options.depth ??= depth;
        return `Headers ${util2.formatWithOptions(options, this.#headersList.entries)}`;
      }
      static getHeadersGuard(o3) {
        return o3.#guard;
      }
      static setHeadersGuard(o3, guard) {
        o3.#guard = guard;
      }
      /**
       * @param {Headers} o
       */
      static getHeadersList(o3) {
        return o3.#headersList;
      }
      /**
       * @param {Headers} target
       * @param {HeadersList} list
       */
      static setHeadersList(target, list) {
        target.#headersList = list;
      }
    };
    var { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers;
    Reflect.deleteProperty(Headers, "getHeadersGuard");
    Reflect.deleteProperty(Headers, "setHeadersGuard");
    Reflect.deleteProperty(Headers, "getHeadersList");
    Reflect.deleteProperty(Headers, "setHeadersList");
    iteratorMixin("Headers", Headers, headersListSortAndCombine, 0, 1);
    Object.defineProperties(Headers.prototype, {
      append: kEnumerableProperty,
      delete: kEnumerableProperty,
      get: kEnumerableProperty,
      has: kEnumerableProperty,
      set: kEnumerableProperty,
      getSetCookie: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "Headers",
        configurable: true
      },
      [util2.inspect.custom]: {
        enumerable: false
      }
    });
    webidl.converters.HeadersInit = function(V, prefix, argument) {
      if (webidl.util.Type(V) === webidl.util.Types.OBJECT) {
        const iterator = Reflect.get(V, Symbol.iterator);
        if (!util2.types.isProxy(V) && iterator === Headers.prototype.entries) {
          try {
            return getHeadersList(V).entriesList;
          } catch {
          }
        }
        if (typeof iterator === "function") {
          return webidl.converters["sequence<sequence<ByteString>>"](V, prefix, argument, iterator.bind(V));
        }
        return webidl.converters["record<ByteString, ByteString>"](V, prefix, argument);
      }
      throw webidl.errors.conversionFailed({
        prefix: "Headers constructor",
        argument: "Argument 1",
        types: ["sequence<sequence<ByteString>>", "record<ByteString, ByteString>"]
      });
    };
    module.exports = {
      fill,
      // for test.
      compareHeaderName,
      Headers,
      HeadersList,
      getHeadersGuard,
      setHeadersGuard,
      setHeadersList,
      getHeadersList
    };
  }
});

// node_modules/undici/lib/web/fetch/response.js
var require_response = __commonJS({
  "node_modules/undici/lib/web/fetch/response.js"(exports, module) {
    "use strict";
    var { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = require_headers();
    var { extractBody, cloneBody, mixinBody, streamRegistry, bodyUnusable } = require_body();
    var util2 = require_util();
    var nodeUtil = __require("util");
    var { kEnumerableProperty } = util2;
    var {
      isValidReasonPhrase,
      isCancelled,
      isAborted: isAborted2,
      isErrorLike,
      environmentSettingsObject: relevantRealm
    } = require_util2();
    var {
      redirectStatusSet,
      nullBodyStatus
    } = require_constants4();
    var { webidl } = require_webidl();
    var { URLSerializer } = require_data_url();
    var { kConstruct } = require_symbols();
    var assert8 = __require("assert");
    var { isomorphicEncode, serializeJavascriptValueToJSONString } = require_infra();
    var textEncoder = new TextEncoder("utf-8");
    var Response2 = class _Response {
      /** @type {Headers} */
      #headers;
      #state;
      // Creates network error Response.
      static error() {
        const responseObject = fromInnerResponse(makeNetworkError(), "immutable");
        return responseObject;
      }
      // https://fetch.spec.whatwg.org/#dom-response-json
      static json(data, init = void 0) {
        webidl.argumentLengthCheck(arguments, 1, "Response.json");
        if (init !== null) {
          init = webidl.converters.ResponseInit(init);
        }
        const bytes = textEncoder.encode(
          serializeJavascriptValueToJSONString(data)
        );
        const body = extractBody(bytes);
        const responseObject = fromInnerResponse(makeResponse({}), "response");
        initializeResponse(responseObject, init, { body: body[0], type: "application/json" });
        return responseObject;
      }
      // Creates a redirect Response that redirects to url with status status.
      static redirect(url, status = 302) {
        webidl.argumentLengthCheck(arguments, 1, "Response.redirect");
        url = webidl.converters.USVString(url);
        status = webidl.converters["unsigned short"](status);
        let parsedURL;
        try {
          parsedURL = new URL(url, relevantRealm.settingsObject.baseUrl);
        } catch (err) {
          throw new TypeError(`Failed to parse URL from ${url}`, { cause: err });
        }
        if (!redirectStatusSet.has(status)) {
          throw new RangeError(`Invalid status code ${status}`);
        }
        const responseObject = fromInnerResponse(makeResponse({}), "immutable");
        responseObject.#state.status = status;
        const value = isomorphicEncode(URLSerializer(parsedURL));
        responseObject.#state.headersList.append("location", value, true);
        return responseObject;
      }
      // https://fetch.spec.whatwg.org/#dom-response
      constructor(body = null, init = void 0) {
        webidl.util.markAsUncloneable(this);
        if (body === kConstruct) {
          return;
        }
        if (body !== null) {
          body = webidl.converters.BodyInit(body, "Response", "body");
        }
        init = webidl.converters.ResponseInit(init);
        this.#state = makeResponse({});
        this.#headers = new Headers(kConstruct);
        setHeadersGuard(this.#headers, "response");
        setHeadersList(this.#headers, this.#state.headersList);
        let bodyWithType = null;
        if (body != null) {
          const [extractedBody, type] = extractBody(body);
          bodyWithType = { body: extractedBody, type };
        }
        initializeResponse(this, init, bodyWithType);
      }
      // Returns response’s type, e.g., "cors".
      get type() {
        webidl.brandCheck(this, _Response);
        return this.#state.type;
      }
      // Returns response’s URL, if it has one; otherwise the empty string.
      get url() {
        webidl.brandCheck(this, _Response);
        const urlList = this.#state.urlList;
        const url = urlList[urlList.length - 1] ?? null;
        if (url === null) {
          return "";
        }
        return URLSerializer(url, true);
      }
      // Returns whether response was obtained through a redirect.
      get redirected() {
        webidl.brandCheck(this, _Response);
        return this.#state.urlList.length > 1;
      }
      // Returns response’s status.
      get status() {
        webidl.brandCheck(this, _Response);
        return this.#state.status;
      }
      // Returns whether response’s status is an ok status.
      get ok() {
        webidl.brandCheck(this, _Response);
        return this.#state.status >= 200 && this.#state.status <= 299;
      }
      // Returns response’s status message.
      get statusText() {
        webidl.brandCheck(this, _Response);
        return this.#state.statusText;
      }
      // Returns response’s headers as Headers.
      get headers() {
        webidl.brandCheck(this, _Response);
        return this.#headers;
      }
      get body() {
        webidl.brandCheck(this, _Response);
        return this.#state.body ? this.#state.body.stream : null;
      }
      get bodyUsed() {
        webidl.brandCheck(this, _Response);
        return !!this.#state.body && util2.isDisturbed(this.#state.body.stream);
      }
      // Returns a clone of response.
      clone() {
        webidl.brandCheck(this, _Response);
        if (bodyUnusable(this.#state)) {
          throw webidl.errors.exception({
            header: "Response.clone",
            message: "Body has already been consumed."
          });
        }
        const clonedResponse = cloneResponse(this.#state);
        if (this.#state.urlList.length !== 0 && this.#state.body?.stream) {
          streamRegistry.register(this, new WeakRef(this.#state.body.stream));
        }
        return fromInnerResponse(clonedResponse, getHeadersGuard(this.#headers));
      }
      [nodeUtil.inspect.custom](depth, options) {
        if (options.depth === null) {
          options.depth = 2;
        }
        options.colors ??= true;
        const properties = {
          status: this.status,
          statusText: this.statusText,
          headers: this.headers,
          body: this.body,
          bodyUsed: this.bodyUsed,
          ok: this.ok,
          redirected: this.redirected,
          type: this.type,
          url: this.url
        };
        return `Response ${nodeUtil.formatWithOptions(options, properties)}`;
      }
      /**
       * @param {Response} response
       */
      static getResponseHeaders(response) {
        return response.#headers;
      }
      /**
       * @param {Response} response
       * @param {Headers} newHeaders
       */
      static setResponseHeaders(response, newHeaders) {
        response.#headers = newHeaders;
      }
      /**
       * @param {Response} response
       */
      static getResponseState(response) {
        return response.#state;
      }
      /**
       * @param {Response} response
       * @param {any} newState
       */
      static setResponseState(response, newState) {
        response.#state = newState;
      }
    };
    var { getResponseHeaders, setResponseHeaders, getResponseState, setResponseState } = Response2;
    Reflect.deleteProperty(Response2, "getResponseHeaders");
    Reflect.deleteProperty(Response2, "setResponseHeaders");
    Reflect.deleteProperty(Response2, "getResponseState");
    Reflect.deleteProperty(Response2, "setResponseState");
    mixinBody(Response2, getResponseState);
    Object.defineProperties(Response2.prototype, {
      type: kEnumerableProperty,
      url: kEnumerableProperty,
      status: kEnumerableProperty,
      ok: kEnumerableProperty,
      redirected: kEnumerableProperty,
      statusText: kEnumerableProperty,
      headers: kEnumerableProperty,
      clone: kEnumerableProperty,
      body: kEnumerableProperty,
      bodyUsed: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "Response",
        configurable: true
      }
    });
    Object.defineProperties(Response2, {
      json: kEnumerableProperty,
      redirect: kEnumerableProperty,
      error: kEnumerableProperty
    });
    function cloneResponse(response) {
      if (response.internalResponse) {
        return filterResponse(
          cloneResponse(response.internalResponse),
          response.type
        );
      }
      const newResponse = makeResponse({ ...response, body: null });
      if (response.body != null) {
        newResponse.body = cloneBody(response.body);
      }
      return newResponse;
    }
    function makeResponse(init) {
      return {
        aborted: false,
        rangeRequested: false,
        timingAllowPassed: false,
        requestIncludesCredentials: false,
        type: "default",
        status: 200,
        timingInfo: null,
        cacheState: "",
        statusText: "",
        ...init,
        headersList: init?.headersList ? new HeadersList(init?.headersList) : new HeadersList(),
        urlList: init?.urlList ? [...init.urlList] : []
      };
    }
    function makeNetworkError(reason) {
      const isError = isErrorLike(reason);
      return makeResponse({
        type: "error",
        status: 0,
        error: isError ? reason : new Error(reason ? String(reason) : reason),
        aborted: reason && reason.name === "AbortError"
      });
    }
    function isNetworkError(response) {
      return (
        // A network error is a response whose type is "error",
        response.type === "error" && // status is 0
        response.status === 0
      );
    }
    function makeFilteredResponse(response, state) {
      state = {
        internalResponse: response,
        ...state
      };
      return new Proxy(response, {
        get(target, p) {
          return p in state ? state[p] : target[p];
        },
        set(target, p, value) {
          assert8(!(p in state));
          target[p] = value;
          return true;
        }
      });
    }
    function filterResponse(response, type) {
      if (type === "basic") {
        return makeFilteredResponse(response, {
          type: "basic",
          headersList: response.headersList
        });
      } else if (type === "cors") {
        return makeFilteredResponse(response, {
          type: "cors",
          headersList: response.headersList
        });
      } else if (type === "opaque") {
        return makeFilteredResponse(response, {
          type: "opaque",
          urlList: [],
          status: 0,
          statusText: "",
          body: null
        });
      } else if (type === "opaqueredirect") {
        return makeFilteredResponse(response, {
          type: "opaqueredirect",
          status: 0,
          statusText: "",
          headersList: [],
          body: null
        });
      } else {
        assert8(false);
      }
    }
    function makeAppropriateNetworkError(fetchParams, err = null) {
      assert8(isCancelled(fetchParams));
      return isAborted2(fetchParams) ? makeNetworkError(Object.assign(new DOMException("The operation was aborted.", "AbortError"), { cause: err })) : makeNetworkError(Object.assign(new DOMException("Request was cancelled."), { cause: err }));
    }
    function initializeResponse(response, init, body) {
      if (init.status !== null && (init.status < 200 || init.status > 599)) {
        throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.');
      }
      if ("statusText" in init && init.statusText != null) {
        if (!isValidReasonPhrase(String(init.statusText))) {
          throw new TypeError("Invalid statusText");
        }
      }
      if ("status" in init && init.status != null) {
        getResponseState(response).status = init.status;
      }
      if ("statusText" in init && init.statusText != null) {
        getResponseState(response).statusText = init.statusText;
      }
      if ("headers" in init && init.headers != null) {
        fill(getResponseHeaders(response), init.headers);
      }
      if (body) {
        if (nullBodyStatus.includes(response.status)) {
          throw webidl.errors.exception({
            header: "Response constructor",
            message: `Invalid response status code ${response.status}`
          });
        }
        getResponseState(response).body = body.body;
        if (body.type != null && !getResponseState(response).headersList.contains("content-type", true)) {
          getResponseState(response).headersList.append("content-type", body.type, true);
        }
      }
    }
    function fromInnerResponse(innerResponse, guard) {
      const response = new Response2(kConstruct);
      setResponseState(response, innerResponse);
      const headers = new Headers(kConstruct);
      setResponseHeaders(response, headers);
      setHeadersList(headers, innerResponse.headersList);
      setHeadersGuard(headers, guard);
      if (innerResponse.urlList.length !== 0 && innerResponse.body?.stream) {
        streamRegistry.register(response, new WeakRef(innerResponse.body.stream));
      }
      return response;
    }
    webidl.converters.XMLHttpRequestBodyInit = function(V, prefix, name) {
      if (typeof V === "string") {
        return webidl.converters.USVString(V, prefix, name);
      }
      if (webidl.is.Blob(V)) {
        return V;
      }
      if (webidl.is.BufferSource(V)) {
        return V;
      }
      if (webidl.is.FormData(V)) {
        return V;
      }
      if (webidl.is.URLSearchParams(V)) {
        return V;
      }
      return webidl.converters.DOMString(V, prefix, name);
    };
    webidl.converters.BodyInit = function(V, prefix, argument) {
      if (webidl.is.ReadableStream(V)) {
        return V;
      }
      if (V?.[Symbol.asyncIterator]) {
        return V;
      }
      return webidl.converters.XMLHttpRequestBodyInit(V, prefix, argument);
    };
    webidl.converters.ResponseInit = webidl.dictionaryConverter([
      {
        key: "status",
        converter: webidl.converters["unsigned short"],
        defaultValue: () => 200
      },
      {
        key: "statusText",
        converter: webidl.converters.ByteString,
        defaultValue: () => ""
      },
      {
        key: "headers",
        converter: webidl.converters.HeadersInit
      }
    ]);
    webidl.is.Response = webidl.util.MakeTypeAssertion(Response2);
    module.exports = {
      isNetworkError,
      makeNetworkError,
      makeResponse,
      makeAppropriateNetworkError,
      filterResponse,
      Response: Response2,
      cloneResponse,
      fromInnerResponse,
      getResponseState
    };
  }
});

// node_modules/undici/lib/web/fetch/request.js
var require_request2 = __commonJS({
  "node_modules/undici/lib/web/fetch/request.js"(exports, module) {
    "use strict";
    var { extractBody, mixinBody, cloneBody, bodyUnusable } = require_body();
    var { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = require_headers();
    var util2 = require_util();
    var nodeUtil = __require("util");
    var {
      isValidHTTPToken,
      sameOrigin,
      environmentSettingsObject
    } = require_util2();
    var {
      forbiddenMethodsSet,
      corsSafeListedMethodsSet,
      referrerPolicy,
      requestRedirect,
      requestMode,
      requestCredentials,
      requestCache,
      requestDuplex
    } = require_constants4();
    var { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util2;
    var { webidl } = require_webidl();
    var { URLSerializer } = require_data_url();
    var { kConstruct } = require_symbols();
    var assert8 = __require("assert");
    var { getMaxListeners, setMaxListeners: setMaxListeners7, defaultMaxListeners } = __require("events");
    var kAbortController = /* @__PURE__ */ Symbol("abortController");
    var requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
      signal.removeEventListener("abort", abort);
    });
    var dependentControllerMap = /* @__PURE__ */ new WeakMap();
    var abortSignalHasEventHandlerLeakWarning;
    try {
      abortSignalHasEventHandlerLeakWarning = getMaxListeners(new AbortController().signal) > 0;
    } catch {
      abortSignalHasEventHandlerLeakWarning = false;
    }
    function buildAbort(acRef) {
      return abort;
      function abort() {
        const ac = acRef.deref();
        if (ac !== void 0) {
          requestFinalizer.unregister(abort);
          this.removeEventListener("abort", abort);
          ac.abort(this.reason);
          const controllerList = dependentControllerMap.get(ac.signal);
          if (controllerList !== void 0) {
            if (controllerList.size !== 0) {
              for (const ref of controllerList) {
                const ctrl = ref.deref();
                if (ctrl !== void 0) {
                  ctrl.abort(this.reason);
                }
              }
              controllerList.clear();
            }
            dependentControllerMap.delete(ac.signal);
          }
        }
      }
    }
    var patchMethodWarning = false;
    var Request2 = class _Request {
      /** @type {AbortSignal} */
      #signal;
      /** @type {import('../../dispatcher/dispatcher')} */
      #dispatcher;
      /** @type {Headers} */
      #headers;
      #state;
      // https://fetch.spec.whatwg.org/#dom-request
      constructor(input, init = void 0) {
        webidl.util.markAsUncloneable(this);
        if (input === kConstruct) {
          return;
        }
        const prefix = "Request constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        input = webidl.converters.RequestInfo(input);
        init = webidl.converters.RequestInit(init);
        let request = null;
        let fallbackMode = null;
        const baseUrl = environmentSettingsObject.settingsObject.baseUrl;
        let signal = null;
        if (typeof input === "string") {
          this.#dispatcher = init.dispatcher;
          let parsedURL;
          try {
            parsedURL = new URL(input, baseUrl);
          } catch (err) {
            throw new TypeError("Failed to parse URL from " + input, { cause: err });
          }
          if (parsedURL.username || parsedURL.password) {
            throw new TypeError(
              "Request cannot be constructed from a URL that includes credentials: " + input
            );
          }
          request = makeRequest({ urlList: [parsedURL] });
          fallbackMode = "cors";
        } else {
          assert8(webidl.is.Request(input));
          request = input.#state;
          signal = input.#signal;
          this.#dispatcher = init.dispatcher || input.#dispatcher;
        }
        const origin = environmentSettingsObject.settingsObject.origin;
        let window = "client";
        if (request.window?.constructor?.name === "EnvironmentSettingsObject" && sameOrigin(request.window, origin)) {
          window = request.window;
        }
        if (init.window != null) {
          throw new TypeError(`'window' option '${window}' must be null`);
        }
        if ("window" in init) {
          window = "no-window";
        }
        request = makeRequest({
          // URL request’s URL.
          // undici implementation note: this is set as the first item in request's urlList in makeRequest
          // method request’s method.
          method: request.method,
          // header list A copy of request’s header list.
          // undici implementation note: headersList is cloned in makeRequest
          headersList: request.headersList,
          // unsafe-request flag Set.
          unsafeRequest: request.unsafeRequest,
          // client This’s relevant settings object.
          client: environmentSettingsObject.settingsObject,
          // window window.
          window,
          // priority request’s priority.
          priority: request.priority,
          // origin request’s origin. The propagation of the origin is only significant for navigation requests
          // being handled by a service worker. In this scenario a request can have an origin that is different
          // from the current client.
          origin: request.origin,
          // referrer request’s referrer.
          referrer: request.referrer,
          // referrer policy request’s referrer policy.
          referrerPolicy: request.referrerPolicy,
          // mode request’s mode.
          mode: request.mode,
          // credentials mode request’s credentials mode.
          credentials: request.credentials,
          // cache mode request’s cache mode.
          cache: request.cache,
          // redirect mode request’s redirect mode.
          redirect: request.redirect,
          // integrity metadata request’s integrity metadata.
          integrity: request.integrity,
          // keepalive request’s keepalive.
          keepalive: request.keepalive,
          // reload-navigation flag request’s reload-navigation flag.
          reloadNavigation: request.reloadNavigation,
          // history-navigation flag request’s history-navigation flag.
          historyNavigation: request.historyNavigation,
          // URL list A clone of request’s URL list.
          urlList: [...request.urlList]
        });
        const initHasKey = Object.keys(init).length !== 0;
        if (initHasKey) {
          if (request.mode === "navigate") {
            request.mode = "same-origin";
          }
          request.reloadNavigation = false;
          request.historyNavigation = false;
          request.origin = "client";
          request.referrer = "client";
          request.referrerPolicy = "";
          request.url = request.urlList[request.urlList.length - 1];
          request.urlList = [request.url];
        }
        if (init.referrer !== void 0) {
          const referrer = init.referrer;
          if (referrer === "") {
            request.referrer = "no-referrer";
          } else {
            let parsedReferrer;
            try {
              parsedReferrer = new URL(referrer, baseUrl);
            } catch (err) {
              throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err });
            }
            if (parsedReferrer.protocol === "about:" && parsedReferrer.hostname === "client" || origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl)) {
              request.referrer = "client";
            } else {
              request.referrer = parsedReferrer;
            }
          }
        }
        if (init.referrerPolicy !== void 0) {
          request.referrerPolicy = init.referrerPolicy;
        }
        let mode;
        if (init.mode !== void 0) {
          mode = init.mode;
        } else {
          mode = fallbackMode;
        }
        if (mode === "navigate") {
          throw webidl.errors.exception({
            header: "Request constructor",
            message: "invalid request mode navigate."
          });
        }
        if (mode != null) {
          request.mode = mode;
        }
        if (init.credentials !== void 0) {
          request.credentials = init.credentials;
        }
        if (init.cache !== void 0) {
          request.cache = init.cache;
        }
        if (request.cache === "only-if-cached" && request.mode !== "same-origin") {
          throw new TypeError(
            "'only-if-cached' can be set only with 'same-origin' mode"
          );
        }
        if (init.redirect !== void 0) {
          request.redirect = init.redirect;
        }
        if (init.integrity != null) {
          request.integrity = String(init.integrity);
        }
        if (init.keepalive !== void 0) {
          request.keepalive = Boolean(init.keepalive);
        }
        if (init.method !== void 0) {
          let method = init.method;
          const mayBeNormalized = normalizedMethodRecords[method];
          if (mayBeNormalized !== void 0) {
            request.method = mayBeNormalized;
          } else {
            if (!isValidHTTPToken(method)) {
              throw new TypeError(`'${method}' is not a valid HTTP method.`);
            }
            const upperCase = method.toUpperCase();
            if (forbiddenMethodsSet.has(upperCase)) {
              throw new TypeError(`'${method}' HTTP method is unsupported.`);
            }
            method = normalizedMethodRecordsBase[upperCase] ?? method;
            request.method = method;
          }
          if (!patchMethodWarning && request.method === "patch") {
            process.emitWarning("Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.", {
              code: "UNDICI-FETCH-patch"
            });
            patchMethodWarning = true;
          }
        }
        if (init.signal !== void 0) {
          signal = init.signal;
        }
        this.#state = request;
        const ac = new AbortController();
        this.#signal = ac.signal;
        if (signal != null) {
          if (signal.aborted) {
            ac.abort(signal.reason);
          } else {
            this[kAbortController] = ac;
            const acRef = new WeakRef(ac);
            const abort = buildAbort(acRef);
            if (abortSignalHasEventHandlerLeakWarning && getMaxListeners(signal) === defaultMaxListeners) {
              setMaxListeners7(1500, signal);
            }
            util2.addAbortListener(signal, abort);
            requestFinalizer.register(ac, { signal, abort }, abort);
          }
        }
        this.#headers = new Headers(kConstruct);
        setHeadersList(this.#headers, request.headersList);
        setHeadersGuard(this.#headers, "request");
        if (mode === "no-cors") {
          if (!corsSafeListedMethodsSet.has(request.method)) {
            throw new TypeError(
              `'${request.method} is unsupported in no-cors mode.`
            );
          }
          setHeadersGuard(this.#headers, "request-no-cors");
        }
        if (initHasKey) {
          const headersList = getHeadersList(this.#headers);
          const headers = init.headers !== void 0 ? init.headers : new HeadersList(headersList);
          headersList.clear();
          if (headers instanceof HeadersList) {
            for (const { name, value } of headers.rawValues()) {
              headersList.append(name, value, false);
            }
            headersList.cookies = headers.cookies;
          } else {
            fillHeaders(this.#headers, headers);
          }
        }
        const inputBody = webidl.is.Request(input) ? input.#state.body : null;
        if ((init.body != null || inputBody != null) && (request.method === "GET" || request.method === "HEAD")) {
          throw new TypeError("Request with GET/HEAD method cannot have body.");
        }
        let initBody = null;
        if (init.body != null) {
          const [extractedBody, contentType] = extractBody(
            init.body,
            request.keepalive
          );
          initBody = extractedBody;
          if (contentType && !getHeadersList(this.#headers).contains("content-type", true)) {
            this.#headers.append("content-type", contentType, true);
          }
        }
        const inputOrInitBody = initBody ?? inputBody;
        if (inputOrInitBody != null && inputOrInitBody.source == null) {
          if (initBody != null && init.duplex == null) {
            throw new TypeError("RequestInit: duplex option is required when sending a body.");
          }
          if (request.mode !== "same-origin" && request.mode !== "cors") {
            throw new TypeError(
              'If request is made from ReadableStream, mode should be "same-origin" or "cors"'
            );
          }
          request.useCORSPreflightFlag = true;
        }
        let finalBody = inputOrInitBody;
        if (initBody == null && inputBody != null) {
          if (bodyUnusable(input.#state)) {
            throw new TypeError(
              "Cannot construct a Request with a Request object that has already been used."
            );
          }
          const identityTransform = new TransformStream();
          inputBody.stream.pipeThrough(identityTransform);
          finalBody = {
            source: inputBody.source,
            length: inputBody.length,
            stream: identityTransform.readable
          };
        }
        this.#state.body = finalBody;
      }
      // Returns request’s HTTP method, which is "GET" by default.
      get method() {
        webidl.brandCheck(this, _Request);
        return this.#state.method;
      }
      // Returns the URL of request as a string.
      get url() {
        webidl.brandCheck(this, _Request);
        return URLSerializer(this.#state.url);
      }
      // Returns a Headers object consisting of the headers associated with request.
      // Note that headers added in the network layer by the user agent will not
      // be accounted for in this object, e.g., the "Host" header.
      get headers() {
        webidl.brandCheck(this, _Request);
        return this.#headers;
      }
      // Returns the kind of resource requested by request, e.g., "document"
      // or "script".
      get destination() {
        webidl.brandCheck(this, _Request);
        return this.#state.destination;
      }
      // Returns the referrer of request. Its value can be a same-origin URL if
      // explicitly set in init, the empty string to indicate no referrer, and
      // "about:client" when defaulting to the global’s default. This is used
      // during fetching to determine the value of the `Referer` header of the
      // request being made.
      get referrer() {
        webidl.brandCheck(this, _Request);
        if (this.#state.referrer === "no-referrer") {
          return "";
        }
        if (this.#state.referrer === "client") {
          return "about:client";
        }
        return this.#state.referrer.toString();
      }
      // Returns the referrer policy associated with request.
      // This is used during fetching to compute the value of the request’s
      // referrer.
      get referrerPolicy() {
        webidl.brandCheck(this, _Request);
        return this.#state.referrerPolicy;
      }
      // Returns the mode associated with request, which is a string indicating
      // whether the request will use CORS, or will be restricted to same-origin
      // URLs.
      get mode() {
        webidl.brandCheck(this, _Request);
        return this.#state.mode;
      }
      // Returns the credentials mode associated with request,
      // which is a string indicating whether credentials will be sent with the
      // request always, never, or only when sent to a same-origin URL.
      get credentials() {
        webidl.brandCheck(this, _Request);
        return this.#state.credentials;
      }
      // Returns the cache mode associated with request,
      // which is a string indicating how the request will
      // interact with the browser’s cache when fetching.
      get cache() {
        webidl.brandCheck(this, _Request);
        return this.#state.cache;
      }
      // Returns the redirect mode associated with request,
      // which is a string indicating how redirects for the
      // request will be handled during fetching. A request
      // will follow redirects by default.
      get redirect() {
        webidl.brandCheck(this, _Request);
        return this.#state.redirect;
      }
      // Returns request’s subresource integrity metadata, which is a
      // cryptographic hash of the resource being fetched. Its value
      // consists of multiple hashes separated by whitespace. [SRI]
      get integrity() {
        webidl.brandCheck(this, _Request);
        return this.#state.integrity;
      }
      // Returns a boolean indicating whether or not request can outlive the
      // global in which it was created.
      get keepalive() {
        webidl.brandCheck(this, _Request);
        return this.#state.keepalive;
      }
      // Returns a boolean indicating whether or not request is for a reload
      // navigation.
      get isReloadNavigation() {
        webidl.brandCheck(this, _Request);
        return this.#state.reloadNavigation;
      }
      // Returns a boolean indicating whether or not request is for a history
      // navigation (a.k.a. back-forward navigation).
      get isHistoryNavigation() {
        webidl.brandCheck(this, _Request);
        return this.#state.historyNavigation;
      }
      // Returns the signal associated with request, which is an AbortSignal
      // object indicating whether or not request has been aborted, and its
      // abort event handler.
      get signal() {
        webidl.brandCheck(this, _Request);
        return this.#signal;
      }
      get body() {
        webidl.brandCheck(this, _Request);
        return this.#state.body ? this.#state.body.stream : null;
      }
      get bodyUsed() {
        webidl.brandCheck(this, _Request);
        return !!this.#state.body && util2.isDisturbed(this.#state.body.stream);
      }
      get duplex() {
        webidl.brandCheck(this, _Request);
        return "half";
      }
      // Returns a clone of request.
      clone() {
        webidl.brandCheck(this, _Request);
        if (bodyUnusable(this.#state)) {
          throw new TypeError("unusable");
        }
        const clonedRequest = cloneRequest(this.#state);
        const ac = new AbortController();
        if (this.signal.aborted) {
          ac.abort(this.signal.reason);
        } else {
          let list = dependentControllerMap.get(this.signal);
          if (list === void 0) {
            list = /* @__PURE__ */ new Set();
            dependentControllerMap.set(this.signal, list);
          }
          const acRef = new WeakRef(ac);
          list.add(acRef);
          util2.addAbortListener(
            ac.signal,
            buildAbort(acRef)
          );
        }
        return fromInnerRequest(clonedRequest, this.#dispatcher, ac.signal, getHeadersGuard(this.#headers));
      }
      [nodeUtil.inspect.custom](depth, options) {
        if (options.depth === null) {
          options.depth = 2;
        }
        options.colors ??= true;
        const properties = {
          method: this.method,
          url: this.url,
          headers: this.headers,
          destination: this.destination,
          referrer: this.referrer,
          referrerPolicy: this.referrerPolicy,
          mode: this.mode,
          credentials: this.credentials,
          cache: this.cache,
          redirect: this.redirect,
          integrity: this.integrity,
          keepalive: this.keepalive,
          isReloadNavigation: this.isReloadNavigation,
          isHistoryNavigation: this.isHistoryNavigation,
          signal: this.signal
        };
        return `Request ${nodeUtil.formatWithOptions(options, properties)}`;
      }
      /**
       * @param {Request} request
       * @param {AbortSignal} newSignal
       */
      static setRequestSignal(request, newSignal) {
        request.#signal = newSignal;
        return request;
      }
      /**
       * @param {Request} request
       */
      static getRequestDispatcher(request) {
        return request.#dispatcher;
      }
      /**
       * @param {Request} request
       * @param {import('../../dispatcher/dispatcher')} newDispatcher
       */
      static setRequestDispatcher(request, newDispatcher) {
        request.#dispatcher = newDispatcher;
      }
      /**
       * @param {Request} request
       * @param {Headers} newHeaders
       */
      static setRequestHeaders(request, newHeaders) {
        request.#headers = newHeaders;
      }
      /**
       * @param {Request} request
       */
      static getRequestState(request) {
        return request.#state;
      }
      /**
       * @param {Request} request
       * @param {any} newState
       */
      static setRequestState(request, newState) {
        request.#state = newState;
      }
    };
    var { setRequestSignal, getRequestDispatcher, setRequestDispatcher, setRequestHeaders, getRequestState, setRequestState } = Request2;
    Reflect.deleteProperty(Request2, "setRequestSignal");
    Reflect.deleteProperty(Request2, "getRequestDispatcher");
    Reflect.deleteProperty(Request2, "setRequestDispatcher");
    Reflect.deleteProperty(Request2, "setRequestHeaders");
    Reflect.deleteProperty(Request2, "getRequestState");
    Reflect.deleteProperty(Request2, "setRequestState");
    mixinBody(Request2, getRequestState);
    function makeRequest(init) {
      return {
        method: init.method ?? "GET",
        localURLsOnly: init.localURLsOnly ?? false,
        unsafeRequest: init.unsafeRequest ?? false,
        body: init.body ?? null,
        client: init.client ?? null,
        reservedClient: init.reservedClient ?? null,
        replacesClientId: init.replacesClientId ?? "",
        window: init.window ?? "client",
        keepalive: init.keepalive ?? false,
        serviceWorkers: init.serviceWorkers ?? "all",
        initiator: init.initiator ?? "",
        destination: init.destination ?? "",
        priority: init.priority ?? null,
        origin: init.origin ?? "client",
        policyContainer: init.policyContainer ?? "client",
        referrer: init.referrer ?? "client",
        referrerPolicy: init.referrerPolicy ?? "",
        mode: init.mode ?? "no-cors",
        useCORSPreflightFlag: init.useCORSPreflightFlag ?? false,
        credentials: init.credentials ?? "same-origin",
        useCredentials: init.useCredentials ?? false,
        cache: init.cache ?? "default",
        redirect: init.redirect ?? "follow",
        integrity: init.integrity ?? "",
        cryptoGraphicsNonceMetadata: init.cryptoGraphicsNonceMetadata ?? "",
        parserMetadata: init.parserMetadata ?? "",
        reloadNavigation: init.reloadNavigation ?? false,
        historyNavigation: init.historyNavigation ?? false,
        userActivation: init.userActivation ?? false,
        taintedOrigin: init.taintedOrigin ?? false,
        redirectCount: init.redirectCount ?? 0,
        responseTainting: init.responseTainting ?? "basic",
        preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false,
        done: init.done ?? false,
        timingAllowFailed: init.timingAllowFailed ?? false,
        useURLCredentials: init.useURLCredentials ?? void 0,
        traversableForUserPrompts: init.traversableForUserPrompts ?? "client",
        urlList: init.urlList,
        url: init.urlList[0],
        headersList: init.headersList ? new HeadersList(init.headersList) : new HeadersList()
      };
    }
    function cloneRequest(request) {
      const newRequest = makeRequest({ ...request, body: null });
      if (request.body != null) {
        newRequest.body = cloneBody(request.body);
      }
      return newRequest;
    }
    function fromInnerRequest(innerRequest, dispatcher, signal, guard) {
      const request = new Request2(kConstruct);
      setRequestState(request, innerRequest);
      setRequestDispatcher(request, dispatcher);
      setRequestSignal(request, signal);
      const headers = new Headers(kConstruct);
      setRequestHeaders(request, headers);
      setHeadersList(headers, innerRequest.headersList);
      setHeadersGuard(headers, guard);
      return request;
    }
    Object.defineProperties(Request2.prototype, {
      method: kEnumerableProperty,
      url: kEnumerableProperty,
      headers: kEnumerableProperty,
      redirect: kEnumerableProperty,
      clone: kEnumerableProperty,
      signal: kEnumerableProperty,
      duplex: kEnumerableProperty,
      destination: kEnumerableProperty,
      body: kEnumerableProperty,
      bodyUsed: kEnumerableProperty,
      isHistoryNavigation: kEnumerableProperty,
      isReloadNavigation: kEnumerableProperty,
      keepalive: kEnumerableProperty,
      integrity: kEnumerableProperty,
      cache: kEnumerableProperty,
      credentials: kEnumerableProperty,
      attribute: kEnumerableProperty,
      referrerPolicy: kEnumerableProperty,
      referrer: kEnumerableProperty,
      mode: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "Request",
        configurable: true
      }
    });
    webidl.is.Request = webidl.util.MakeTypeAssertion(Request2);
    webidl.converters.RequestInfo = function(V) {
      if (typeof V === "string") {
        return webidl.converters.USVString(V);
      }
      if (webidl.is.Request(V)) {
        return V;
      }
      return webidl.converters.USVString(V);
    };
    webidl.converters.RequestInit = webidl.dictionaryConverter([
      {
        key: "method",
        converter: webidl.converters.ByteString
      },
      {
        key: "headers",
        converter: webidl.converters.HeadersInit
      },
      {
        key: "body",
        converter: webidl.nullableConverter(
          webidl.converters.BodyInit
        )
      },
      {
        key: "referrer",
        converter: webidl.converters.USVString
      },
      {
        key: "referrerPolicy",
        converter: webidl.converters.DOMString,
        // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy
        allowedValues: referrerPolicy
      },
      {
        key: "mode",
        converter: webidl.converters.DOMString,
        // https://fetch.spec.whatwg.org/#concept-request-mode
        allowedValues: requestMode
      },
      {
        key: "credentials",
        converter: webidl.converters.DOMString,
        // https://fetch.spec.whatwg.org/#requestcredentials
        allowedValues: requestCredentials
      },
      {
        key: "cache",
        converter: webidl.converters.DOMString,
        // https://fetch.spec.whatwg.org/#requestcache
        allowedValues: requestCache
      },
      {
        key: "redirect",
        converter: webidl.converters.DOMString,
        // https://fetch.spec.whatwg.org/#requestredirect
        allowedValues: requestRedirect
      },
      {
        key: "integrity",
        converter: webidl.converters.DOMString
      },
      {
        key: "keepalive",
        converter: webidl.converters.boolean
      },
      {
        key: "signal",
        converter: webidl.nullableConverter(
          (signal) => webidl.converters.AbortSignal(
            signal,
            "RequestInit",
            "signal"
          )
        )
      },
      {
        key: "window",
        converter: webidl.converters.any
      },
      {
        key: "duplex",
        converter: webidl.converters.DOMString,
        allowedValues: requestDuplex
      },
      {
        key: "dispatcher",
        // undici specific option
        converter: webidl.converters.any
      },
      {
        key: "priority",
        converter: webidl.converters.DOMString,
        allowedValues: ["high", "low", "auto"],
        defaultValue: () => "auto"
      }
    ]);
    module.exports = {
      Request: Request2,
      makeRequest,
      fromInnerRequest,
      cloneRequest,
      getRequestDispatcher,
      getRequestState
    };
  }
});

// node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js
var require_subresource_integrity = __commonJS({
  "node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var { runtimeFeatures } = require_runtime_features();
    var validSRIHashAlgorithmTokenSet = /* @__PURE__ */ new Map([["sha256", 0], ["sha384", 1], ["sha512", 2]]);
    var crypto6;
    if (runtimeFeatures.has("crypto")) {
      crypto6 = __require("crypto");
      const cryptoHashes = crypto6.getHashes();
      if (cryptoHashes.length === 0) {
        validSRIHashAlgorithmTokenSet.clear();
      }
      for (const algorithm of validSRIHashAlgorithmTokenSet.keys()) {
        if (cryptoHashes.includes(algorithm) === false) {
          validSRIHashAlgorithmTokenSet.delete(algorithm);
        }
      }
    } else {
      validSRIHashAlgorithmTokenSet.clear();
    }
    var getSRIHashAlgorithmIndex = (
      /** @type {GetSRIHashAlgorithmIndex} */
      Map.prototype.get.bind(
        validSRIHashAlgorithmTokenSet
      )
    );
    var isValidSRIHashAlgorithm = (
      /** @type {IsValidSRIHashAlgorithm} */
      Map.prototype.has.bind(validSRIHashAlgorithmTokenSet)
    );
    var bytesMatch = runtimeFeatures.has("crypto") === false || validSRIHashAlgorithmTokenSet.size === 0 ? () => true : (bytes, metadataList) => {
      const parsedMetadata = parseMetadata(metadataList);
      if (parsedMetadata.length === 0) {
        return true;
      }
      const metadata = getStrongestMetadata(parsedMetadata);
      for (const item of metadata) {
        const algorithm = item.alg;
        const expectedValue = item.val;
        const actualValue = applyAlgorithmToBytes(algorithm, bytes);
        if (caseSensitiveMatch(actualValue, expectedValue)) {
          return true;
        }
      }
      return false;
    };
    function getStrongestMetadata(metadataList) {
      const result = [];
      let strongest = null;
      for (const item of metadataList) {
        assert8(isValidSRIHashAlgorithm(item.alg), "Invalid SRI hash algorithm token");
        if (result.length === 0) {
          result.push(item);
          strongest = item;
          continue;
        }
        const currentAlgorithm = (
          /** @type {Metadata} */
          strongest.alg
        );
        const currentAlgorithmIndex = getSRIHashAlgorithmIndex(currentAlgorithm);
        const newAlgorithm = item.alg;
        const newAlgorithmIndex = getSRIHashAlgorithmIndex(newAlgorithm);
        if (newAlgorithmIndex < currentAlgorithmIndex) {
          continue;
        } else if (newAlgorithmIndex > currentAlgorithmIndex) {
          strongest = item;
          result[0] = item;
          result.length = 1;
        } else {
          result.push(item);
        }
      }
      return result;
    }
    function parseMetadata(metadata) {
      const result = [];
      for (const item of metadata.split(" ")) {
        const expressionAndOptions = item.split("?", 1);
        const algorithmExpression = expressionAndOptions[0];
        let base64Value = "";
        const algorithmAndValue = [algorithmExpression.slice(0, 6), algorithmExpression.slice(7)];
        const algorithm = algorithmAndValue[0];
        if (!isValidSRIHashAlgorithm(algorithm)) {
          continue;
        }
        if (algorithmAndValue[1]) {
          base64Value = algorithmAndValue[1];
        }
        const metadata2 = {
          alg: algorithm,
          val: base64Value
        };
        result.push(metadata2);
      }
      return result;
    }
    var applyAlgorithmToBytes = (algorithm, bytes) => {
      return crypto6.hash(algorithm, bytes, "base64");
    };
    function caseSensitiveMatch(actualValue, expectedValue) {
      let actualValueLength = actualValue.length;
      if (actualValueLength !== 0 && actualValue[actualValueLength - 1] === "=") {
        actualValueLength -= 1;
      }
      if (actualValueLength !== 0 && actualValue[actualValueLength - 1] === "=") {
        actualValueLength -= 1;
      }
      let expectedValueLength = expectedValue.length;
      if (expectedValueLength !== 0 && expectedValue[expectedValueLength - 1] === "=") {
        expectedValueLength -= 1;
      }
      if (expectedValueLength !== 0 && expectedValue[expectedValueLength - 1] === "=") {
        expectedValueLength -= 1;
      }
      if (actualValueLength !== expectedValueLength) {
        return false;
      }
      for (let i = 0; i < actualValueLength; ++i) {
        if (actualValue[i] === expectedValue[i] || actualValue[i] === "+" && expectedValue[i] === "-" || actualValue[i] === "/" && expectedValue[i] === "_") {
          continue;
        }
        return false;
      }
      return true;
    }
    module.exports = {
      applyAlgorithmToBytes,
      bytesMatch,
      caseSensitiveMatch,
      isValidSRIHashAlgorithm,
      getStrongestMetadata,
      parseMetadata
    };
  }
});

// node_modules/undici/lib/web/fetch/index.js
var require_fetch = __commonJS({
  "node_modules/undici/lib/web/fetch/index.js"(exports, module) {
    "use strict";
    var {
      makeNetworkError,
      makeAppropriateNetworkError,
      filterResponse,
      makeResponse,
      fromInnerResponse,
      getResponseState
    } = require_response();
    var { HeadersList } = require_headers();
    var { Request: Request2, cloneRequest, getRequestDispatcher, getRequestState } = require_request2();
    var zlib = __require("zlib");
    var {
      makePolicyContainer,
      clonePolicyContainer,
      requestBadPort,
      TAOCheck,
      appendRequestOriginHeader,
      responseLocationURL,
      requestCurrentURL,
      setRequestReferrerPolicyOnRedirect,
      tryUpgradeRequestToAPotentiallyTrustworthyURL,
      createOpaqueTimingInfo,
      appendFetchMetadata,
      corsCheck,
      crossOriginResourcePolicyCheck,
      determineRequestsReferrer,
      coarsenedSharedCurrentTime,
      sameOrigin,
      isCancelled,
      isAborted: isAborted2,
      isErrorLike,
      fullyReadBody,
      readableStreamClose,
      urlIsLocal,
      urlIsHttpHttpsScheme,
      urlHasHttpsScheme,
      clampAndCoarsenConnectionTimingInfo,
      simpleRangeHeaderValue,
      buildContentRange,
      createInflate,
      extractMimeType,
      hasAuthenticationEntry,
      includesCredentials,
      isTraversableNavigable
    } = require_util2();
    var assert8 = __require("assert");
    var { safelyExtractBody, extractBody } = require_body();
    var {
      redirectStatusSet,
      nullBodyStatus,
      safeMethodsSet,
      requestBodyHeader,
      subresourceSet
    } = require_constants4();
    var EE = __require("events");
    var { Readable, pipeline, finished: finished2, isErrored, isReadable } = __require("stream");
    var { addAbortListener, bufferToLowerCasedHeaderName } = require_util();
    var { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require_data_url();
    var { getGlobalDispatcher } = require_global2();
    var { webidl } = require_webidl();
    var { STATUS_CODES } = __require("http");
    var { bytesMatch } = require_subresource_integrity();
    var { isomorphicEncode } = require_infra();
    var GET_OR_HEAD = ["GET", "HEAD"];
    var defaultUserAgent = typeof __UNDICI_IS_NODE__ !== "undefined" || typeof esbuildDetection !== "undefined" ? "node" : "undici";
    var resolveObjectURL;
    function appendHeadersListFromResponseHeaders(headersList, headers, rawHeaders) {
      if (Array.isArray(rawHeaders)) {
        for (let i = 0; i < rawHeaders.length; i += 2) {
          const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i]);
          const value = rawHeaders[i + 1];
          if (Array.isArray(value) && !Buffer.isBuffer(value)) {
            for (const val of value) {
              headersList.append(nameStr, val.toString("latin1"), true);
            }
          } else {
            headersList.append(nameStr, value.toString("latin1"), true);
          }
        }
        return;
      }
      for (const [name, value] of Object.entries(headers ?? {})) {
        if (Array.isArray(value)) {
          for (const entry of value) {
            headersList.append(name, `${entry}`, true);
          }
        } else {
          headersList.append(name, `${value}`, true);
        }
      }
    }
    var Fetch = class extends EE {
      constructor(dispatcher) {
        super();
        this.dispatcher = dispatcher;
        this.connection = null;
        this.dump = false;
        this.state = "ongoing";
      }
      terminate(reason) {
        if (this.state !== "ongoing") {
          return;
        }
        this.state = "terminated";
        this.connection?.destroy(reason);
        this.emit("terminated", reason);
      }
      // https://fetch.spec.whatwg.org/#fetch-controller-abort
      abort(error) {
        if (this.state !== "ongoing") {
          return;
        }
        this.state = "aborted";
        if (!error) {
          error = new DOMException("The operation was aborted.", "AbortError");
        }
        this.serializedAbortReason = error;
        this.connection?.destroy(error);
        this.emit("terminated", error);
      }
    };
    function handleFetchDone(response) {
      finalizeAndReportTiming(response, "fetch");
    }
    function fetch2(input, init = void 0) {
      webidl.argumentLengthCheck(arguments, 1, "globalThis.fetch");
      let p = Promise.withResolvers();
      let requestObject;
      try {
        requestObject = new Request2(input, init);
      } catch (e7) {
        p.reject(e7);
        return p.promise;
      }
      const request = getRequestState(requestObject);
      if (requestObject.signal.aborted) {
        abortFetch(p, request, null, requestObject.signal.reason, null);
        return p.promise;
      }
      const globalObject = request.client.globalObject;
      if (globalObject?.constructor?.name === "ServiceWorkerGlobalScope") {
        request.serviceWorkers = "none";
      }
      let responseObject = null;
      let locallyAborted = false;
      let controller = null;
      addAbortListener(
        requestObject.signal,
        () => {
          locallyAborted = true;
          assert8(controller != null);
          controller.abort(requestObject.signal.reason);
          const realResponse = responseObject?.deref();
          abortFetch(p, request, realResponse, requestObject.signal.reason, controller.controller);
        }
      );
      const processResponse = (response) => {
        if (locallyAborted) {
          return;
        }
        if (response.aborted) {
          abortFetch(p, request, responseObject, controller.serializedAbortReason, controller.controller);
          return;
        }
        if (response.type === "error") {
          p.reject(new TypeError("fetch failed", { cause: response.error }));
          return;
        }
        responseObject = new WeakRef(fromInnerResponse(response, "immutable"));
        p.resolve(responseObject.deref());
        p = null;
      };
      controller = fetching({
        request,
        processResponseEndOfBody: handleFetchDone,
        processResponse,
        dispatcher: getRequestDispatcher(requestObject),
        // undici
        // Keep requestObject alive to prevent its AbortController from being GC'd
        // See https://github.com/nodejs/undici/issues/4627
        requestObject
      });
      return p.promise;
    }
    function finalizeAndReportTiming(response, initiatorType = "other") {
      if (response.type === "error" && response.aborted) {
        return;
      }
      if (!response.urlList?.length) {
        return;
      }
      const originalURL = response.urlList[0];
      let timingInfo = response.timingInfo;
      let cacheState = response.cacheState;
      if (!urlIsHttpHttpsScheme(originalURL)) {
        return;
      }
      if (timingInfo === null) {
        return;
      }
      if (!response.timingAllowPassed) {
        timingInfo = createOpaqueTimingInfo({
          startTime: timingInfo.startTime
        });
        cacheState = "";
      }
      timingInfo.endTime = coarsenedSharedCurrentTime();
      response.timingInfo = timingInfo;
      markResourceTiming(
        timingInfo,
        originalURL.href,
        initiatorType,
        globalThis,
        cacheState,
        "",
        // bodyType
        response.status
      );
    }
    var markResourceTiming = performance.markResourceTiming;
    function abortFetch(p, request, responseObject, error, controller) {
      if (p) {
        p.reject(error);
      }
      if (request.body?.stream != null && isReadable(request.body.stream)) {
        request.body.stream.cancel(error).catch((err) => {
          if (err.code === "ERR_INVALID_STATE") {
            return;
          }
          throw err;
        });
      }
      if (responseObject == null) {
        return;
      }
      const response = getResponseState(responseObject);
      if (response.body?.stream != null && isReadable(response.body.stream)) {
        controller.error(error);
      }
    }
    function fetching({
      request,
      processRequestBodyChunkLength,
      processRequestEndOfBody,
      processResponse,
      processResponseEndOfBody,
      processResponseConsumeBody,
      useParallelQueue = false,
      dispatcher = getGlobalDispatcher(),
      // undici
      requestObject = null
      // Keep alive to prevent AbortController GC, see #4627
    }) {
      assert8(dispatcher);
      let taskDestination = null;
      let crossOriginIsolatedCapability = false;
      if (request.client != null) {
        taskDestination = request.client.globalObject;
        crossOriginIsolatedCapability = request.client.crossOriginIsolatedCapability;
      }
      const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability);
      const timingInfo = createOpaqueTimingInfo({
        startTime: currentTime
      });
      const fetchParams = {
        controller: new Fetch(dispatcher),
        request,
        timingInfo,
        processRequestBodyChunkLength,
        processRequestEndOfBody,
        processResponse,
        processResponseConsumeBody,
        processResponseEndOfBody,
        taskDestination,
        crossOriginIsolatedCapability,
        // Keep requestObject alive to prevent its AbortController from being GC'd
        requestObject
      };
      assert8(!request.body || request.body.stream);
      if (request.window === "client") {
        request.window = request.client?.globalObject?.constructor?.name === "Window" ? request.client : "no-window";
      }
      if (request.origin === "client") {
        request.origin = request.client.origin;
      }
      if (request.policyContainer === "client") {
        if (request.client != null) {
          request.policyContainer = clonePolicyContainer(
            request.client.policyContainer
          );
        } else {
          request.policyContainer = makePolicyContainer();
        }
      }
      if (!request.headersList.contains("accept", true)) {
        const value = "*/*";
        request.headersList.append("accept", value, true);
      }
      if (!request.headersList.contains("accept-language", true)) {
        request.headersList.append("accept-language", "*", true);
      }
      if (request.priority === null) {
      }
      if (subresourceSet.has(request.destination)) {
      }
      mainFetch(fetchParams, false);
      return fetchParams.controller;
    }
    async function mainFetch(fetchParams, recursive) {
      try {
        const request = fetchParams.request;
        let response = null;
        if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {
          response = makeNetworkError("local URLs only");
        }
        tryUpgradeRequestToAPotentiallyTrustworthyURL(request);
        if (requestBadPort(request) === "blocked") {
          response = makeNetworkError("bad port");
        }
        if (request.referrerPolicy === "") {
          request.referrerPolicy = request.policyContainer.referrerPolicy;
        }
        if (request.referrer !== "no-referrer") {
          request.referrer = determineRequestsReferrer(request);
        }
        if (response === null) {
          const currentURL = requestCurrentURL(request);
          if (
            // - request’s current URL’s origin is same origin with request’s origin,
            //   and request’s response tainting is "basic"
            sameOrigin(currentURL, request.url) && request.responseTainting === "basic" || // request’s current URL’s scheme is "data"
            currentURL.protocol === "data:" || // - request’s mode is "navigate" or "websocket"
            (request.mode === "navigate" || request.mode === "websocket")
          ) {
            request.responseTainting = "basic";
            response = await schemeFetch(fetchParams);
          } else if (request.mode === "same-origin") {
            response = makeNetworkError('request mode cannot be "same-origin"');
          } else if (request.mode === "no-cors") {
            if (request.redirect !== "follow") {
              response = makeNetworkError(
                'redirect mode cannot be "follow" for "no-cors" request'
              );
            } else {
              request.responseTainting = "opaque";
              response = await schemeFetch(fetchParams);
            }
          } else if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
            response = makeNetworkError("URL scheme must be a HTTP(S) scheme");
          } else {
            request.responseTainting = "cors";
            response = await httpFetch(fetchParams);
          }
        }
        if (recursive) {
          return response;
        }
        if (response.status !== 0 && !response.internalResponse) {
          if (request.responseTainting === "cors") {
          }
          if (request.responseTainting === "basic") {
            response = filterResponse(response, "basic");
          } else if (request.responseTainting === "cors") {
            response = filterResponse(response, "cors");
          } else if (request.responseTainting === "opaque") {
            response = filterResponse(response, "opaque");
          } else {
            assert8(false);
          }
        }
        let internalResponse = response.status === 0 ? response : response.internalResponse;
        if (internalResponse.urlList.length === 0) {
          internalResponse.urlList.push(...request.urlList);
        }
        if (!request.timingAllowFailed) {
          response.timingAllowPassed = true;
        }
        if (response.type === "opaque" && internalResponse.status === 206 && internalResponse.rangeRequested && !request.headers.contains("range", true)) {
          response = internalResponse = makeNetworkError();
        }
        if (response.status !== 0 && (request.method === "HEAD" || request.method === "CONNECT" || nullBodyStatus.includes(internalResponse.status))) {
          internalResponse.body = null;
          fetchParams.controller.dump = true;
        }
        if (request.integrity) {
          const processBodyError = (reason) => fetchFinale(fetchParams, makeNetworkError(reason));
          if (request.responseTainting === "opaque" || response.body == null) {
            processBodyError(response.error);
            return;
          }
          const processBody = (bytes) => {
            if (!bytesMatch(bytes, request.integrity)) {
              processBodyError("integrity mismatch");
              return;
            }
            response.body = safelyExtractBody(bytes)[0];
            fetchFinale(fetchParams, response);
          };
          fullyReadBody(response.body, processBody, processBodyError);
        } else {
          fetchFinale(fetchParams, response);
        }
      } catch (err) {
        fetchParams.controller.terminate(err);
      }
    }
    function schemeFetch(fetchParams) {
      if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
        return Promise.resolve(makeAppropriateNetworkError(fetchParams));
      }
      const { request } = fetchParams;
      const { protocol: scheme } = requestCurrentURL(request);
      switch (scheme) {
        case "about:": {
          return Promise.resolve(makeNetworkError("about scheme is not supported"));
        }
        case "blob:": {
          if (!resolveObjectURL) {
            resolveObjectURL = __require("buffer").resolveObjectURL;
          }
          const blobURLEntry = requestCurrentURL(request);
          if (blobURLEntry.search.length !== 0) {
            return Promise.resolve(makeNetworkError("NetworkError when attempting to fetch resource."));
          }
          const blob = resolveObjectURL(blobURLEntry.toString());
          if (request.method !== "GET" || !webidl.is.Blob(blob)) {
            return Promise.resolve(makeNetworkError("invalid method"));
          }
          const response = makeResponse();
          const fullLength = blob.size;
          const serializedFullLength = isomorphicEncode(`${fullLength}`);
          const type = blob.type;
          if (!request.headersList.contains("range", true)) {
            const bodyWithType = extractBody(blob);
            response.statusText = "OK";
            response.body = bodyWithType[0];
            response.headersList.set("content-length", serializedFullLength, true);
            response.headersList.set("content-type", type, true);
          } else {
            response.rangeRequested = true;
            const rangeHeader = request.headersList.get("range", true);
            const rangeValue = simpleRangeHeaderValue(rangeHeader, true);
            if (rangeValue === "failure") {
              return Promise.resolve(makeNetworkError("failed to fetch the data URL"));
            }
            let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue;
            if (rangeStart === null) {
              rangeStart = fullLength - rangeEnd;
              rangeEnd = rangeStart + rangeEnd - 1;
            } else {
              if (rangeStart >= fullLength) {
                return Promise.resolve(makeNetworkError("Range start is greater than the blob's size."));
              }
              if (rangeEnd === null || rangeEnd >= fullLength) {
                rangeEnd = fullLength - 1;
              }
            }
            const slicedBlob = blob.slice(rangeStart, rangeEnd + 1, type);
            const slicedBodyWithType = extractBody(slicedBlob);
            response.body = slicedBodyWithType[0];
            const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`);
            const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength);
            response.status = 206;
            response.statusText = "Partial Content";
            response.headersList.set("content-length", serializedSlicedLength, true);
            response.headersList.set("content-type", type, true);
            response.headersList.set("content-range", contentRange, true);
          }
          return Promise.resolve(response);
        }
        case "data:": {
          const currentURL = requestCurrentURL(request);
          const dataURLStruct = dataURLProcessor(currentURL);
          if (dataURLStruct === "failure") {
            return Promise.resolve(makeNetworkError("failed to fetch the data URL"));
          }
          const mimeType = serializeAMimeType(dataURLStruct.mimeType);
          return Promise.resolve(makeResponse({
            statusText: "OK",
            headersList: [
              ["content-type", { name: "Content-Type", value: mimeType }]
            ],
            body: safelyExtractBody(dataURLStruct.body)[0]
          }));
        }
        case "file:": {
          return Promise.resolve(makeNetworkError("not implemented... yet..."));
        }
        case "http:":
        case "https:": {
          return httpFetch(fetchParams).catch((err) => makeNetworkError(err));
        }
        default: {
          return Promise.resolve(makeNetworkError("unknown scheme"));
        }
      }
    }
    function finalizeResponse(fetchParams, response) {
      fetchParams.request.done = true;
      if (fetchParams.processResponseDone != null) {
        queueMicrotask(() => fetchParams.processResponseDone(response));
      }
    }
    function fetchFinale(fetchParams, response) {
      let timingInfo = fetchParams.timingInfo;
      const processResponseEndOfBody = () => {
        const unsafeEndTime = Date.now();
        if (fetchParams.request.destination === "document") {
          fetchParams.controller.fullTimingInfo = timingInfo;
        }
        fetchParams.controller.reportTimingSteps = () => {
          if (!urlIsHttpHttpsScheme(fetchParams.request.url)) {
            return;
          }
          timingInfo.endTime = unsafeEndTime;
          let cacheState = response.cacheState;
          const bodyInfo = response.bodyInfo;
          if (!response.timingAllowPassed) {
            timingInfo = createOpaqueTimingInfo(timingInfo);
            cacheState = "";
          }
          let responseStatus = 0;
          if (fetchParams.request.mode !== "navigate" || !response.hasCrossOriginRedirects) {
            responseStatus = response.status;
            const mimeType = extractMimeType(response.headersList);
            if (mimeType !== "failure") {
              bodyInfo.contentType = minimizeSupportedMimeType(mimeType);
            }
          }
          if (fetchParams.request.initiatorType != null) {
            markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus);
          }
        };
        const processResponseEndOfBodyTask = () => {
          fetchParams.request.done = true;
          if (fetchParams.processResponseEndOfBody != null) {
            queueMicrotask(() => fetchParams.processResponseEndOfBody(response));
          }
          if (fetchParams.request.initiatorType != null) {
            fetchParams.controller.reportTimingSteps();
          }
        };
        queueMicrotask(() => processResponseEndOfBodyTask());
      };
      if (fetchParams.processResponse != null) {
        queueMicrotask(() => {
          fetchParams.processResponse(response);
          fetchParams.processResponse = null;
        });
      }
      const internalResponse = response.type === "error" ? response : response.internalResponse ?? response;
      if (internalResponse.body == null) {
        processResponseEndOfBody();
      } else {
        finished2(internalResponse.body.stream, () => {
          processResponseEndOfBody();
        });
      }
    }
    async function httpFetch(fetchParams) {
      const request = fetchParams.request;
      let response = null;
      let actualResponse = null;
      const timingInfo = fetchParams.timingInfo;
      if (request.serviceWorkers === "all") {
      }
      if (response === null) {
        if (request.redirect === "follow") {
          request.serviceWorkers = "none";
        }
        actualResponse = response = await httpNetworkOrCacheFetch(fetchParams);
        if (request.responseTainting === "cors" && corsCheck(request, response) === "failure") {
          return makeNetworkError("cors failure");
        }
        if (TAOCheck(request, response) === "failure") {
          request.timingAllowFailed = true;
        }
      }
      if ((request.responseTainting === "opaque" || response.type === "opaque") && crossOriginResourcePolicyCheck(
        request.origin,
        request.client,
        request.destination,
        actualResponse
      ) === "blocked") {
        return makeNetworkError("blocked");
      }
      if (redirectStatusSet.has(actualResponse.status)) {
        if (request.redirect !== "manual") {
          fetchParams.controller.connection.destroy(void 0, false);
        }
        if (request.redirect === "error") {
          response = makeNetworkError("unexpected redirect");
        } else if (request.redirect === "manual") {
          response = actualResponse;
        } else if (request.redirect === "follow") {
          response = await httpRedirectFetch(fetchParams, response);
        } else {
          assert8(false);
        }
      }
      response.timingInfo = timingInfo;
      return response;
    }
    function httpRedirectFetch(fetchParams, response) {
      const request = fetchParams.request;
      const actualResponse = response.internalResponse ? response.internalResponse : response;
      let locationURL;
      try {
        locationURL = responseLocationURL(
          actualResponse,
          requestCurrentURL(request).hash
        );
        if (locationURL == null) {
          return response;
        }
      } catch (err) {
        return Promise.resolve(makeNetworkError(err));
      }
      if (!urlIsHttpHttpsScheme(locationURL)) {
        return Promise.resolve(makeNetworkError("URL scheme must be a HTTP(S) scheme"));
      }
      if (request.redirectCount === 20) {
        return Promise.resolve(makeNetworkError("redirect count exceeded"));
      }
      request.redirectCount += 1;
      if (request.mode === "cors" && (locationURL.username || locationURL.password) && !sameOrigin(request, locationURL)) {
        return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'));
      }
      if (request.responseTainting === "cors" && (locationURL.username || locationURL.password)) {
        return Promise.resolve(makeNetworkError(
          'URL cannot contain credentials for request mode "cors"'
        ));
      }
      if (actualResponse.status !== 303 && request.body != null && request.body.source == null) {
        return Promise.resolve(makeNetworkError());
      }
      if ([301, 302].includes(actualResponse.status) && request.method === "POST" || actualResponse.status === 303 && !GET_OR_HEAD.includes(request.method)) {
        request.method = "GET";
        request.body = null;
        for (const headerName of requestBodyHeader) {
          request.headersList.delete(headerName);
        }
      }
      if (!sameOrigin(requestCurrentURL(request), locationURL)) {
        request.headersList.delete("authorization", true);
        request.headersList.delete("proxy-authorization", true);
        request.headersList.delete("cookie", true);
        request.headersList.delete("host", true);
      }
      if (request.body != null) {
        assert8(request.body.source != null);
        request.body = safelyExtractBody(request.body.source)[0];
      }
      const timingInfo = fetchParams.timingInfo;
      timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
      if (timingInfo.redirectStartTime === 0) {
        timingInfo.redirectStartTime = timingInfo.startTime;
      }
      request.urlList.push(locationURL);
      setRequestReferrerPolicyOnRedirect(request, actualResponse);
      return mainFetch(fetchParams, true);
    }
    async function httpNetworkOrCacheFetch(fetchParams, isAuthenticationFetch = false, isNewConnectionFetch = false) {
      const request = fetchParams.request;
      let httpFetchParams = null;
      let httpRequest = null;
      let response = null;
      const httpCache = null;
      const revalidatingFlag = false;
      if (request.window === "no-window" && request.redirect === "error") {
        httpFetchParams = fetchParams;
        httpRequest = request;
      } else {
        httpRequest = cloneRequest(request);
        httpFetchParams = { ...fetchParams };
        httpFetchParams.request = httpRequest;
      }
      const includeCredentials = request.credentials === "include" || request.credentials === "same-origin" && request.responseTainting === "basic";
      const contentLength = httpRequest.body ? httpRequest.body.length : null;
      let contentLengthHeaderValue = null;
      if (httpRequest.body == null && ["POST", "PUT"].includes(httpRequest.method)) {
        contentLengthHeaderValue = "0";
      }
      if (contentLength != null) {
        contentLengthHeaderValue = isomorphicEncode(`${contentLength}`);
      }
      if (contentLengthHeaderValue != null && !httpRequest.headersList.contains("content-length", true)) {
        httpRequest.headersList.append("content-length", contentLengthHeaderValue, true);
      }
      if (contentLength != null && httpRequest.keepalive) {
      }
      if (webidl.is.URL(httpRequest.referrer)) {
        httpRequest.headersList.append("referer", isomorphicEncode(httpRequest.referrer.href), true);
      }
      appendRequestOriginHeader(httpRequest);
      appendFetchMetadata(httpRequest);
      if (!httpRequest.headersList.contains("user-agent", true)) {
        httpRequest.headersList.append("user-agent", defaultUserAgent, true);
      }
      if (httpRequest.cache === "default" && (httpRequest.headersList.contains("if-modified-since", true) || httpRequest.headersList.contains("if-none-match", true) || httpRequest.headersList.contains("if-unmodified-since", true) || httpRequest.headersList.contains("if-match", true) || httpRequest.headersList.contains("if-range", true))) {
        httpRequest.cache = "no-store";
      }
      if (httpRequest.cache === "no-cache" && !httpRequest.preventNoCacheCacheControlHeaderModification && !httpRequest.headersList.contains("cache-control", true)) {
        httpRequest.headersList.append("cache-control", "max-age=0", true);
      }
      if (httpRequest.cache === "no-store" || httpRequest.cache === "reload") {
        if (!httpRequest.headersList.contains("pragma", true)) {
          httpRequest.headersList.append("pragma", "no-cache", true);
        }
        if (!httpRequest.headersList.contains("cache-control", true)) {
          httpRequest.headersList.append("cache-control", "no-cache", true);
        }
      }
      if (httpRequest.headersList.contains("range", true)) {
        httpRequest.headersList.append("accept-encoding", "identity", true);
      }
      if (!httpRequest.headersList.contains("accept-encoding", true)) {
        if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
          httpRequest.headersList.append("accept-encoding", "br, gzip, deflate", true);
        } else {
          httpRequest.headersList.append("accept-encoding", "gzip, deflate", true);
        }
      }
      httpRequest.headersList.delete("host", true);
      if (includeCredentials) {
        if (!httpRequest.headersList.contains("authorization", true)) {
          let authorizationValue = null;
          if (hasAuthenticationEntry(httpRequest) && (httpRequest.useURLCredentials === void 0 || !includesCredentials(requestCurrentURL(httpRequest)))) {
          } else if (includesCredentials(requestCurrentURL(httpRequest)) && isAuthenticationFetch) {
            const { username, password } = requestCurrentURL(httpRequest);
            authorizationValue = `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
          }
          if (authorizationValue !== null) {
            httpRequest.headersList.append("Authorization", authorizationValue, false);
          }
        }
      }
      if (httpCache == null) {
        httpRequest.cache = "no-store";
      }
      if (httpRequest.cache !== "no-store" && httpRequest.cache !== "reload") {
      }
      if (response == null) {
        if (httpRequest.cache === "only-if-cached") {
          return makeNetworkError("only if cached");
        }
        const forwardResponse = await httpNetworkFetch(
          httpFetchParams,
          includeCredentials,
          isNewConnectionFetch
        );
        if (!safeMethodsSet.has(httpRequest.method) && forwardResponse.status >= 200 && forwardResponse.status <= 399) {
        }
        if (revalidatingFlag && forwardResponse.status === 304) {
        }
        if (response == null) {
          response = forwardResponse;
        }
      }
      response.urlList = [...httpRequest.urlList];
      if (httpRequest.headersList.contains("range", true)) {
        response.rangeRequested = true;
      }
      response.requestIncludesCredentials = includeCredentials;
      if (response.status === 401 && httpRequest.responseTainting !== "cors" && includeCredentials && (request.useURLCredentials !== void 0 || isTraversableNavigable(request.traversableForUserPrompts))) {
        if (request.body != null) {
          if (request.body.source == null) {
            return response;
          }
          request.body = safelyExtractBody(request.body.source)[0];
        }
        if (request.useURLCredentials === void 0 || isAuthenticationFetch) {
          if (isCancelled(fetchParams)) {
            return makeAppropriateNetworkError(fetchParams);
          }
          return response;
        }
        fetchParams.controller.connection.destroy();
        response = await httpNetworkOrCacheFetch(fetchParams, true);
      }
      if (response.status === 407) {
        if (request.window === "no-window") {
          return makeNetworkError();
        }
        if (isCancelled(fetchParams)) {
          return makeAppropriateNetworkError(fetchParams);
        }
        return makeNetworkError("proxy authentication required");
      }
      if (
        // response’s status is 421
        response.status === 421 && // isNewConnectionFetch is false
        !isNewConnectionFetch && // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
        (request.body == null || request.body.source != null)
      ) {
        if (isCancelled(fetchParams)) {
          return makeAppropriateNetworkError(fetchParams);
        }
        fetchParams.controller.connection.destroy();
        response = await httpNetworkOrCacheFetch(
          fetchParams,
          isAuthenticationFetch,
          true
        );
      }
      if (isAuthenticationFetch) {
      }
      return response;
    }
    async function httpNetworkFetch(fetchParams, includeCredentials = false, forceNewConnection = false) {
      assert8(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed);
      fetchParams.controller.connection = {
        abort: null,
        destroyed: false,
        destroy(err, abort = true) {
          if (!this.destroyed) {
            this.destroyed = true;
            if (abort) {
              this.abort?.(err ?? new DOMException("The operation was aborted.", "AbortError"));
            }
          }
        }
      };
      const request = fetchParams.request;
      let response = null;
      const timingInfo = fetchParams.timingInfo;
      const httpCache = null;
      if (httpCache == null) {
        request.cache = "no-store";
      }
      const newConnection = forceNewConnection ? "yes" : "no";
      if (request.mode === "websocket") {
      } else {
      }
      let requestBody = null;
      if (request.body == null && fetchParams.processRequestEndOfBody) {
        queueMicrotask(() => fetchParams.processRequestEndOfBody());
      } else if (request.body != null) {
        const processBodyChunk = async function* (bytes) {
          if (isCancelled(fetchParams)) {
            return;
          }
          yield bytes;
          fetchParams.processRequestBodyChunkLength?.(bytes.byteLength);
        };
        const processEndOfBody = () => {
          if (isCancelled(fetchParams)) {
            return;
          }
          if (fetchParams.processRequestEndOfBody) {
            fetchParams.processRequestEndOfBody();
          }
        };
        const processBodyError = (e7) => {
          if (isCancelled(fetchParams)) {
            return;
          }
          if (e7.name === "AbortError") {
            fetchParams.controller.abort();
          } else {
            fetchParams.controller.terminate(e7);
          }
        };
        requestBody = (async function* () {
          try {
            for await (const bytes of request.body.stream) {
              yield* processBodyChunk(bytes);
            }
            processEndOfBody();
          } catch (err) {
            processBodyError(err);
          }
        })();
      }
      try {
        const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody });
        if (socket) {
          response = makeResponse({ status, statusText, headersList, socket });
        } else {
          const iterator = body[Symbol.asyncIterator]();
          fetchParams.controller.next = () => iterator.next();
          response = makeResponse({ status, statusText, headersList });
        }
      } catch (err) {
        if (err.name === "AbortError") {
          fetchParams.controller.connection.destroy();
          return makeAppropriateNetworkError(fetchParams, err);
        }
        return makeNetworkError(err);
      }
      const pullAlgorithm = () => {
        return fetchParams.controller.resume();
      };
      const cancelAlgorithm = (reason) => {
        if (!isCancelled(fetchParams)) {
          fetchParams.controller.abort(reason);
        }
      };
      const stream = new ReadableStream(
        {
          start(controller) {
            fetchParams.controller.controller = controller;
          },
          pull: pullAlgorithm,
          cancel: cancelAlgorithm,
          type: "bytes"
        }
      );
      response.body = { stream, source: null, length: null };
      if (!fetchParams.controller.resume) {
        fetchParams.controller.on("terminated", onAborted);
      }
      fetchParams.controller.resume = async () => {
        while (true) {
          let bytes;
          let isFailure;
          try {
            const { done, value } = await fetchParams.controller.next();
            if (isAborted2(fetchParams)) {
              break;
            }
            bytes = done ? void 0 : value;
          } catch (err) {
            if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
              bytes = void 0;
            } else {
              bytes = err;
              isFailure = true;
            }
          }
          if (bytes === void 0) {
            readableStreamClose(fetchParams.controller.controller);
            finalizeResponse(fetchParams, response);
            return;
          }
          timingInfo.decodedBodySize += bytes?.byteLength ?? 0;
          if (isFailure) {
            fetchParams.controller.terminate(bytes);
            return;
          }
          const buffer2 = new Uint8Array(bytes);
          if (buffer2.byteLength) {
            fetchParams.controller.controller.enqueue(buffer2);
          }
          if (isErrored(stream)) {
            fetchParams.controller.terminate();
            return;
          }
          if (fetchParams.controller.controller.desiredSize <= 0) {
            return;
          }
        }
      };
      function onAborted(reason) {
        if (isAborted2(fetchParams)) {
          response.aborted = true;
          if (isReadable(stream)) {
            fetchParams.controller.controller.error(
              fetchParams.controller.serializedAbortReason
            );
          }
        } else {
          if (isReadable(stream)) {
            fetchParams.controller.controller.error(new TypeError("terminated", {
              cause: isErrorLike(reason) ? reason : void 0
            }));
          }
        }
        fetchParams.controller.connection.destroy();
      }
      return response;
      function dispatch({ body }) {
        const url = requestCurrentURL(request);
        const agent = fetchParams.controller.dispatcher;
        const path2 = url.pathname + url.search;
        const hasTrailingQuestionMark = url.search.length === 0 && url.href[url.href.length - url.hash.length - 1] === "?";
        return dispatchWithProtocolPreference(body);
        function dispatchWithProtocolPreference(body2, allowH2) {
          return new Promise((resolve, reject) => agent.dispatch(
            {
              path: hasTrailingQuestionMark ? `${path2}?` : path2,
              origin: url.origin,
              method: request.method,
              body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body2,
              headers: request.headersList.entries,
              maxRedirections: 0,
              upgrade: request.mode === "websocket" ? "websocket" : void 0,
              ...allowH2 === false ? { allowH2 } : null
            },
            {
              body: null,
              abort: null,
              onRequestStart(controller) {
                const { connection } = fetchParams.controller;
                timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(void 0, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability);
                const abort = (reason) => controller.abort(reason);
                if (connection.destroyed) {
                  abort(new DOMException("The operation was aborted.", "AbortError"));
                } else {
                  fetchParams.controller.on("terminated", abort);
                  this.abort = connection.abort = abort;
                }
                timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
              },
              onResponseStarted() {
                timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability);
              },
              onResponseStart(controller, status, headers, statusText) {
                if (status < 200) {
                  return;
                }
                const rawHeaders = controller?.rawHeaders ?? [];
                const headersList = new HeadersList();
                appendHeadersListFromResponseHeaders(headersList, headers, rawHeaders);
                const location = headersList.get("location", true);
                this.body = new Readable({ read: () => controller.resume() });
                const willFollow = location && request.redirect === "follow" && redirectStatusSet.has(status);
                const decoders = [];
                if (request.method !== "HEAD" && request.method !== "CONNECT" && !nullBodyStatus.includes(status) && !willFollow) {
                  const contentEncoding = headersList.get("content-encoding", true);
                  const codings = contentEncoding ? contentEncoding.toLowerCase().split(",") : [];
                  const maxContentEncodings = 5;
                  if (codings.length > maxContentEncodings) {
                    reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`));
                    return;
                  }
                  for (let i = codings.length - 1; i >= 0; --i) {
                    const coding = codings[i].trim();
                    if (coding === "x-gzip" || coding === "gzip") {
                      decoders.push(zlib.createGunzip({
                        // Be less strict when decoding compressed responses, since sometimes
                        // servers send slightly invalid responses that are still accepted
                        // by common browsers.
                        // Always using Z_SYNC_FLUSH is what cURL does.
                        flush: zlib.constants.Z_SYNC_FLUSH,
                        finishFlush: zlib.constants.Z_SYNC_FLUSH
                      }));
                    } else if (coding === "deflate") {
                      decoders.push(createInflate({
                        flush: zlib.constants.Z_SYNC_FLUSH,
                        finishFlush: zlib.constants.Z_SYNC_FLUSH
                      }));
                    } else if (coding === "br") {
                      decoders.push(zlib.createBrotliDecompress({
                        flush: zlib.constants.BROTLI_OPERATION_FLUSH,
                        finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
                      }));
                    } else if (coding === "zstd") {
                      decoders.push(zlib.createZstdDecompress({
                        flush: zlib.constants.ZSTD_e_continue,
                        finishFlush: zlib.constants.ZSTD_e_end
                      }));
                    } else {
                      decoders.length = 0;
                      break;
                    }
                  }
                }
                const onError = (err) => this.onResponseError(controller, err);
                resolve({
                  status,
                  statusText,
                  headersList,
                  body: decoders.length ? pipeline(this.body, ...decoders, (err) => {
                    if (err) {
                      this.onResponseError(controller, err);
                    }
                  }).on("error", onError) : this.body.on("error", onError)
                });
              },
              onResponseData(controller, chunk) {
                if (fetchParams.controller.dump) {
                  return;
                }
                const bytes = chunk;
                timingInfo.encodedBodySize += bytes.byteLength;
                if (this.body.push(bytes) === false) {
                  controller.pause();
                }
              },
              onResponseEnd() {
                if (this.abort) {
                  fetchParams.controller.off("terminated", this.abort);
                }
                fetchParams.controller.ended = true;
                this.body?.push(null);
              },
              onResponseError(_controller, error) {
                if (this.abort) {
                  fetchParams.controller.off("terminated", this.abort);
                }
                if (request.mode === "websocket" && allowH2 !== false && error?.code === "UND_ERR_INFO" && error?.message === "HTTP/2: Extended CONNECT protocol not supported by server") {
                  resolve(dispatchWithProtocolPreference(body2, false));
                  return;
                }
                this.body?.destroy(error);
                fetchParams.controller.terminate(error);
                reject(error);
              },
              onRequestUpgrade(controller, status, headers, socket) {
                if (socket.session != null && status !== 200 || socket.session == null && status !== 101) {
                  return false;
                }
                const rawHeaders = controller?.rawHeaders ?? [];
                const headersList = new HeadersList();
                appendHeadersListFromResponseHeaders(headersList, headers, rawHeaders);
                resolve({
                  status,
                  statusText: STATUS_CODES[status],
                  headersList,
                  socket
                });
                return true;
              }
            }
          ));
        }
      }
    }
    module.exports = {
      fetch: fetch2,
      Fetch,
      fetching,
      finalizeAndReportTiming
    };
  }
});

// node_modules/undici/lib/web/cache/util.js
var require_util3 = __commonJS({
  "node_modules/undici/lib/web/cache/util.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var { URLSerializer } = require_data_url();
    var { isValidHeaderName } = require_util2();
    function urlEquals(A, B, excludeFragment = false) {
      const serializedA = URLSerializer(A, excludeFragment);
      const serializedB = URLSerializer(B, excludeFragment);
      return serializedA === serializedB;
    }
    function getFieldValues(header) {
      assert8(header !== null);
      const values = [];
      for (let value of header.split(",")) {
        value = value.trim();
        if (isValidHeaderName(value)) {
          values.push(value);
        }
      }
      return values;
    }
    module.exports = {
      urlEquals,
      getFieldValues
    };
  }
});

// node_modules/undici/lib/web/cache/cache.js
var require_cache3 = __commonJS({
  "node_modules/undici/lib/web/cache/cache.js"(exports, module) {
    "use strict";
    var assert8 = __require("assert");
    var { kConstruct } = require_symbols();
    var { urlEquals, getFieldValues } = require_util3();
    var { kEnumerableProperty, isDisturbed } = require_util();
    var { webidl } = require_webidl();
    var { cloneResponse, fromInnerResponse, getResponseState } = require_response();
    var { Request: Request2, fromInnerRequest, getRequestState } = require_request2();
    var { fetching } = require_fetch();
    var { urlIsHttpHttpsScheme, readAllBytes } = require_util2();
    var Cache = class _Cache {
      /**
       * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
       * @type {requestResponseList}
       */
      #relevantRequestResponseList;
      constructor() {
        if (arguments[0] !== kConstruct) {
          webidl.illegalConstructor();
        }
        webidl.util.markAsUncloneable(this);
        this.#relevantRequestResponseList = arguments[1];
      }
      async match(request, options = {}) {
        webidl.brandCheck(this, _Cache);
        const prefix = "Cache.match";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        request = webidl.converters.RequestInfo(request);
        options = webidl.converters.CacheQueryOptions(options, prefix, "options");
        const p = this.#internalMatchAll(request, options, 1);
        if (p.length === 0) {
          return;
        }
        return p[0];
      }
      async matchAll(request = void 0, options = {}) {
        webidl.brandCheck(this, _Cache);
        const prefix = "Cache.matchAll";
        if (request !== void 0) request = webidl.converters.RequestInfo(request);
        options = webidl.converters.CacheQueryOptions(options, prefix, "options");
        return this.#internalMatchAll(request, options);
      }
      async add(request) {
        webidl.brandCheck(this, _Cache);
        const prefix = "Cache.add";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        request = webidl.converters.RequestInfo(request);
        const requests = [request];
        const responseArrayPromise = this.addAll(requests);
        return await responseArrayPromise;
      }
      async addAll(requests) {
        webidl.brandCheck(this, _Cache);
        const prefix = "Cache.addAll";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        const responsePromises = [];
        const requestList = [];
        for (let request of requests) {
          if (request === void 0) {
            throw webidl.errors.conversionFailed({
              prefix,
              argument: "Argument 1",
              types: ["undefined is not allowed"]
            });
          }
          request = webidl.converters.RequestInfo(request);
          if (typeof request === "string") {
            continue;
          }
          const r = getRequestState(request);
          if (!urlIsHttpHttpsScheme(r.url) || r.method !== "GET") {
            throw webidl.errors.exception({
              header: prefix,
              message: "Expected http/s scheme when method is not GET."
            });
          }
        }
        const fetchControllers = [];
        for (const request of requests) {
          const r = getRequestState(new Request2(request));
          if (!urlIsHttpHttpsScheme(r.url)) {
            throw webidl.errors.exception({
              header: prefix,
              message: "Expected http/s scheme."
            });
          }
          r.initiator = "fetch";
          r.destination = "subresource";
          requestList.push(r);
          const responsePromise = Promise.withResolvers();
          fetchControllers.push(fetching({
            request: r,
            processResponse(response) {
              if (response.type === "error" || response.status === 206 || response.status < 200 || response.status > 299) {
                responsePromise.reject(webidl.errors.exception({
                  header: "Cache.addAll",
                  message: "Received an invalid status code or the request failed."
                }));
              } else if (response.headersList.contains("vary")) {
                const fieldValues = getFieldValues(response.headersList.get("vary"));
                for (const fieldValue of fieldValues) {
                  if (fieldValue === "*") {
                    responsePromise.reject(webidl.errors.exception({
                      header: "Cache.addAll",
                      message: "invalid vary field value"
                    }));
                    for (const controller of fetchControllers) {
                      controller.abort();
                    }
                    return;
                  }
                }
              }
            },
            processResponseEndOfBody(response) {
              if (response.aborted) {
                responsePromise.reject(new DOMException("aborted", "AbortError"));
                return;
              }
              responsePromise.resolve(response);
            }
          }));
          responsePromises.push(responsePromise.promise);
        }
        const p = Promise.all(responsePromises);
        const responses = await p;
        const operations = [];
        let index2 = 0;
        for (const response of responses) {
          const operation = {
            type: "put",
            // 7.3.2
            request: requestList[index2],
            // 7.3.3
            response
            // 7.3.4
          };
          operations.push(operation);
          index2++;
        }
        const cacheJobPromise = Promise.withResolvers();
        let errorData = null;
        try {
          this.#batchCacheOperations(operations);
        } catch (e7) {
          errorData = e7;
        }
        queueMicrotask(() => {
          if (errorData === null) {
            cacheJobPromise.resolve(void 0);
          } else {
            cacheJobPromise.reject(errorData);
          }
        });
        return cacheJobPromise.promise;
      }
      async put(request, response) {
        webidl.brandCheck(this, _Cache);
        const prefix = "Cache.put";
        webidl.argumentLengthCheck(arguments, 2, prefix);
        request = webidl.converters.RequestInfo(request);
        response = webidl.converters.Response(response, prefix, "response");
        let innerRequest = null;
        if (webidl.is.Request(request)) {
          innerRequest = getRequestState(request);
        } else {
          innerRequest = getRequestState(new Request2(request));
        }
        if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== "GET") {
          throw webidl.errors.exception({
            header: prefix,
            message: "Expected an http/s scheme when method is not GET"
          });
        }
        const innerResponse = getResponseState(response);
        if (innerResponse.status === 206) {
          throw webidl.errors.exception({
            header: prefix,
            message: "Got 206 status"
          });
        }
        if (innerResponse.headersList.contains("vary")) {
          const fieldValues = getFieldValues(innerResponse.headersList.get("vary"));
          for (const fieldValue of fieldValues) {
            if (fieldValue === "*") {
              throw webidl.errors.exception({
                header: prefix,
                message: "Got * vary field value"
              });
            }
          }
        }
        if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {
          throw webidl.errors.exception({
            header: prefix,
            message: "Response body is locked or disturbed"
          });
        }
        const clonedResponse = cloneResponse(innerResponse);
        const bodyReadPromise = Promise.withResolvers();
        if (innerResponse.body != null) {
          const stream = innerResponse.body.stream;
          const reader = stream.getReader();
          readAllBytes(reader, bodyReadPromise.resolve, bodyReadPromise.reject);
        } else {
          bodyReadPromise.resolve(void 0);
        }
        const operations = [];
        const operation = {
          type: "put",
          // 14.
          request: innerRequest,
          // 15.
          response: clonedResponse
          // 16.
        };
        operations.push(operation);
        const bytes = await bodyReadPromise.promise;
        if (clonedResponse.body != null) {
          clonedResponse.body.source = bytes;
        }
        const cacheJobPromise = Promise.withResolvers();
        let errorData = null;
        try {
          this.#batchCacheOperations(operations);
        } catch (e7) {
          errorData = e7;
        }
        queueMicrotask(() => {
          if (errorData === null) {
            cacheJobPromise.resolve();
          } else {
            cacheJobPromise.reject(errorData);
          }
        });
        return cacheJobPromise.promise;
      }
      async delete(request, options = {}) {
        webidl.brandCheck(this, _Cache);
        const prefix = "Cache.delete";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        request = webidl.converters.RequestInfo(request);
        options = webidl.converters.CacheQueryOptions(options, prefix, "options");
        let r = null;
        if (webidl.is.Request(request)) {
          r = getRequestState(request);
          if (r.method !== "GET" && !options.ignoreMethod) {
            return false;
          }
        } else {
          assert8(typeof request === "string");
          r = getRequestState(new Request2(request));
        }
        const operations = [];
        const operation = {
          type: "delete",
          request: r,
          options
        };
        operations.push(operation);
        const cacheJobPromise = Promise.withResolvers();
        let errorData = null;
        let requestResponses;
        try {
          requestResponses = this.#batchCacheOperations(operations);
        } catch (e7) {
          errorData = e7;
        }
        queueMicrotask(() => {
          if (errorData === null) {
            cacheJobPromise.resolve(!!requestResponses?.length);
          } else {
            cacheJobPromise.reject(errorData);
          }
        });
        return cacheJobPromise.promise;
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
       * @param {any} request
       * @param {import('../../../types/cache').CacheQueryOptions} options
       * @returns {Promise<readonly Request[]>}
       */
      async keys(request = void 0, options = {}) {
        webidl.brandCheck(this, _Cache);
        const prefix = "Cache.keys";
        if (request !== void 0) request = webidl.converters.RequestInfo(request);
        options = webidl.converters.CacheQueryOptions(options, prefix, "options");
        let r = null;
        if (request !== void 0) {
          if (webidl.is.Request(request)) {
            r = getRequestState(request);
            if (r.method !== "GET" && !options.ignoreMethod) {
              return [];
            }
          } else if (typeof request === "string") {
            r = getRequestState(new Request2(request));
          }
        }
        const promise = Promise.withResolvers();
        const requests = [];
        if (request === void 0) {
          for (const requestResponse of this.#relevantRequestResponseList) {
            requests.push(requestResponse[0]);
          }
        } else {
          const requestResponses = this.#queryCache(r, options);
          for (const requestResponse of requestResponses) {
            requests.push(requestResponse[0]);
          }
        }
        queueMicrotask(() => {
          const requestList = [];
          for (const request2 of requests) {
            const requestObject = fromInnerRequest(
              request2,
              void 0,
              new AbortController().signal,
              "immutable"
            );
            requestList.push(requestObject);
          }
          promise.resolve(Object.freeze(requestList));
        });
        return promise.promise;
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm
       * @param {CacheBatchOperation[]} operations
       * @returns {requestResponseList}
       */
      #batchCacheOperations(operations) {
        const cache2 = this.#relevantRequestResponseList;
        const backupCache = [...cache2];
        const addedItems = [];
        const resultList = [];
        try {
          for (const operation of operations) {
            if (operation.type !== "delete" && operation.type !== "put") {
              throw webidl.errors.exception({
                header: "Cache.#batchCacheOperations",
                message: 'operation type does not match "delete" or "put"'
              });
            }
            if (operation.type === "delete" && operation.response != null) {
              throw webidl.errors.exception({
                header: "Cache.#batchCacheOperations",
                message: "delete operation should not have an associated response"
              });
            }
            if (this.#queryCache(operation.request, operation.options, addedItems).length) {
              throw new DOMException("???", "InvalidStateError");
            }
            let requestResponses;
            if (operation.type === "delete") {
              requestResponses = this.#queryCache(operation.request, operation.options);
              if (requestResponses.length === 0) {
                return [];
              }
              for (const requestResponse of requestResponses) {
                const idx = cache2.indexOf(requestResponse);
                assert8(idx !== -1);
                cache2.splice(idx, 1);
              }
            } else if (operation.type === "put") {
              if (operation.response == null) {
                throw webidl.errors.exception({
                  header: "Cache.#batchCacheOperations",
                  message: "put operation should have an associated response"
                });
              }
              const r = operation.request;
              if (!urlIsHttpHttpsScheme(r.url)) {
                throw webidl.errors.exception({
                  header: "Cache.#batchCacheOperations",
                  message: "expected http or https scheme"
                });
              }
              if (r.method !== "GET") {
                throw webidl.errors.exception({
                  header: "Cache.#batchCacheOperations",
                  message: "not get method"
                });
              }
              if (operation.options != null) {
                throw webidl.errors.exception({
                  header: "Cache.#batchCacheOperations",
                  message: "options must not be defined"
                });
              }
              requestResponses = this.#queryCache(operation.request);
              for (const requestResponse of requestResponses) {
                const idx = cache2.indexOf(requestResponse);
                assert8(idx !== -1);
                cache2.splice(idx, 1);
              }
              cache2.push([operation.request, operation.response]);
              addedItems.push([operation.request, operation.response]);
            }
            resultList.push([operation.request, operation.response]);
          }
          return resultList;
        } catch (e7) {
          this.#relevantRequestResponseList.length = 0;
          this.#relevantRequestResponseList = backupCache;
          throw e7;
        }
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#query-cache
       * @param {any} requestQuery
       * @param {import('../../../types/cache').CacheQueryOptions} options
       * @param {requestResponseList} targetStorage
       * @returns {requestResponseList}
       */
      #queryCache(requestQuery, options, targetStorage) {
        const resultList = [];
        const storage = targetStorage ?? this.#relevantRequestResponseList;
        for (const requestResponse of storage) {
          const [cachedRequest, cachedResponse] = requestResponse;
          if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {
            resultList.push(requestResponse);
          }
        }
        return resultList;
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm
       * @param {any} requestQuery
       * @param {any} request
       * @param {any | null} response
       * @param {import('../../../types/cache').CacheQueryOptions | undefined} options
       * @returns {boolean}
       */
      #requestMatchesCachedItem(requestQuery, request, response = null, options) {
        const queryURL = new URL(requestQuery.url);
        const cachedURL = new URL(request.url);
        if (options?.ignoreSearch) {
          cachedURL.search = "";
          queryURL.search = "";
        }
        if (!urlEquals(queryURL, cachedURL, true)) {
          return false;
        }
        if (response == null || options?.ignoreVary || !response.headersList.contains("vary")) {
          return true;
        }
        const fieldValues = getFieldValues(response.headersList.get("vary"));
        for (const fieldValue of fieldValues) {
          if (fieldValue === "*") {
            return false;
          }
          const requestValue = request.headersList.get(fieldValue);
          const queryValue = requestQuery.headersList.get(fieldValue);
          if (requestValue !== queryValue) {
            return false;
          }
        }
        return true;
      }
      #internalMatchAll(request, options, maxResponses = Infinity) {
        let r = null;
        if (request !== void 0) {
          if (webidl.is.Request(request)) {
            r = getRequestState(request);
            if (r.method !== "GET" && !options.ignoreMethod) {
              return [];
            }
          } else if (typeof request === "string") {
            r = getRequestState(new Request2(request));
          }
        }
        const responses = [];
        if (request === void 0) {
          for (const requestResponse of this.#relevantRequestResponseList) {
            responses.push(requestResponse[1]);
          }
        } else {
          const requestResponses = this.#queryCache(r, options);
          for (const requestResponse of requestResponses) {
            responses.push(requestResponse[1]);
          }
        }
        const responseList = [];
        for (const response of responses) {
          const responseObject = fromInnerResponse(cloneResponse(response), "immutable");
          responseList.push(responseObject);
          if (responseList.length >= maxResponses) {
            break;
          }
        }
        return Object.freeze(responseList);
      }
    };
    Object.defineProperties(Cache.prototype, {
      [Symbol.toStringTag]: {
        value: "Cache",
        configurable: true
      },
      match: kEnumerableProperty,
      matchAll: kEnumerableProperty,
      add: kEnumerableProperty,
      addAll: kEnumerableProperty,
      put: kEnumerableProperty,
      delete: kEnumerableProperty,
      keys: kEnumerableProperty
    });
    var cacheQueryOptionConverters = [
      {
        key: "ignoreSearch",
        converter: webidl.converters.boolean,
        defaultValue: () => false
      },
      {
        key: "ignoreMethod",
        converter: webidl.converters.boolean,
        defaultValue: () => false
      },
      {
        key: "ignoreVary",
        converter: webidl.converters.boolean,
        defaultValue: () => false
      }
    ];
    webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters);
    webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([
      ...cacheQueryOptionConverters,
      {
        key: "cacheName",
        converter: webidl.converters.DOMString
      }
    ]);
    webidl.converters.Response = webidl.interfaceConverter(
      webidl.is.Response,
      "Response"
    );
    webidl.converters["sequence<RequestInfo>"] = webidl.sequenceConverter(
      webidl.converters.RequestInfo
    );
    module.exports = {
      Cache
    };
  }
});

// node_modules/undici/lib/web/cache/cachestorage.js
var require_cachestorage = __commonJS({
  "node_modules/undici/lib/web/cache/cachestorage.js"(exports, module) {
    "use strict";
    var { Cache } = require_cache3();
    var { webidl } = require_webidl();
    var { kEnumerableProperty } = require_util();
    var { kConstruct } = require_symbols();
    var CacheStorage = class _CacheStorage {
      /**
       * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
       * @type {Map<string, import('./cache').requestResponseList}
       */
      #caches = /* @__PURE__ */ new Map();
      constructor() {
        if (arguments[0] !== kConstruct) {
          webidl.illegalConstructor();
        }
        webidl.util.markAsUncloneable(this);
      }
      async match(request, options = {}) {
        webidl.brandCheck(this, _CacheStorage);
        webidl.argumentLengthCheck(arguments, 1, "CacheStorage.match");
        request = webidl.converters.RequestInfo(request);
        options = webidl.converters.MultiCacheQueryOptions(options);
        if (options.cacheName != null) {
          if (this.#caches.has(options.cacheName)) {
            const cacheList = this.#caches.get(options.cacheName);
            const cache2 = new Cache(kConstruct, cacheList);
            return await cache2.match(request, options);
          }
        } else {
          for (const cacheList of this.#caches.values()) {
            const cache2 = new Cache(kConstruct, cacheList);
            const response = await cache2.match(request, options);
            if (response !== void 0) {
              return response;
            }
          }
        }
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#cache-storage-has
       * @param {string} cacheName
       * @returns {Promise<boolean>}
       */
      async has(cacheName) {
        webidl.brandCheck(this, _CacheStorage);
        const prefix = "CacheStorage.has";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName");
        return this.#caches.has(cacheName);
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open
       * @param {string} cacheName
       * @returns {Promise<Cache>}
       */
      async open(cacheName) {
        webidl.brandCheck(this, _CacheStorage);
        const prefix = "CacheStorage.open";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName");
        if (this.#caches.has(cacheName)) {
          const cache3 = this.#caches.get(cacheName);
          return new Cache(kConstruct, cache3);
        }
        const cache2 = [];
        this.#caches.set(cacheName, cache2);
        return new Cache(kConstruct, cache2);
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
       * @param {string} cacheName
       * @returns {Promise<boolean>}
       */
      async delete(cacheName) {
        webidl.brandCheck(this, _CacheStorage);
        const prefix = "CacheStorage.delete";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        cacheName = webidl.converters.DOMString(cacheName, prefix, "cacheName");
        return this.#caches.delete(cacheName);
      }
      /**
       * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
       * @returns {Promise<string[]>}
       */
      async keys() {
        webidl.brandCheck(this, _CacheStorage);
        const keys = this.#caches.keys();
        return [...keys];
      }
    };
    Object.defineProperties(CacheStorage.prototype, {
      [Symbol.toStringTag]: {
        value: "CacheStorage",
        configurable: true
      },
      match: kEnumerableProperty,
      has: kEnumerableProperty,
      open: kEnumerableProperty,
      delete: kEnumerableProperty,
      keys: kEnumerableProperty
    });
    module.exports = {
      CacheStorage
    };
  }
});

// node_modules/undici/lib/web/cookies/constants.js
var require_constants5 = __commonJS({
  "node_modules/undici/lib/web/cookies/constants.js"(exports, module) {
    "use strict";
    var maxAttributeValueSize = 1024;
    var maxNameValuePairSize = 4096;
    module.exports = {
      maxAttributeValueSize,
      maxNameValuePairSize
    };
  }
});

// node_modules/undici/lib/web/cookies/util.js
var require_util4 = __commonJS({
  "node_modules/undici/lib/web/cookies/util.js"(exports, module) {
    "use strict";
    function isCTLExcludingHtab(value) {
      for (let i = 0; i < value.length; ++i) {
        const code = value.charCodeAt(i);
        if (code >= 0 && code <= 8 || code >= 10 && code <= 31 || code === 127) {
          return true;
        }
      }
      return false;
    }
    function validateCookieName(name) {
      for (let i = 0; i < name.length; ++i) {
        const code = name.charCodeAt(i);
        if (code < 33 || // exclude CTLs (0-31), SP and HT
        code > 126 || // exclude non-ascii and DEL
        code === 34 || // "
        code === 40 || // (
        code === 41 || // )
        code === 60 || // <
        code === 62 || // >
        code === 64 || // @
        code === 44 || // ,
        code === 59 || // ;
        code === 58 || // :
        code === 92 || // \
        code === 47 || // /
        code === 91 || // [
        code === 93 || // ]
        code === 63 || // ?
        code === 61 || // =
        code === 123 || // {
        code === 125) {
          throw new Error("Invalid cookie name");
        }
      }
    }
    function validateCookieValue(value) {
      let len = value.length;
      let i = 0;
      if (value[0] === '"') {
        if (len === 1 || value[len - 1] !== '"') {
          throw new Error("Invalid cookie value");
        }
        --len;
        ++i;
      }
      while (i < len) {
        const code = value.charCodeAt(i++);
        if (code < 33 || // exclude CTLs (0-31)
        code > 126 || // non-ascii and DEL (127)
        code === 34 || // "
        code === 44 || // ,
        code === 59 || // ;
        code === 92) {
          throw new Error("Invalid cookie value");
        }
      }
    }
    function validateCookiePath(path2) {
      for (let i = 0; i < path2.length; ++i) {
        const code = path2.charCodeAt(i);
        if (code < 32 || // exclude CTLs (0-31)
        code === 127 || // DEL
        code === 59) {
          throw new Error("Invalid cookie path");
        }
      }
    }
    function validateCookieDomain(domain) {
      if (domain.startsWith("-") || domain.endsWith(".") || domain.endsWith("-")) {
        throw new Error("Invalid cookie domain");
      }
    }
    var IMFDays = [
      "Sun",
      "Mon",
      "Tue",
      "Wed",
      "Thu",
      "Fri",
      "Sat"
    ];
    var IMFMonths = [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec"
    ];
    var IMFPaddedNumbers = Array(61).fill(0).map((_, i) => i.toString().padStart(2, "0"));
    function toIMFDate(date) {
      if (typeof date === "number") {
        date = new Date(date);
      }
      return `${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT`;
    }
    function validateCookieMaxAge(maxAge) {
      if (maxAge < 0) {
        throw new Error("Invalid cookie max-age");
      }
    }
    function stringify4(cookie) {
      if (cookie.name.length === 0) {
        return null;
      }
      validateCookieName(cookie.name);
      validateCookieValue(cookie.value);
      const out = [`${cookie.name}=${cookie.value}`];
      if (cookie.name.startsWith("__Secure-")) {
        cookie.secure = true;
      }
      if (cookie.name.startsWith("__Host-")) {
        cookie.secure = true;
        cookie.domain = null;
        cookie.path = "/";
      }
      if (cookie.secure) {
        out.push("Secure");
      }
      if (cookie.httpOnly) {
        out.push("HttpOnly");
      }
      if (typeof cookie.maxAge === "number") {
        validateCookieMaxAge(cookie.maxAge);
        out.push(`Max-Age=${cookie.maxAge}`);
      }
      if (cookie.domain) {
        validateCookieDomain(cookie.domain);
        out.push(`Domain=${cookie.domain}`);
      }
      if (cookie.path) {
        validateCookiePath(cookie.path);
        out.push(`Path=${cookie.path}`);
      }
      if (cookie.expires && cookie.expires.toString() !== "Invalid Date") {
        out.push(`Expires=${toIMFDate(cookie.expires)}`);
      }
      if (cookie.sameSite) {
        out.push(`SameSite=${cookie.sameSite}`);
      }
      for (const part of cookie.unparsed) {
        if (!part.includes("=")) {
          throw new Error("Invalid unparsed");
        }
        const [key, ...value] = part.split("=");
        out.push(`${key.trim()}=${value.join("=")}`);
      }
      return out.join("; ");
    }
    module.exports = {
      isCTLExcludingHtab,
      validateCookieName,
      validateCookiePath,
      validateCookieValue,
      toIMFDate,
      stringify: stringify4
    };
  }
});

// node_modules/undici/lib/web/cookies/parse.js
var require_parse = __commonJS({
  "node_modules/undici/lib/web/cookies/parse.js"(exports, module) {
    "use strict";
    var { collectASequenceOfCodePointsFast } = require_infra();
    var { maxNameValuePairSize, maxAttributeValueSize } = require_constants5();
    var { isCTLExcludingHtab } = require_util4();
    var assert8 = __require("assert");
    var { unescape: qsUnescape } = __require("querystring");
    function parseSetCookie(header) {
      if (isCTLExcludingHtab(header)) {
        return null;
      }
      let nameValuePair = "";
      let unparsedAttributes = "";
      let name = "";
      let value = "";
      if (header.includes(";")) {
        const position = { position: 0 };
        nameValuePair = collectASequenceOfCodePointsFast(";", header, position);
        unparsedAttributes = header.slice(position.position);
      } else {
        nameValuePair = header;
      }
      if (!nameValuePair.includes("=")) {
        value = nameValuePair;
      } else {
        const position = { position: 0 };
        name = collectASequenceOfCodePointsFast(
          "=",
          nameValuePair,
          position
        );
        value = nameValuePair.slice(position.position + 1);
      }
      name = name.trim();
      value = value.trim();
      if (name.length + value.length > maxNameValuePairSize) {
        return null;
      }
      return {
        name,
        value: qsUnescape(value),
        ...parseUnparsedAttributes(unparsedAttributes)
      };
    }
    function parseUnparsedAttributes(unparsedAttributes, cookieAttributeList = {}) {
      if (unparsedAttributes.length === 0) {
        return cookieAttributeList;
      }
      assert8(unparsedAttributes[0] === ";");
      unparsedAttributes = unparsedAttributes.slice(1);
      let cookieAv = "";
      if (unparsedAttributes.includes(";")) {
        cookieAv = collectASequenceOfCodePointsFast(
          ";",
          unparsedAttributes,
          { position: 0 }
        );
        unparsedAttributes = unparsedAttributes.slice(cookieAv.length);
      } else {
        cookieAv = unparsedAttributes;
        unparsedAttributes = "";
      }
      let attributeName = "";
      let attributeValue = "";
      if (cookieAv.includes("=")) {
        const position = { position: 0 };
        attributeName = collectASequenceOfCodePointsFast(
          "=",
          cookieAv,
          position
        );
        attributeValue = cookieAv.slice(position.position + 1);
      } else {
        attributeName = cookieAv;
      }
      attributeName = attributeName.trim();
      attributeValue = attributeValue.trim();
      if (attributeValue.length > maxAttributeValueSize) {
        return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
      }
      const attributeNameLowercase = attributeName.toLowerCase();
      if (attributeNameLowercase === "expires") {
        const expiryTime = new Date(attributeValue);
        cookieAttributeList.expires = expiryTime;
      } else if (attributeNameLowercase === "max-age") {
        const charCode = attributeValue.charCodeAt(0);
        if ((charCode < 48 || charCode > 57) && attributeValue[0] !== "-") {
          return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
        }
        if (!/^\d+$/.test(attributeValue)) {
          return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
        }
        const deltaSeconds = Number(attributeValue);
        cookieAttributeList.maxAge = deltaSeconds;
      } else if (attributeNameLowercase === "domain") {
        let cookieDomain = attributeValue;
        if (cookieDomain[0] === ".") {
          cookieDomain = cookieDomain.slice(1);
        }
        cookieDomain = cookieDomain.toLowerCase();
        cookieAttributeList.domain = cookieDomain;
      } else if (attributeNameLowercase === "path") {
        let cookiePath = "";
        if (attributeValue.length === 0 || attributeValue[0] !== "/") {
          cookiePath = "/";
        } else {
          cookiePath = attributeValue;
        }
        cookieAttributeList.path = cookiePath;
      } else if (attributeNameLowercase === "secure") {
        cookieAttributeList.secure = true;
      } else if (attributeNameLowercase === "httponly") {
        cookieAttributeList.httpOnly = true;
      } else if (attributeNameLowercase === "samesite") {
        let enforcement = "Default";
        const attributeValueLowercase = attributeValue.toLowerCase();
        if (attributeValueLowercase.includes("none")) {
          enforcement = "None";
        }
        if (attributeValueLowercase.includes("strict")) {
          enforcement = "Strict";
        }
        if (attributeValueLowercase.includes("lax")) {
          enforcement = "Lax";
        }
        cookieAttributeList.sameSite = enforcement;
      } else {
        cookieAttributeList.unparsed ??= [];
        cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`);
      }
      return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList);
    }
    module.exports = {
      parseSetCookie,
      parseUnparsedAttributes
    };
  }
});

// node_modules/undici/lib/web/cookies/index.js
var require_cookies = __commonJS({
  "node_modules/undici/lib/web/cookies/index.js"(exports, module) {
    "use strict";
    var { parseSetCookie } = require_parse();
    var { stringify: stringify4 } = require_util4();
    var { webidl } = require_webidl();
    var { Headers } = require_headers();
    var brandChecks = webidl.brandCheckMultiple([Headers, globalThis.Headers].filter(Boolean));
    function getCookies(headers) {
      webidl.argumentLengthCheck(arguments, 1, "getCookies");
      brandChecks(headers);
      const cookie = headers.get("cookie");
      const out = {};
      if (!cookie) {
        return out;
      }
      for (const piece of cookie.split(";")) {
        const [name, ...value] = piece.split("=");
        out[name.trim()] = value.join("=");
      }
      return out;
    }
    function deleteCookie(headers, name, attributes) {
      brandChecks(headers);
      const prefix = "deleteCookie";
      webidl.argumentLengthCheck(arguments, 2, prefix);
      name = webidl.converters.DOMString(name, prefix, "name");
      attributes = webidl.converters.DeleteCookieAttributes(attributes);
      setCookie(headers, {
        name,
        value: "",
        expires: /* @__PURE__ */ new Date(0),
        ...attributes
      });
    }
    function getSetCookies(headers) {
      webidl.argumentLengthCheck(arguments, 1, "getSetCookies");
      brandChecks(headers);
      const cookies = headers.getSetCookie();
      if (!cookies) {
        return [];
      }
      return cookies.map((pair) => parseSetCookie(pair));
    }
    function parseCookie(cookie) {
      cookie = webidl.converters.DOMString(cookie);
      return parseSetCookie(cookie);
    }
    function setCookie(headers, cookie) {
      webidl.argumentLengthCheck(arguments, 2, "setCookie");
      brandChecks(headers);
      cookie = webidl.converters.Cookie(cookie);
      const str = stringify4(cookie);
      if (str) {
        headers.append("set-cookie", str, true);
      }
    }
    webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([
      {
        converter: webidl.nullableConverter(webidl.converters.DOMString),
        key: "path",
        defaultValue: () => null
      },
      {
        converter: webidl.nullableConverter(webidl.converters.DOMString),
        key: "domain",
        defaultValue: () => null
      }
    ]);
    webidl.converters.Cookie = webidl.dictionaryConverter([
      {
        converter: webidl.converters.DOMString,
        key: "name"
      },
      {
        converter: webidl.converters.DOMString,
        key: "value"
      },
      {
        converter: webidl.nullableConverter((value) => {
          if (typeof value === "number") {
            return webidl.converters["unsigned long long"](value);
          }
          return new Date(value);
        }),
        key: "expires",
        defaultValue: () => null
      },
      {
        converter: webidl.nullableConverter(webidl.converters["long long"]),
        key: "maxAge",
        defaultValue: () => null
      },
      {
        converter: webidl.nullableConverter(webidl.converters.DOMString),
        key: "domain",
        defaultValue: () => null
      },
      {
        converter: webidl.nullableConverter(webidl.converters.DOMString),
        key: "path",
        defaultValue: () => null
      },
      {
        converter: webidl.nullableConverter(webidl.converters.boolean),
        key: "secure",
        defaultValue: () => null
      },
      {
        converter: webidl.nullableConverter(webidl.converters.boolean),
        key: "httpOnly",
        defaultValue: () => null
      },
      {
        converter: webidl.converters.USVString,
        key: "sameSite",
        allowedValues: ["Strict", "Lax", "None"]
      },
      {
        converter: webidl.sequenceConverter(webidl.converters.DOMString),
        key: "unparsed",
        defaultValue: () => []
      }
    ]);
    module.exports = {
      getCookies,
      deleteCookie,
      getSetCookies,
      setCookie,
      parseCookie
    };
  }
});

// node_modules/undici/lib/web/websocket/events.js
var require_events = __commonJS({
  "node_modules/undici/lib/web/websocket/events.js"(exports, module) {
    "use strict";
    var { webidl } = require_webidl();
    var { kEnumerableProperty } = require_util();
    var { kConstruct } = require_symbols();
    var MessageEvent = class _MessageEvent extends Event {
      #eventInit;
      constructor(type, eventInitDict = {}) {
        if (type === kConstruct) {
          super(arguments[1], arguments[2]);
          webidl.util.markAsUncloneable(this);
          return;
        }
        const prefix = "MessageEvent constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        type = webidl.converters.DOMString(type, prefix, "type");
        eventInitDict = webidl.converters.MessageEventInit(eventInitDict, prefix, "eventInitDict");
        super(type, eventInitDict);
        this.#eventInit = eventInitDict;
        webidl.util.markAsUncloneable(this);
      }
      get data() {
        webidl.brandCheck(this, _MessageEvent);
        return this.#eventInit.data;
      }
      get origin() {
        webidl.brandCheck(this, _MessageEvent);
        return this.#eventInit.origin;
      }
      get lastEventId() {
        webidl.brandCheck(this, _MessageEvent);
        return this.#eventInit.lastEventId;
      }
      get source() {
        webidl.brandCheck(this, _MessageEvent);
        return this.#eventInit.source;
      }
      get ports() {
        webidl.brandCheck(this, _MessageEvent);
        if (!Object.isFrozen(this.#eventInit.ports)) {
          Object.freeze(this.#eventInit.ports);
        }
        return this.#eventInit.ports;
      }
      initMessageEvent(type, bubbles = false, cancelable = false, data = null, origin = "", lastEventId = "", source = null, ports = []) {
        webidl.brandCheck(this, _MessageEvent);
        webidl.argumentLengthCheck(arguments, 1, "MessageEvent.initMessageEvent");
        return new _MessageEvent(type, {
          bubbles,
          cancelable,
          data,
          origin,
          lastEventId,
          source,
          ports
        });
      }
      static createFastMessageEvent(type, init) {
        const messageEvent = new _MessageEvent(kConstruct, type, init);
        messageEvent.#eventInit = init;
        messageEvent.#eventInit.data ??= null;
        messageEvent.#eventInit.origin ??= "";
        messageEvent.#eventInit.lastEventId ??= "";
        messageEvent.#eventInit.source ??= null;
        messageEvent.#eventInit.ports ??= [];
        return messageEvent;
      }
    };
    var { createFastMessageEvent } = MessageEvent;
    delete MessageEvent.createFastMessageEvent;
    var CloseEvent = class _CloseEvent extends Event {
      #eventInit;
      constructor(type, eventInitDict = {}) {
        const prefix = "CloseEvent constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        type = webidl.converters.DOMString(type, prefix, "type");
        eventInitDict = webidl.converters.CloseEventInit(eventInitDict);
        super(type, eventInitDict);
        this.#eventInit = eventInitDict;
        webidl.util.markAsUncloneable(this);
      }
      get wasClean() {
        webidl.brandCheck(this, _CloseEvent);
        return this.#eventInit.wasClean;
      }
      get code() {
        webidl.brandCheck(this, _CloseEvent);
        return this.#eventInit.code;
      }
      get reason() {
        webidl.brandCheck(this, _CloseEvent);
        return this.#eventInit.reason;
      }
    };
    var ErrorEvent = class _ErrorEvent extends Event {
      #eventInit;
      constructor(type, eventInitDict) {
        const prefix = "ErrorEvent constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        super(type, eventInitDict);
        webidl.util.markAsUncloneable(this);
        type = webidl.converters.DOMString(type, prefix, "type");
        eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {});
        this.#eventInit = eventInitDict;
      }
      get message() {
        webidl.brandCheck(this, _ErrorEvent);
        return this.#eventInit.message;
      }
      get filename() {
        webidl.brandCheck(this, _ErrorEvent);
        return this.#eventInit.filename;
      }
      get lineno() {
        webidl.brandCheck(this, _ErrorEvent);
        return this.#eventInit.lineno;
      }
      get colno() {
        webidl.brandCheck(this, _ErrorEvent);
        return this.#eventInit.colno;
      }
      get error() {
        webidl.brandCheck(this, _ErrorEvent);
        return this.#eventInit.error;
      }
    };
    Object.defineProperties(MessageEvent.prototype, {
      [Symbol.toStringTag]: {
        value: "MessageEvent",
        configurable: true
      },
      data: kEnumerableProperty,
      origin: kEnumerableProperty,
      lastEventId: kEnumerableProperty,
      source: kEnumerableProperty,
      ports: kEnumerableProperty,
      initMessageEvent: kEnumerableProperty
    });
    Object.defineProperties(CloseEvent.prototype, {
      [Symbol.toStringTag]: {
        value: "CloseEvent",
        configurable: true
      },
      reason: kEnumerableProperty,
      code: kEnumerableProperty,
      wasClean: kEnumerableProperty
    });
    Object.defineProperties(ErrorEvent.prototype, {
      [Symbol.toStringTag]: {
        value: "ErrorEvent",
        configurable: true
      },
      message: kEnumerableProperty,
      filename: kEnumerableProperty,
      lineno: kEnumerableProperty,
      colno: kEnumerableProperty,
      error: kEnumerableProperty
    });
    webidl.converters.MessagePort = webidl.interfaceConverter(
      webidl.is.MessagePort,
      "MessagePort"
    );
    webidl.converters["sequence<MessagePort>"] = webidl.sequenceConverter(
      webidl.converters.MessagePort
    );
    var eventInit = [
      {
        key: "bubbles",
        converter: webidl.converters.boolean,
        defaultValue: () => false
      },
      {
        key: "cancelable",
        converter: webidl.converters.boolean,
        defaultValue: () => false
      },
      {
        key: "composed",
        converter: webidl.converters.boolean,
        defaultValue: () => false
      }
    ];
    webidl.converters.MessageEventInit = webidl.dictionaryConverter([
      ...eventInit,
      {
        key: "data",
        converter: webidl.converters.any,
        defaultValue: () => null
      },
      {
        key: "origin",
        converter: webidl.converters.USVString,
        defaultValue: () => ""
      },
      {
        key: "lastEventId",
        converter: webidl.converters.DOMString,
        defaultValue: () => ""
      },
      {
        key: "source",
        // Node doesn't implement WindowProxy or ServiceWorker, so the only
        // valid value for source is a MessagePort.
        converter: webidl.nullableConverter(webidl.converters.MessagePort),
        defaultValue: () => null
      },
      {
        key: "ports",
        converter: webidl.converters["sequence<MessagePort>"],
        defaultValue: () => []
      }
    ]);
    webidl.converters.CloseEventInit = webidl.dictionaryConverter([
      ...eventInit,
      {
        key: "wasClean",
        converter: webidl.converters.boolean,
        defaultValue: () => false
      },
      {
        key: "code",
        converter: webidl.converters["unsigned short"],
        defaultValue: () => 0
      },
      {
        key: "reason",
        converter: webidl.converters.USVString,
        defaultValue: () => ""
      }
    ]);
    webidl.converters.ErrorEventInit = webidl.dictionaryConverter([
      ...eventInit,
      {
        key: "message",
        converter: webidl.converters.DOMString,
        defaultValue: () => ""
      },
      {
        key: "filename",
        converter: webidl.converters.USVString,
        defaultValue: () => ""
      },
      {
        key: "lineno",
        converter: webidl.converters["unsigned long"],
        defaultValue: () => 0
      },
      {
        key: "colno",
        converter: webidl.converters["unsigned long"],
        defaultValue: () => 0
      },
      {
        key: "error",
        converter: webidl.converters.any
      }
    ]);
    module.exports = {
      MessageEvent,
      CloseEvent,
      ErrorEvent,
      createFastMessageEvent
    };
  }
});

// node_modules/undici/lib/web/websocket/constants.js
var require_constants6 = __commonJS({
  "node_modules/undici/lib/web/websocket/constants.js"(exports, module) {
    "use strict";
    var uid2 = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    var staticPropertyDescriptors = {
      enumerable: true,
      writable: false,
      configurable: false
    };
    var states = {
      CONNECTING: 0,
      OPEN: 1,
      CLOSING: 2,
      CLOSED: 3
    };
    var sentCloseFrameState = {
      SENT: 1,
      RECEIVED: 2
    };
    var opcodes = {
      CONTINUATION: 0,
      TEXT: 1,
      BINARY: 2,
      CLOSE: 8,
      PING: 9,
      PONG: 10
    };
    var maxUnsigned16Bit = 65535;
    var parserStates = {
      INFO: 0,
      PAYLOADLENGTH_16: 2,
      PAYLOADLENGTH_64: 3,
      READ_DATA: 4
    };
    var emptyBuffer = Buffer.allocUnsafe(0);
    var sendHints = {
      text: 1,
      typedArray: 2,
      arrayBuffer: 3,
      blob: 4
    };
    module.exports = {
      uid: uid2,
      sentCloseFrameState,
      staticPropertyDescriptors,
      states,
      opcodes,
      maxUnsigned16Bit,
      parserStates,
      emptyBuffer,
      sendHints
    };
  }
});

// node_modules/undici/lib/web/websocket/util.js
var require_util5 = __commonJS({
  "node_modules/undici/lib/web/websocket/util.js"(exports, module) {
    "use strict";
    var { states, opcodes } = require_constants6();
    var { isUtf8 } = __require("buffer");
    var { removeHTTPWhitespace } = require_data_url();
    var { collectASequenceOfCodePointsFast } = require_infra();
    function isConnecting(readyState) {
      return readyState === states.CONNECTING;
    }
    function isEstablished(readyState) {
      return readyState === states.OPEN;
    }
    function isClosing(readyState) {
      return readyState === states.CLOSING;
    }
    function isClosed(readyState) {
      return readyState === states.CLOSED;
    }
    function fireEvent(e7, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) {
      const event = eventFactory(e7, eventInitDict);
      target.dispatchEvent(event);
    }
    function websocketMessageReceived(handler, type, data) {
      handler.onMessage(type, data);
    }
    function toArrayBuffer2(buffer2) {
      if (buffer2.byteLength === buffer2.buffer.byteLength) {
        return buffer2.buffer;
      }
      return new Uint8Array(buffer2).buffer;
    }
    function isValidSubprotocol(protocol) {
      if (protocol.length === 0) {
        return false;
      }
      for (let i = 0; i < protocol.length; ++i) {
        const code = protocol.charCodeAt(i);
        if (code < 33 || // CTL, contains SP (0x20) and HT (0x09)
        code > 126 || code === 34 || // "
        code === 40 || // (
        code === 41 || // )
        code === 44 || // ,
        code === 47 || // /
        code === 58 || // :
        code === 59 || // ;
        code === 60 || // <
        code === 61 || // =
        code === 62 || // >
        code === 63 || // ?
        code === 64 || // @
        code === 91 || // [
        code === 92 || // \
        code === 93 || // ]
        code === 123 || // {
        code === 125) {
          return false;
        }
      }
      return true;
    }
    function isValidStatusCode(code) {
      if (code >= 1e3 && code < 1015) {
        return code !== 1004 && // reserved
        code !== 1005 && // "MUST NOT be set as a status code"
        code !== 1006;
      }
      return code >= 3e3 && code <= 4999;
    }
    function isControlFrame(opcode) {
      return opcode === opcodes.CLOSE || opcode === opcodes.PING || opcode === opcodes.PONG;
    }
    function isContinuationFrame(opcode) {
      return opcode === opcodes.CONTINUATION;
    }
    function isTextBinaryFrame(opcode) {
      return opcode === opcodes.TEXT || opcode === opcodes.BINARY;
    }
    function isValidOpcode(opcode) {
      return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode);
    }
    function parseExtensions(extensions) {
      const position = { position: 0 };
      const extensionList = /* @__PURE__ */ new Map();
      while (position.position < extensions.length) {
        const pair = collectASequenceOfCodePointsFast(";", extensions, position);
        const [name, value = ""] = pair.split("=", 2);
        extensionList.set(
          removeHTTPWhitespace(name, true, false),
          removeHTTPWhitespace(value, false, true)
        );
        position.position++;
      }
      return extensionList;
    }
    function isValidClientWindowBits(value) {
      if (value.length === 0) {
        return false;
      }
      for (let i = 0; i < value.length; i++) {
        const byte = value.charCodeAt(i);
        if (byte < 48 || byte > 57) {
          return false;
        }
      }
      const num2 = Number.parseInt(value, 10);
      return num2 >= 8 && num2 <= 15;
    }
    function getURLRecord(url, baseURL) {
      let urlRecord;
      try {
        urlRecord = new URL(url, baseURL);
      } catch (e7) {
        throw new DOMException(e7, "SyntaxError");
      }
      if (urlRecord.protocol === "http:") {
        urlRecord.protocol = "ws:";
      } else if (urlRecord.protocol === "https:") {
        urlRecord.protocol = "wss:";
      }
      if (urlRecord.protocol !== "ws:" && urlRecord.protocol !== "wss:") {
        throw new DOMException("expected a ws: or wss: url", "SyntaxError");
      }
      if (urlRecord.hash.length || urlRecord.href.endsWith("#")) {
        throw new DOMException("hash", "SyntaxError");
      }
      return urlRecord;
    }
    function validateCloseCodeAndReason(code, reason) {
      if (code !== null) {
        if (code !== 1e3 && (code < 3e3 || code > 4999)) {
          throw new DOMException("invalid code", "InvalidAccessError");
        }
      }
      if (reason !== null) {
        const reasonBytesLength = Buffer.byteLength(reason);
        if (reasonBytesLength > 123) {
          throw new DOMException(`Reason must be less than 123 bytes; received ${reasonBytesLength}`, "SyntaxError");
        }
      }
    }
    var utf8Decode = (() => {
      if (typeof process.versions.icu === "string") {
        const fatalDecoder = new TextDecoder("utf-8", { fatal: true });
        return fatalDecoder.decode.bind(fatalDecoder);
      }
      return function(buffer2) {
        if (isUtf8(buffer2)) {
          return buffer2.toString("utf-8");
        }
        throw new TypeError("Invalid utf-8 received.");
      };
    })();
    module.exports = {
      isConnecting,
      isEstablished,
      isClosing,
      isClosed,
      fireEvent,
      isValidSubprotocol,
      isValidStatusCode,
      websocketMessageReceived,
      utf8Decode,
      isControlFrame,
      isContinuationFrame,
      isTextBinaryFrame,
      isValidOpcode,
      parseExtensions,
      isValidClientWindowBits,
      toArrayBuffer: toArrayBuffer2,
      getURLRecord,
      validateCloseCodeAndReason
    };
  }
});

// node_modules/undici/lib/web/websocket/frame.js
var require_frame = __commonJS({
  "node_modules/undici/lib/web/websocket/frame.js"(exports, module) {
    "use strict";
    var { runtimeFeatures } = require_runtime_features();
    var { maxUnsigned16Bit, opcodes } = require_constants6();
    var BUFFER_SIZE = 8 * 1024;
    var buffer2 = null;
    var bufIdx = BUFFER_SIZE;
    var randomFillSync = runtimeFeatures.has("crypto") ? __require("crypto").randomFillSync : null;
    function generateMask() {
      if (bufIdx === BUFFER_SIZE) {
        bufIdx = 0;
        randomFillSync(buffer2 ??= Buffer.allocUnsafeSlow(BUFFER_SIZE), 0, BUFFER_SIZE);
      }
      return [buffer2[bufIdx++], buffer2[bufIdx++], buffer2[bufIdx++], buffer2[bufIdx++]];
    }
    var WebsocketFrameSend = class {
      /**
       * @param {Buffer|undefined} data
       */
      constructor(data) {
        this.frameData = data;
      }
      createFrame(opcode) {
        const frameData = this.frameData;
        const maskKey = generateMask();
        const bodyLength = frameData?.byteLength ?? 0;
        let payloadLength = bodyLength;
        let offset = 6;
        if (bodyLength > maxUnsigned16Bit) {
          offset += 8;
          payloadLength = 127;
        } else if (bodyLength > 125) {
          offset += 2;
          payloadLength = 126;
        }
        const buffer3 = Buffer.allocUnsafe(bodyLength + offset);
        buffer3[0] = buffer3[1] = 0;
        buffer3[0] |= 128;
        buffer3[0] = (buffer3[0] & 240) + opcode;
        buffer3[offset - 4] = maskKey[0];
        buffer3[offset - 3] = maskKey[1];
        buffer3[offset - 2] = maskKey[2];
        buffer3[offset - 1] = maskKey[3];
        buffer3[1] = payloadLength;
        if (payloadLength === 126) {
          buffer3.writeUInt16BE(bodyLength, 2);
        } else if (payloadLength === 127) {
          buffer3[2] = buffer3[3] = 0;
          buffer3.writeUIntBE(bodyLength, 4, 6);
        }
        buffer3[1] |= 128;
        for (let i = 0; i < bodyLength; ++i) {
          buffer3[offset + i] = frameData[i] ^ maskKey[i & 3];
        }
        return buffer3;
      }
      /**
       * @param {Uint8Array} buffer
       */
      static createFastTextFrame(buffer3) {
        const maskKey = generateMask();
        const bodyLength = buffer3.length;
        for (let i = 0; i < bodyLength; ++i) {
          buffer3[i] ^= maskKey[i & 3];
        }
        let payloadLength = bodyLength;
        let offset = 6;
        if (bodyLength > maxUnsigned16Bit) {
          offset += 8;
          payloadLength = 127;
        } else if (bodyLength > 125) {
          offset += 2;
          payloadLength = 126;
        }
        const head = Buffer.allocUnsafeSlow(offset);
        head[0] = 128 | opcodes.TEXT;
        head[1] = payloadLength | 128;
        head[offset - 4] = maskKey[0];
        head[offset - 3] = maskKey[1];
        head[offset - 2] = maskKey[2];
        head[offset - 1] = maskKey[3];
        if (payloadLength === 126) {
          head.writeUInt16BE(bodyLength, 2);
        } else if (payloadLength === 127) {
          head[2] = head[3] = 0;
          head.writeUIntBE(bodyLength, 4, 6);
        }
        return [head, buffer3];
      }
    };
    module.exports = {
      WebsocketFrameSend,
      generateMask
      // for benchmark
    };
  }
});

// node_modules/undici/lib/web/websocket/connection.js
var require_connection = __commonJS({
  "node_modules/undici/lib/web/websocket/connection.js"(exports, module) {
    "use strict";
    var { uid: uid2, states, sentCloseFrameState, emptyBuffer, opcodes } = require_constants6();
    var { parseExtensions, isClosed, isClosing, isEstablished, isConnecting, validateCloseCodeAndReason } = require_util5();
    var { makeRequest } = require_request2();
    var { fetching } = require_fetch();
    var { Headers, getHeadersList } = require_headers();
    var { getDecodeSplit } = require_util2();
    var { WebsocketFrameSend } = require_frame();
    var assert8 = __require("assert");
    var { runtimeFeatures } = require_runtime_features();
    var crypto6 = runtimeFeatures.has("crypto") ? __require("crypto") : null;
    var warningEmitted = false;
    function establishWebSocketConnection(url, protocols, client, handler, options) {
      const requestURL = url;
      requestURL.protocol = url.protocol === "ws:" ? "http:" : "https:";
      const request = makeRequest({
        urlList: [requestURL],
        client,
        serviceWorkers: "none",
        referrer: "no-referrer",
        mode: "websocket",
        credentials: "include",
        cache: "no-store",
        redirect: "error",
        useURLCredentials: true
      });
      if (options.headers) {
        const headersList = getHeadersList(new Headers(options.headers));
        request.headersList = headersList;
      }
      const keyValue = crypto6.randomBytes(16).toString("base64");
      request.headersList.append("sec-websocket-key", keyValue, true);
      request.headersList.append("sec-websocket-version", "13", true);
      for (const protocol of protocols) {
        request.headersList.append("sec-websocket-protocol", protocol, true);
      }
      const permessageDeflate = "permessage-deflate; client_max_window_bits";
      request.headersList.append("sec-websocket-extensions", permessageDeflate, true);
      const controller = fetching({
        request,
        useParallelQueue: true,
        dispatcher: options.dispatcher,
        processResponse(response) {
          if (response.type === "error" || response.status !== 101) {
            if (response.socket?.session == null) {
              failWebsocketConnection(handler, 1002, "Received network error or non-101 status code.", response.error);
              return;
            }
            if (response.status !== 200) {
              failWebsocketConnection(handler, 1002, "Received network error or non-200 status code.", response.error);
              return;
            }
          }
          if (warningEmitted === false && response.socket?.session != null) {
            process.emitWarning("WebSocket over HTTP2 is experimental, and subject to change.", "ExperimentalWarning");
            warningEmitted = true;
          }
          if (protocols.length !== 0 && !response.headersList.get("Sec-WebSocket-Protocol")) {
            failWebsocketConnection(handler, 1002, "Server did not respond with sent protocols.");
            return;
          }
          if (response.socket.session == null && response.headersList.get("Upgrade")?.toLowerCase() !== "websocket") {
            failWebsocketConnection(handler, 1002, 'Server did not set Upgrade header to "websocket".');
            return;
          }
          if (response.socket.session == null && response.headersList.get("Connection")?.toLowerCase() !== "upgrade") {
            failWebsocketConnection(handler, 1002, 'Server did not set Connection header to "upgrade".');
            return;
          }
          const secWSAccept = response.headersList.get("Sec-WebSocket-Accept");
          const digest = crypto6.hash("sha1", keyValue + uid2, "base64");
          if (secWSAccept !== digest) {
            failWebsocketConnection(handler, 1002, "Incorrect hash received in Sec-WebSocket-Accept header.");
            return;
          }
          const secExtension = response.headersList.get("Sec-WebSocket-Extensions");
          let extensions;
          if (secExtension !== null) {
            extensions = parseExtensions(secExtension);
            if (!extensions.has("permessage-deflate")) {
              failWebsocketConnection(handler, 1002, "Sec-WebSocket-Extensions header does not match.");
              return;
            }
          }
          const secProtocol = response.headersList.get("Sec-WebSocket-Protocol");
          if (secProtocol !== null) {
            const requestProtocols = getDecodeSplit("sec-websocket-protocol", request.headersList);
            if (!requestProtocols.includes(secProtocol)) {
              failWebsocketConnection(handler, 1002, "Protocol was not set in the opening handshake.");
              return;
            }
          }
          response.socket.on("data", handler.onSocketData);
          response.socket.on("close", handler.onSocketClose);
          response.socket.on("error", handler.onSocketError);
          handler.wasEverConnected = true;
          handler.onConnectionEstablished(response, extensions);
        }
      });
      return controller;
    }
    function closeWebSocketConnection(object, code, reason, validate6 = false) {
      code ??= null;
      reason ??= "";
      if (validate6) validateCloseCodeAndReason(code, reason);
      if (isClosed(object.readyState) || isClosing(object.readyState)) {
      } else if (!isEstablished(object.readyState)) {
        failWebsocketConnection(object);
        object.readyState = states.CLOSING;
      } else if (!object.closeState.has(sentCloseFrameState.SENT) && !object.closeState.has(sentCloseFrameState.RECEIVED)) {
        const frame = new WebsocketFrameSend();
        if (reason.length !== 0 && code === null) {
          code = 1e3;
        }
        assert8(code === null || Number.isInteger(code));
        if (code === null && reason.length === 0) {
          frame.frameData = emptyBuffer;
        } else if (code !== null && reason === null) {
          frame.frameData = Buffer.allocUnsafe(2);
          frame.frameData.writeUInt16BE(code, 0);
        } else if (code !== null && reason !== null) {
          frame.frameData = Buffer.allocUnsafe(2 + Buffer.byteLength(reason));
          frame.frameData.writeUInt16BE(code, 0);
          frame.frameData.write(reason, 2, "utf-8");
        } else {
          frame.frameData = emptyBuffer;
        }
        object.socket.write(frame.createFrame(opcodes.CLOSE));
        object.closeState.add(sentCloseFrameState.SENT);
        object.readyState = states.CLOSING;
      } else {
        object.readyState = states.CLOSING;
      }
    }
    function failWebsocketConnection(handler, code, reason, cause) {
      if (isEstablished(handler.readyState)) {
        closeWebSocketConnection(handler, code, reason, false);
      }
      handler.controller.abort();
      if (isConnecting(handler.readyState)) {
        handler.onSocketClose();
      } else if (handler.socket?.destroyed === false) {
        handler.socket.destroy();
      }
    }
    module.exports = {
      establishWebSocketConnection,
      failWebsocketConnection,
      closeWebSocketConnection
    };
  }
});

// node_modules/undici/lib/web/websocket/permessage-deflate.js
var require_permessage_deflate2 = __commonJS({
  "node_modules/undici/lib/web/websocket/permessage-deflate.js"(exports, module) {
    "use strict";
    var { createInflateRaw, Z_DEFAULT_WINDOWBITS } = __require("zlib");
    var { isValidClientWindowBits } = require_util5();
    var { MessageSizeExceededError } = require_errors();
    var tail = Buffer.from([0, 0, 255, 255]);
    var kBuffer = /* @__PURE__ */ Symbol("kBuffer");
    var kLength = /* @__PURE__ */ Symbol("kLength");
    var PerMessageDeflate2 = class {
      /** @type {import('node:zlib').InflateRaw} */
      #inflate;
      #options = {};
      #maxPayloadSize = 0;
      /**
       * @param {Map<string, string>} extensions
       */
      constructor(extensions, options) {
        this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover");
        this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits");
        this.#maxPayloadSize = options.maxPayloadSize;
      }
      /**
       * Decompress a compressed payload.
       * @param {Buffer} chunk Compressed data
       * @param {boolean} fin Final fragment flag
       * @param {Function} callback Callback function
       */
      decompress(chunk, fin, callback) {
        if (!this.#inflate) {
          let windowBits = Z_DEFAULT_WINDOWBITS;
          if (this.#options.serverMaxWindowBits) {
            if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) {
              callback(new Error("Invalid server_max_window_bits"));
              return;
            }
            windowBits = Number.parseInt(this.#options.serverMaxWindowBits);
          }
          try {
            this.#inflate = createInflateRaw({ windowBits });
          } catch (err) {
            callback(err);
            return;
          }
          this.#inflate[kBuffer] = [];
          this.#inflate[kLength] = 0;
          this.#inflate.on("data", (data) => {
            this.#inflate[kLength] += data.length;
            if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) {
              callback(new MessageSizeExceededError());
              this.#inflate.removeAllListeners();
              this.#inflate = null;
              return;
            }
            this.#inflate[kBuffer].push(data);
          });
          this.#inflate.on("error", (err) => {
            this.#inflate = null;
            callback(err);
          });
        }
        this.#inflate.write(chunk);
        if (fin) {
          this.#inflate.write(tail);
        }
        this.#inflate.flush(() => {
          if (!this.#inflate) {
            return;
          }
          const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength]);
          this.#inflate[kBuffer].length = 0;
          this.#inflate[kLength] = 0;
          callback(null, full);
        });
      }
    };
    module.exports = { PerMessageDeflate: PerMessageDeflate2 };
  }
});

// node_modules/undici/lib/web/websocket/receiver.js
var require_receiver2 = __commonJS({
  "node_modules/undici/lib/web/websocket/receiver.js"(exports, module) {
    "use strict";
    var { Writable } = __require("stream");
    var assert8 = __require("assert");
    var { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = require_constants6();
    var {
      isValidStatusCode,
      isValidOpcode,
      websocketMessageReceived,
      utf8Decode,
      isControlFrame,
      isTextBinaryFrame,
      isContinuationFrame
    } = require_util5();
    var { failWebsocketConnection } = require_connection();
    var { WebsocketFrameSend } = require_frame();
    var { PerMessageDeflate: PerMessageDeflate2 } = require_permessage_deflate2();
    var { MessageSizeExceededError } = require_errors();
    var ByteParser = class extends Writable {
      #buffers = [];
      #fragmentsBytes = 0;
      #byteOffset = 0;
      #loop = false;
      #state = parserStates.INFO;
      #info = {};
      #fragments = [];
      /** @type {Map<string, PerMessageDeflate>} */
      #extensions;
      /** @type {import('./websocket').Handler} */
      #handler;
      /** @type {number} */
      #maxPayloadSize;
      /**
       * @param {import('./websocket').Handler} handler
       * @param {Map<string, string>|null} extensions
       * @param {{ maxPayloadSize?: number }} [options]
       */
      constructor(handler, extensions, options = {}) {
        super();
        this.#handler = handler;
        this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions;
        this.#maxPayloadSize = options.maxPayloadSize ?? 0;
        if (this.#extensions.has("permessage-deflate")) {
          this.#extensions.set("permessage-deflate", new PerMessageDeflate2(extensions, options));
        }
      }
      /**
       * @param {Buffer} chunk
       * @param {() => void} callback
       */
      _write(chunk, _, callback) {
        this.#buffers.push(chunk);
        this.#byteOffset += chunk.length;
        this.#loop = true;
        this.run(callback);
      }
      #validatePayloadLength() {
        if (this.#maxPayloadSize > 0 && !isControlFrame(this.#info.opcode) && this.#info.payloadLength > this.#maxPayloadSize) {
          failWebsocketConnection(this.#handler, 1009, "Payload size exceeds maximum allowed size");
          return false;
        }
        return true;
      }
      /**
       * Runs whenever a new chunk is received.
       * Callback is called whenever there are no more chunks buffering,
       * or not enough bytes are buffered to parse.
       */
      run(callback) {
        while (this.#loop) {
          if (this.#state === parserStates.INFO) {
            if (this.#byteOffset < 2) {
              return callback();
            }
            const buffer2 = this.consume(2);
            const fin = (buffer2[0] & 128) !== 0;
            const opcode = buffer2[0] & 15;
            const masked = (buffer2[1] & 128) === 128;
            const fragmented = !fin && opcode !== opcodes.CONTINUATION;
            const payloadLength = buffer2[1] & 127;
            const rsv1 = buffer2[0] & 64;
            const rsv2 = buffer2[0] & 32;
            const rsv3 = buffer2[0] & 16;
            if (!isValidOpcode(opcode)) {
              failWebsocketConnection(this.#handler, 1002, "Invalid opcode received");
              return callback();
            }
            if (masked) {
              failWebsocketConnection(this.#handler, 1002, "Frame cannot be masked");
              return callback();
            }
            if (rsv1 !== 0 && !this.#extensions.has("permessage-deflate")) {
              failWebsocketConnection(this.#handler, 1002, "Expected RSV1 to be clear.");
              return;
            }
            if (rsv2 !== 0 || rsv3 !== 0) {
              failWebsocketConnection(this.#handler, 1002, "RSV1, RSV2, RSV3 must be clear");
              return;
            }
            if (fragmented && !isTextBinaryFrame(opcode)) {
              failWebsocketConnection(this.#handler, 1002, "Invalid frame type was fragmented.");
              return;
            }
            if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) {
              failWebsocketConnection(this.#handler, 1002, "Expected continuation frame");
              return;
            }
            if (this.#info.fragmented && fragmented) {
              failWebsocketConnection(this.#handler, 1002, "Fragmented frame exceeded 125 bytes.");
              return;
            }
            if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) {
              failWebsocketConnection(this.#handler, 1002, "Control frame either too large or fragmented");
              return;
            }
            if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) {
              failWebsocketConnection(this.#handler, 1002, "Unexpected continuation frame");
              return;
            }
            if (payloadLength <= 125) {
              this.#info.payloadLength = payloadLength;
              this.#state = parserStates.READ_DATA;
              if (!this.#validatePayloadLength()) {
                return;
              }
            } else if (payloadLength === 126) {
              this.#state = parserStates.PAYLOADLENGTH_16;
            } else if (payloadLength === 127) {
              this.#state = parserStates.PAYLOADLENGTH_64;
            }
            if (isTextBinaryFrame(opcode)) {
              this.#info.binaryType = opcode;
              this.#info.compressed = rsv1 !== 0;
            }
            this.#info.opcode = opcode;
            this.#info.masked = masked;
            this.#info.fin = fin;
            this.#info.fragmented = fragmented;
          } else if (this.#state === parserStates.PAYLOADLENGTH_16) {
            if (this.#byteOffset < 2) {
              return callback();
            }
            const buffer2 = this.consume(2);
            this.#info.payloadLength = buffer2.readUInt16BE(0);
            this.#state = parserStates.READ_DATA;
            if (!this.#validatePayloadLength()) {
              return;
            }
          } else if (this.#state === parserStates.PAYLOADLENGTH_64) {
            if (this.#byteOffset < 8) {
              return callback();
            }
            const buffer2 = this.consume(8);
            const upper = buffer2.readUInt32BE(0);
            const lower = buffer2.readUInt32BE(4);
            if (upper !== 0 || lower > 2 ** 31 - 1) {
              failWebsocketConnection(this.#handler, 1009, "Received payload length > 2^31 bytes.");
              return;
            }
            this.#info.payloadLength = lower;
            this.#state = parserStates.READ_DATA;
            if (!this.#validatePayloadLength()) {
              return;
            }
          } else if (this.#state === parserStates.READ_DATA) {
            if (this.#byteOffset < this.#info.payloadLength) {
              return callback();
            }
            const body = this.consume(this.#info.payloadLength);
            if (isControlFrame(this.#info.opcode)) {
              this.#loop = this.parseControlFrame(body);
              this.#state = parserStates.INFO;
            } else {
              if (!this.#info.compressed) {
                this.writeFragments(body);
                if (!this.#info.fragmented && this.#info.fin) {
                  websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
                }
                this.#state = parserStates.INFO;
              } else {
                this.#extensions.get("permessage-deflate").decompress(
                  body,
                  this.#info.fin,
                  (error, data) => {
                    if (error) {
                      const code = error instanceof MessageSizeExceededError ? 1009 : 1007;
                      failWebsocketConnection(this.#handler, code, error.message);
                      return;
                    }
                    this.writeFragments(data);
                    if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) {
                      failWebsocketConnection(this.#handler, 1009, new MessageSizeExceededError().message);
                      return;
                    }
                    if (!this.#info.fin) {
                      this.#state = parserStates.INFO;
                      this.#loop = true;
                      this.run(callback);
                      return;
                    }
                    websocketMessageReceived(this.#handler, this.#info.binaryType, this.consumeFragments());
                    this.#loop = true;
                    this.#state = parserStates.INFO;
                    this.run(callback);
                  },
                  this.#fragmentsBytes
                );
                this.#loop = false;
                break;
              }
            }
          }
        }
      }
      /**
       * Take n bytes from the buffered Buffers
       * @param {number} n
       * @returns {Buffer}
       */
      consume(n) {
        if (n > this.#byteOffset) {
          throw new Error("Called consume() before buffers satiated.");
        } else if (n === 0) {
          return emptyBuffer;
        }
        this.#byteOffset -= n;
        const first = this.#buffers[0];
        if (first.length > n) {
          this.#buffers[0] = first.subarray(n, first.length);
          return first.subarray(0, n);
        } else if (first.length === n) {
          return this.#buffers.shift();
        } else {
          let offset = 0;
          const buffer2 = Buffer.allocUnsafeSlow(n);
          while (offset !== n) {
            const next = this.#buffers[0];
            const length = next.length;
            if (length + offset === n) {
              buffer2.set(this.#buffers.shift(), offset);
              break;
            } else if (length + offset > n) {
              buffer2.set(next.subarray(0, n - offset), offset);
              this.#buffers[0] = next.subarray(n - offset);
              break;
            } else {
              buffer2.set(this.#buffers.shift(), offset);
              offset += length;
            }
          }
          return buffer2;
        }
      }
      writeFragments(fragment) {
        this.#fragmentsBytes += fragment.length;
        this.#fragments.push(fragment);
      }
      consumeFragments() {
        const fragments = this.#fragments;
        if (fragments.length === 1) {
          this.#fragmentsBytes = 0;
          return fragments.shift();
        }
        let offset = 0;
        const output = Buffer.allocUnsafeSlow(this.#fragmentsBytes);
        for (let i = 0; i < fragments.length; ++i) {
          const buffer2 = fragments[i];
          output.set(buffer2, offset);
          offset += buffer2.length;
        }
        this.#fragments = [];
        this.#fragmentsBytes = 0;
        return output;
      }
      parseCloseBody(data) {
        assert8(data.length !== 1);
        let code;
        if (data.length >= 2) {
          code = data.readUInt16BE(0);
        }
        if (code !== void 0 && !isValidStatusCode(code)) {
          return { code: 1002, reason: "Invalid status code", error: true };
        }
        let reason = data.subarray(2);
        if (reason[0] === 239 && reason[1] === 187 && reason[2] === 191) {
          reason = reason.subarray(3);
        }
        try {
          reason = utf8Decode(reason);
        } catch {
          return { code: 1007, reason: "Invalid UTF-8", error: true };
        }
        return { code, reason, error: false };
      }
      /**
       * Parses control frames.
       * @param {Buffer} body
       */
      parseControlFrame(body) {
        const { opcode, payloadLength } = this.#info;
        if (opcode === opcodes.CLOSE) {
          if (payloadLength === 1) {
            failWebsocketConnection(this.#handler, 1002, "Received close frame with a 1-byte body.");
            return false;
          }
          this.#info.closeInfo = this.parseCloseBody(body);
          if (this.#info.closeInfo.error) {
            const { code, reason } = this.#info.closeInfo;
            failWebsocketConnection(this.#handler, code, reason);
            return false;
          }
          if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
            let body2 = emptyBuffer;
            if (this.#info.closeInfo.code) {
              body2 = Buffer.allocUnsafe(2);
              body2.writeUInt16BE(this.#info.closeInfo.code, 0);
            }
            const closeFrame = new WebsocketFrameSend(body2);
            this.#handler.socket.write(closeFrame.createFrame(opcodes.CLOSE));
            this.#handler.closeState.add(sentCloseFrameState.SENT);
          }
          this.#handler.readyState = states.CLOSING;
          this.#handler.closeState.add(sentCloseFrameState.RECEIVED);
          return false;
        } else if (opcode === opcodes.PING) {
          if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
            const frame = new WebsocketFrameSend(body);
            this.#handler.socket.write(frame.createFrame(opcodes.PONG));
            this.#handler.onPing(body);
          }
        } else if (opcode === opcodes.PONG) {
          this.#handler.onPong(body);
        }
        return true;
      }
      get closingInfo() {
        return this.#info.closeInfo;
      }
    };
    module.exports = {
      ByteParser
    };
  }
});

// node_modules/undici/lib/web/websocket/sender.js
var require_sender2 = __commonJS({
  "node_modules/undici/lib/web/websocket/sender.js"(exports, module) {
    "use strict";
    var { WebsocketFrameSend } = require_frame();
    var { opcodes, sendHints } = require_constants6();
    var FixedQueue = require_fixed_queue();
    var SendQueue = class {
      /**
       * @type {FixedQueue}
       */
      #queue = new FixedQueue();
      /**
       * @type {boolean}
       */
      #running = false;
      /** @type {import('node:net').Socket} */
      #socket;
      constructor(socket) {
        this.#socket = socket;
      }
      add(item, cb, hint) {
        if (hint !== sendHints.blob) {
          if (!this.#running) {
            if (hint === sendHints.text) {
              const { 0: head, 1: body } = WebsocketFrameSend.createFastTextFrame(item);
              this.#socket.cork();
              this.#socket.write(head);
              this.#socket.write(body, cb);
              this.#socket.uncork();
            } else {
              this.#socket.write(createFrame(item, hint), cb);
            }
          } else {
            const node2 = {
              promise: null,
              callback: cb,
              frame: createFrame(item, hint)
            };
            this.#queue.push(node2);
          }
          return;
        }
        const node = {
          promise: item.arrayBuffer().then((ab) => {
            node.promise = null;
            node.frame = createFrame(ab, hint);
          }),
          callback: cb,
          frame: null
        };
        this.#queue.push(node);
        if (!this.#running) {
          this.#run();
        }
      }
      async #run() {
        this.#running = true;
        const queue = this.#queue;
        while (!queue.isEmpty()) {
          const node = queue.shift();
          if (node.promise !== null) {
            await node.promise;
          }
          this.#socket.write(node.frame, node.callback);
          node.callback = node.frame = null;
        }
        this.#running = false;
      }
    };
    function createFrame(data, hint) {
      return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.text ? opcodes.TEXT : opcodes.BINARY);
    }
    function toBuffer(data, hint) {
      switch (hint) {
        case sendHints.text:
        case sendHints.typedArray:
          return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
        case sendHints.arrayBuffer:
        case sendHints.blob:
          return new Uint8Array(data);
      }
    }
    module.exports = { SendQueue };
  }
});

// node_modules/undici/lib/web/websocket/websocket.js
var require_websocket2 = __commonJS({
  "node_modules/undici/lib/web/websocket/websocket.js"(exports, module) {
    "use strict";
    var { isArrayBuffer } = __require("util/types");
    var { webidl } = require_webidl();
    var { URLSerializer } = require_data_url();
    var { environmentSettingsObject } = require_util2();
    var { staticPropertyDescriptors, states, sentCloseFrameState, sendHints, opcodes } = require_constants6();
    var {
      isConnecting,
      isEstablished,
      isClosing,
      isClosed,
      isValidSubprotocol,
      fireEvent,
      utf8Decode,
      toArrayBuffer: toArrayBuffer2,
      getURLRecord
    } = require_util5();
    var { establishWebSocketConnection, closeWebSocketConnection, failWebsocketConnection } = require_connection();
    var { ByteParser } = require_receiver2();
    var { kEnumerableProperty } = require_util();
    var { getGlobalDispatcher } = require_global2();
    var { ErrorEvent, CloseEvent, createFastMessageEvent } = require_events();
    var { SendQueue } = require_sender2();
    var { WebsocketFrameSend } = require_frame();
    var { channels } = require_diagnostics();
    function getSocketAddress(socket) {
      if (typeof socket?.address === "function") {
        return socket.address();
      }
      if (typeof socket?.session?.socket?.address === "function") {
        return socket.session.socket.address();
      }
      return null;
    }
    var WebSocket2 = class _WebSocket extends EventTarget {
      #events = {
        open: null,
        error: null,
        close: null,
        message: null
      };
      #bufferedAmount = 0;
      #protocol = "";
      #extensions = "";
      /** @type {SendQueue} */
      #sendQueue;
      /** @type {Handler} */
      #handler = {
        onConnectionEstablished: (response, extensions) => this.#onConnectionEstablished(response, extensions),
        onMessage: (opcode, data) => this.#onMessage(opcode, data),
        onParserError: (err) => failWebsocketConnection(this.#handler, null, err.message),
        onParserDrain: () => this.#onParserDrain(),
        onSocketData: (chunk) => {
          if (!this.#parser.write(chunk)) {
            this.#handler.socket.pause();
          }
        },
        onSocketError: (err) => {
          this.#handler.readyState = states.CLOSING;
          if (channels.socketError.hasSubscribers) {
            channels.socketError.publish(err);
          }
          this.#handler.socket.destroy();
        },
        onSocketClose: () => this.#onSocketClose(),
        onPing: (body) => {
          if (channels.ping.hasSubscribers) {
            channels.ping.publish({
              payload: body,
              websocket: this
            });
          }
        },
        onPong: (body) => {
          if (channels.pong.hasSubscribers) {
            channels.pong.publish({
              payload: body,
              websocket: this
            });
          }
        },
        readyState: states.CONNECTING,
        socket: null,
        closeState: /* @__PURE__ */ new Set(),
        controller: null,
        wasEverConnected: false
      };
      #url;
      #binaryType;
      /** @type {import('./receiver').ByteParser} */
      #parser;
      /**
       * @param {string} url
       * @param {string|string[]} protocols
       */
      constructor(url, protocols = []) {
        super();
        webidl.util.markAsUncloneable(this);
        const prefix = "WebSocket constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        const options = webidl.converters["DOMString or sequence<DOMString> or WebSocketInit"](protocols, prefix, "options");
        url = webidl.converters.USVString(url);
        protocols = options.protocols;
        const baseURL = environmentSettingsObject.settingsObject.baseUrl;
        const urlRecord = getURLRecord(url, baseURL);
        if (typeof protocols === "string") {
          protocols = [protocols];
        }
        if (protocols.length !== new Set(protocols.map((p) => p.toLowerCase())).size) {
          throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
        }
        if (protocols.length > 0 && !protocols.every((p) => isValidSubprotocol(p))) {
          throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
        }
        this.#url = new URL(urlRecord.href);
        const client = environmentSettingsObject.settingsObject;
        this.#handler.controller = establishWebSocketConnection(
          urlRecord,
          protocols,
          client,
          this.#handler,
          options
        );
        this.#handler.readyState = _WebSocket.CONNECTING;
        this.#binaryType = "blob";
      }
      /**
       * @see https://websockets.spec.whatwg.org/#dom-websocket-close
       * @param {number|undefined} code
       * @param {string|undefined} reason
       */
      close(code = void 0, reason = void 0) {
        webidl.brandCheck(this, _WebSocket);
        const prefix = "WebSocket.close";
        if (code !== void 0) {
          code = webidl.converters["unsigned short"](code, prefix, "code", webidl.attributes.Clamp);
        }
        if (reason !== void 0) {
          reason = webidl.converters.USVString(reason);
        }
        code ??= null;
        reason ??= "";
        closeWebSocketConnection(this.#handler, code, reason, true);
      }
      /**
       * @see https://websockets.spec.whatwg.org/#dom-websocket-send
       * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data
       */
      send(data) {
        webidl.brandCheck(this, _WebSocket);
        const prefix = "WebSocket.send";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        data = webidl.converters.WebSocketSendData(data, prefix, "data");
        if (isConnecting(this.#handler.readyState)) {
          throw new DOMException("Sent before connected.", "InvalidStateError");
        }
        if (!isEstablished(this.#handler.readyState) || isClosing(this.#handler.readyState)) {
          return;
        }
        if (typeof data === "string") {
          const buffer2 = Buffer.from(data);
          this.#bufferedAmount += buffer2.byteLength;
          this.#sendQueue.add(buffer2, () => {
            this.#bufferedAmount -= buffer2.byteLength;
          }, sendHints.text);
        } else if (isArrayBuffer(data)) {
          this.#bufferedAmount += data.byteLength;
          this.#sendQueue.add(data, () => {
            this.#bufferedAmount -= data.byteLength;
          }, sendHints.arrayBuffer);
        } else if (ArrayBuffer.isView(data)) {
          this.#bufferedAmount += data.byteLength;
          this.#sendQueue.add(data, () => {
            this.#bufferedAmount -= data.byteLength;
          }, sendHints.typedArray);
        } else if (webidl.is.Blob(data)) {
          this.#bufferedAmount += data.size;
          this.#sendQueue.add(data, () => {
            this.#bufferedAmount -= data.size;
          }, sendHints.blob);
        }
      }
      get readyState() {
        webidl.brandCheck(this, _WebSocket);
        return this.#handler.readyState;
      }
      get bufferedAmount() {
        webidl.brandCheck(this, _WebSocket);
        return this.#bufferedAmount;
      }
      get url() {
        webidl.brandCheck(this, _WebSocket);
        return URLSerializer(this.#url);
      }
      get extensions() {
        webidl.brandCheck(this, _WebSocket);
        return this.#extensions;
      }
      get protocol() {
        webidl.brandCheck(this, _WebSocket);
        return this.#protocol;
      }
      get onopen() {
        webidl.brandCheck(this, _WebSocket);
        return this.#events.open;
      }
      set onopen(fn) {
        webidl.brandCheck(this, _WebSocket);
        if (this.#events.open) {
          this.removeEventListener("open", this.#events.open);
        }
        const listener = webidl.converters.EventHandlerNonNull(fn);
        if (listener !== null) {
          this.addEventListener("open", listener);
          this.#events.open = fn;
        } else {
          this.#events.open = null;
        }
      }
      get onerror() {
        webidl.brandCheck(this, _WebSocket);
        return this.#events.error;
      }
      set onerror(fn) {
        webidl.brandCheck(this, _WebSocket);
        if (this.#events.error) {
          this.removeEventListener("error", this.#events.error);
        }
        const listener = webidl.converters.EventHandlerNonNull(fn);
        if (listener !== null) {
          this.addEventListener("error", listener);
          this.#events.error = fn;
        } else {
          this.#events.error = null;
        }
      }
      get onclose() {
        webidl.brandCheck(this, _WebSocket);
        return this.#events.close;
      }
      set onclose(fn) {
        webidl.brandCheck(this, _WebSocket);
        if (this.#events.close) {
          this.removeEventListener("close", this.#events.close);
        }
        const listener = webidl.converters.EventHandlerNonNull(fn);
        if (listener !== null) {
          this.addEventListener("close", listener);
          this.#events.close = fn;
        } else {
          this.#events.close = null;
        }
      }
      get onmessage() {
        webidl.brandCheck(this, _WebSocket);
        return this.#events.message;
      }
      set onmessage(fn) {
        webidl.brandCheck(this, _WebSocket);
        if (this.#events.message) {
          this.removeEventListener("message", this.#events.message);
        }
        const listener = webidl.converters.EventHandlerNonNull(fn);
        if (listener !== null) {
          this.addEventListener("message", listener);
          this.#events.message = fn;
        } else {
          this.#events.message = null;
        }
      }
      get binaryType() {
        webidl.brandCheck(this, _WebSocket);
        return this.#binaryType;
      }
      set binaryType(type) {
        webidl.brandCheck(this, _WebSocket);
        if (type !== "blob" && type !== "arraybuffer") {
          this.#binaryType = "blob";
        } else {
          this.#binaryType = type;
        }
      }
      /**
       * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
       */
      #onConnectionEstablished(response, parsedExtensions) {
        this.#handler.socket = response.socket;
        const maxPayloadSize = this.#handler.controller.dispatcher?.webSocketOptions?.maxPayloadSize;
        const parser = new ByteParser(this.#handler, parsedExtensions, {
          maxPayloadSize
        });
        parser.on("drain", () => this.#handler.onParserDrain());
        parser.on("error", (err) => this.#handler.onParserError(err));
        this.#parser = parser;
        this.#sendQueue = new SendQueue(response.socket);
        this.#handler.readyState = states.OPEN;
        const extensions = response.headersList.get("sec-websocket-extensions");
        if (extensions !== null) {
          this.#extensions = extensions;
        }
        const protocol = response.headersList.get("sec-websocket-protocol");
        if (protocol !== null) {
          this.#protocol = protocol;
        }
        fireEvent("open", this);
        if (channels.open.hasSubscribers) {
          const headers = response.headersList.entries;
          channels.open.publish({
            address: getSocketAddress(response.socket),
            protocol: this.#protocol,
            extensions: this.#extensions,
            websocket: this,
            handshakeResponse: {
              status: response.status,
              statusText: response.statusText,
              headers
            }
          });
        }
      }
      #onMessage(type, data) {
        if (this.#handler.readyState !== states.OPEN) {
          return;
        }
        let dataForEvent;
        if (type === opcodes.TEXT) {
          try {
            dataForEvent = utf8Decode(data);
          } catch {
            failWebsocketConnection(this.#handler, 1007, "Received invalid UTF-8 in text frame.");
            return;
          }
        } else if (type === opcodes.BINARY) {
          if (this.#binaryType === "blob") {
            dataForEvent = new Blob([data]);
          } else {
            dataForEvent = toArrayBuffer2(data);
          }
        }
        fireEvent("message", this, createFastMessageEvent, {
          origin: this.#url.origin,
          data: dataForEvent
        });
      }
      #onParserDrain() {
        this.#handler.socket.resume();
      }
      /**
       * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
       * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
       */
      #onSocketClose() {
        const wasClean = this.#handler.closeState.has(sentCloseFrameState.SENT) && this.#handler.closeState.has(sentCloseFrameState.RECEIVED);
        let code = 1005;
        let reason = "";
        const result = this.#parser?.closingInfo;
        if (result && !result.error) {
          code = result.code ?? 1005;
          reason = result.reason;
        }
        this.#handler.readyState = states.CLOSED;
        if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
          code = 1006;
          fireEvent("error", this, (type, init) => new ErrorEvent(type, init), {
            error: new TypeError(reason)
          });
        }
        fireEvent("close", this, (type, init) => new CloseEvent(type, init), {
          wasClean,
          code,
          reason
        });
        if (channels.close.hasSubscribers) {
          channels.close.publish({
            websocket: this,
            code,
            reason
          });
        }
      }
      /**
       * @param {WebSocket} ws
       * @param {Buffer|undefined} buffer
       */
      static ping(ws, buffer2) {
        if (Buffer.isBuffer(buffer2)) {
          if (buffer2.length > 125) {
            throw new TypeError("A PING frame cannot have a body larger than 125 bytes.");
          }
        } else if (buffer2 !== void 0) {
          throw new TypeError("Expected buffer payload");
        }
        const readyState = ws.#handler.readyState;
        if (isEstablished(readyState) && !isClosing(readyState) && !isClosed(readyState)) {
          const frame = new WebsocketFrameSend(buffer2);
          ws.#handler.socket.write(frame.createFrame(opcodes.PING));
        }
      }
    };
    var { ping } = WebSocket2;
    Reflect.deleteProperty(WebSocket2, "ping");
    WebSocket2.CONNECTING = WebSocket2.prototype.CONNECTING = states.CONNECTING;
    WebSocket2.OPEN = WebSocket2.prototype.OPEN = states.OPEN;
    WebSocket2.CLOSING = WebSocket2.prototype.CLOSING = states.CLOSING;
    WebSocket2.CLOSED = WebSocket2.prototype.CLOSED = states.CLOSED;
    Object.defineProperties(WebSocket2.prototype, {
      CONNECTING: staticPropertyDescriptors,
      OPEN: staticPropertyDescriptors,
      CLOSING: staticPropertyDescriptors,
      CLOSED: staticPropertyDescriptors,
      url: kEnumerableProperty,
      readyState: kEnumerableProperty,
      bufferedAmount: kEnumerableProperty,
      onopen: kEnumerableProperty,
      onerror: kEnumerableProperty,
      onclose: kEnumerableProperty,
      close: kEnumerableProperty,
      onmessage: kEnumerableProperty,
      binaryType: kEnumerableProperty,
      send: kEnumerableProperty,
      extensions: kEnumerableProperty,
      protocol: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "WebSocket",
        writable: false,
        enumerable: false,
        configurable: true
      }
    });
    Object.defineProperties(WebSocket2, {
      CONNECTING: staticPropertyDescriptors,
      OPEN: staticPropertyDescriptors,
      CLOSING: staticPropertyDescriptors,
      CLOSED: staticPropertyDescriptors
    });
    webidl.converters["sequence<DOMString>"] = webidl.sequenceConverter(
      webidl.converters.DOMString
    );
    webidl.converters["DOMString or sequence<DOMString>"] = function(V, prefix, argument) {
      if (webidl.util.Type(V) === webidl.util.Types.OBJECT && Symbol.iterator in V) {
        return webidl.converters["sequence<DOMString>"](V);
      }
      return webidl.converters.DOMString(V, prefix, argument);
    };
    webidl.converters.WebSocketInit = webidl.dictionaryConverter([
      {
        key: "protocols",
        converter: webidl.converters["DOMString or sequence<DOMString>"],
        defaultValue: () => []
      },
      {
        key: "dispatcher",
        converter: webidl.converters.any,
        defaultValue: () => getGlobalDispatcher()
      },
      {
        key: "headers",
        converter: webidl.nullableConverter(webidl.converters.HeadersInit)
      }
    ]);
    webidl.converters["DOMString or sequence<DOMString> or WebSocketInit"] = function(V) {
      if (webidl.util.Type(V) === webidl.util.Types.OBJECT && !(Symbol.iterator in V)) {
        return webidl.converters.WebSocketInit(V);
      }
      return { protocols: webidl.converters["DOMString or sequence<DOMString>"](V) };
    };
    webidl.converters.WebSocketSendData = function(V) {
      if (webidl.util.Type(V) === webidl.util.Types.OBJECT) {
        if (webidl.is.Blob(V)) {
          return V;
        }
        if (webidl.is.BufferSource(V)) {
          return V;
        }
      }
      return webidl.converters.USVString(V);
    };
    module.exports = {
      WebSocket: WebSocket2,
      ping
    };
  }
});

// node_modules/undici/lib/web/websocket/stream/websocketerror.js
var require_websocketerror = __commonJS({
  "node_modules/undici/lib/web/websocket/stream/websocketerror.js"(exports, module) {
    "use strict";
    var { webidl } = require_webidl();
    var { validateCloseCodeAndReason } = require_util5();
    var { kConstruct } = require_symbols();
    var { kEnumerableProperty } = require_util();
    function createInheritableDOMException() {
      class Test extends DOMException {
        get reason() {
          return "";
        }
      }
      if (new Test().reason !== void 0) {
        return DOMException;
      }
      return new Proxy(DOMException, {
        construct(target, args, newTarget) {
          const instance = Reflect.construct(target, args, target);
          Object.setPrototypeOf(instance, newTarget.prototype);
          return instance;
        }
      });
    }
    var WebSocketError = class _WebSocketError extends createInheritableDOMException() {
      #closeCode;
      #reason;
      constructor(message = "", init = void 0) {
        message = webidl.converters.DOMString(message, "WebSocketError", "message");
        super(message, "WebSocketError");
        if (init === kConstruct) {
          return;
        } else if (init !== null) {
          init = webidl.converters.WebSocketCloseInfo(init);
        }
        let code = init.closeCode ?? null;
        const reason = init.reason ?? "";
        validateCloseCodeAndReason(code, reason);
        if (reason.length !== 0 && code === null) {
          code = 1e3;
        }
        this.#closeCode = code;
        this.#reason = reason;
      }
      get closeCode() {
        return this.#closeCode;
      }
      get reason() {
        return this.#reason;
      }
      /**
       * @param {string} message
       * @param {number|null} code
       * @param {string} reason
       */
      static createUnvalidatedWebSocketError(message, code, reason) {
        const error = new _WebSocketError(message, kConstruct);
        error.#closeCode = code;
        error.#reason = reason;
        return error;
      }
    };
    var { createUnvalidatedWebSocketError } = WebSocketError;
    delete WebSocketError.createUnvalidatedWebSocketError;
    Object.defineProperties(WebSocketError.prototype, {
      closeCode: kEnumerableProperty,
      reason: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "WebSocketError",
        writable: false,
        enumerable: false,
        configurable: true
      }
    });
    webidl.is.WebSocketError = webidl.util.MakeTypeAssertion(WebSocketError);
    module.exports = { WebSocketError, createUnvalidatedWebSocketError };
  }
});

// node_modules/undici/lib/web/websocket/stream/websocketstream.js
var require_websocketstream = __commonJS({
  "node_modules/undici/lib/web/websocket/stream/websocketstream.js"(exports, module) {
    "use strict";
    var { addAbortListener } = __require("events");
    var { environmentSettingsObject, readableStreamClose } = require_util2();
    var { states, opcodes, sentCloseFrameState } = require_constants6();
    var { webidl } = require_webidl();
    var { getURLRecord, isValidSubprotocol, isEstablished, utf8Decode } = require_util5();
    var { establishWebSocketConnection, failWebsocketConnection, closeWebSocketConnection } = require_connection();
    var { channels } = require_diagnostics();
    var { WebsocketFrameSend } = require_frame();
    var { ByteParser } = require_receiver2();
    var { WebSocketError, createUnvalidatedWebSocketError } = require_websocketerror();
    var { kEnumerableProperty } = require_util();
    var { utf8DecodeBytes } = require_encoding();
    var emittedExperimentalWarning = false;
    var WebSocketStream = class {
      // Each WebSocketStream object has an associated url , which is a URL record .
      /** @type {URL} */
      #url;
      // Each WebSocketStream object has an associated opened promise , which is a promise.
      /** @type {ReturnType<typeof Promise.withResolvers>} */
      #openedPromise;
      // Each WebSocketStream object has an associated closed promise , which is a promise.
      /** @type {ReturnType<typeof Promise.withResolvers>} */
      #closedPromise;
      // Each WebSocketStream object has an associated readable stream , which is a ReadableStream .
      /** @type {ReadableStream} */
      #readableStream;
      /** @type {ReadableStreamDefaultController} */
      #readableStreamController;
      // Each WebSocketStream object has an associated writable stream , which is a WritableStream .
      /** @type {WritableStream} */
      #writableStream;
      // Each WebSocketStream object has an associated boolean handshake aborted , which is initially false.
      #handshakeAborted = false;
      /** @type {import('../websocket').Handler} */
      #handler = {
        // https://whatpr.org/websockets/48/7b748d3...d5570f3.html#feedback-to-websocket-stream-from-the-protocol
        onConnectionEstablished: (response, extensions) => this.#onConnectionEstablished(response, extensions),
        onMessage: (opcode, data) => this.#onMessage(opcode, data),
        onParserError: (err) => failWebsocketConnection(this.#handler, null, err.message),
        onParserDrain: () => this.#handler.socket.resume(),
        onSocketData: (chunk) => {
          if (!this.#parser.write(chunk)) {
            this.#handler.socket.pause();
          }
        },
        onSocketError: (err) => {
          this.#handler.readyState = states.CLOSING;
          if (channels.socketError.hasSubscribers) {
            channels.socketError.publish(err);
          }
          this.#handler.socket.destroy();
        },
        onSocketClose: () => this.#onSocketClose(),
        onPing: () => {
        },
        onPong: () => {
        },
        readyState: states.CONNECTING,
        socket: null,
        closeState: /* @__PURE__ */ new Set(),
        controller: null,
        wasEverConnected: false
      };
      /** @type {import('../receiver').ByteParser} */
      #parser;
      constructor(url, options = void 0) {
        if (!emittedExperimentalWarning) {
          process.emitWarning("WebSocketStream is experimental! Expect it to change at any time.", {
            code: "UNDICI-WSS"
          });
          emittedExperimentalWarning = true;
        }
        webidl.argumentLengthCheck(arguments, 1, "WebSocket");
        url = webidl.converters.USVString(url);
        if (options !== null) {
          options = webidl.converters.WebSocketStreamOptions(options);
        }
        const baseURL = environmentSettingsObject.settingsObject.baseUrl;
        const urlRecord = getURLRecord(url, baseURL);
        const protocols = options.protocols;
        if (protocols.length !== new Set(protocols.map((p) => p.toLowerCase())).size) {
          throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
        }
        if (protocols.length > 0 && !protocols.every((p) => isValidSubprotocol(p))) {
          throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
        }
        this.#url = urlRecord.toString();
        this.#openedPromise = Promise.withResolvers();
        this.#closedPromise = Promise.withResolvers();
        if (options.signal != null) {
          const signal = options.signal;
          if (signal.aborted) {
            this.#openedPromise.reject(signal.reason);
            this.#closedPromise.reject(signal.reason);
            return;
          }
          addAbortListener(signal, () => {
            if (!isEstablished(this.#handler.readyState)) {
              failWebsocketConnection(this.#handler);
              this.#handler.readyState = states.CLOSING;
              this.#openedPromise.reject(signal.reason);
              this.#closedPromise.reject(signal.reason);
              this.#handshakeAborted = true;
            }
          });
        }
        const client = environmentSettingsObject.settingsObject;
        this.#handler.controller = establishWebSocketConnection(
          urlRecord,
          protocols,
          client,
          this.#handler,
          options
        );
      }
      // The url getter steps are to return this 's url , serialized .
      get url() {
        return this.#url.toString();
      }
      // The opened getter steps are to return this 's opened promise .
      get opened() {
        return this.#openedPromise.promise;
      }
      // The closed getter steps are to return this 's closed promise .
      get closed() {
        return this.#closedPromise.promise;
      }
      // The close( closeInfo ) method steps are:
      close(closeInfo = void 0) {
        if (closeInfo !== null) {
          closeInfo = webidl.converters.WebSocketCloseInfo(closeInfo);
        }
        const code = closeInfo.closeCode ?? null;
        const reason = closeInfo.reason;
        closeWebSocketConnection(this.#handler, code, reason, true);
      }
      #write(chunk) {
        chunk = webidl.converters.WebSocketStreamWrite(chunk);
        const promise = Promise.withResolvers();
        let data = null;
        let opcode = null;
        if (webidl.is.BufferSource(chunk)) {
          data = new Uint8Array(ArrayBuffer.isView(chunk) ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength) : chunk.slice());
          opcode = opcodes.BINARY;
        } else {
          let string;
          try {
            string = webidl.converters.DOMString(chunk);
          } catch (e7) {
            promise.reject(e7);
            return promise.promise;
          }
          data = new TextEncoder().encode(string);
          opcode = opcodes.TEXT;
        }
        if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
          const frame = new WebsocketFrameSend(data);
          this.#handler.socket.write(frame.createFrame(opcode), () => {
            promise.resolve(void 0);
          });
        }
        return promise.promise;
      }
      /** @type {import('../websocket').Handler['onConnectionEstablished']} */
      #onConnectionEstablished(response, parsedExtensions) {
        this.#handler.socket = response.socket;
        const parser = new ByteParser(this.#handler, parsedExtensions);
        parser.on("drain", () => this.#handler.onParserDrain());
        parser.on("error", (err) => this.#handler.onParserError(err));
        this.#parser = parser;
        this.#handler.readyState = states.OPEN;
        const extensions = parsedExtensions ?? "";
        const protocol = response.headersList.get("sec-websocket-protocol") ?? "";
        const readable = new ReadableStream({
          start: (controller) => {
            this.#readableStreamController = controller;
          },
          cancel: (reason) => this.#cancel(reason)
        });
        const writable = new WritableStream({
          write: (chunk) => this.#write(chunk),
          close: () => closeWebSocketConnection(this.#handler, null, null),
          abort: (reason) => this.#closeUsingReason(reason)
        });
        this.#readableStream = readable;
        this.#writableStream = writable;
        this.#openedPromise.resolve({
          extensions,
          protocol,
          readable,
          writable
        });
      }
      /** @type {import('../websocket').Handler['onMessage']} */
      #onMessage(type, data) {
        if (this.#handler.readyState !== states.OPEN) {
          return;
        }
        let chunk;
        if (type === opcodes.TEXT) {
          try {
            chunk = utf8Decode(data);
          } catch {
            failWebsocketConnection(this.#handler, 1007, "Received invalid UTF-8 in text frame.");
            return;
          }
        } else if (type === opcodes.BINARY) {
          chunk = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
        }
        this.#readableStreamController.enqueue(chunk);
      }
      /** @type {import('../websocket').Handler['onSocketClose']} */
      #onSocketClose() {
        const wasClean = this.#handler.closeState.has(sentCloseFrameState.SENT) && this.#handler.closeState.has(sentCloseFrameState.RECEIVED);
        this.#handler.readyState = states.CLOSED;
        if (this.#handshakeAborted) {
          return;
        }
        if (!this.#handler.wasEverConnected) {
          this.#openedPromise.reject(new WebSocketError("Socket never opened"));
        }
        const result = this.#parser?.closingInfo;
        let code = result?.code ?? 1005;
        if (!this.#handler.closeState.has(sentCloseFrameState.SENT) && !this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
          code = 1006;
        }
        const reason = result?.reason == null ? "" : utf8DecodeBytes(Buffer.from(result.reason));
        if (wasClean) {
          readableStreamClose(this.#readableStreamController);
          if (!this.#writableStream.locked) {
            this.#writableStream.abort(new DOMException("A closed WebSocketStream cannot be written to", "InvalidStateError"));
          }
          this.#closedPromise.resolve({
            closeCode: code,
            reason
          });
        } else {
          const error = createUnvalidatedWebSocketError("unclean close", code, reason);
          this.#readableStreamController?.error(error);
          this.#writableStream?.abort(error);
          this.#closedPromise.reject(error);
        }
      }
      #closeUsingReason(reason) {
        let code = null;
        let reasonString = "";
        if (webidl.is.WebSocketError(reason)) {
          code = reason.closeCode;
          reasonString = reason.reason;
        }
        closeWebSocketConnection(this.#handler, code, reasonString);
      }
      //  To cancel a WebSocketStream stream given reason , close using reason giving stream and reason .
      #cancel(reason) {
        this.#closeUsingReason(reason);
      }
    };
    Object.defineProperties(WebSocketStream.prototype, {
      url: kEnumerableProperty,
      opened: kEnumerableProperty,
      closed: kEnumerableProperty,
      close: kEnumerableProperty,
      [Symbol.toStringTag]: {
        value: "WebSocketStream",
        writable: false,
        enumerable: false,
        configurable: true
      }
    });
    webidl.converters.WebSocketStreamOptions = webidl.dictionaryConverter([
      {
        key: "protocols",
        converter: webidl.sequenceConverter(webidl.converters.USVString),
        defaultValue: () => []
      },
      {
        key: "signal",
        converter: webidl.nullableConverter(webidl.converters.AbortSignal),
        defaultValue: () => null
      }
    ]);
    webidl.converters.WebSocketCloseInfo = webidl.dictionaryConverter([
      {
        key: "closeCode",
        converter: (V) => webidl.converters["unsigned short"](V, webidl.attributes.EnforceRange)
      },
      {
        key: "reason",
        converter: webidl.converters.USVString,
        defaultValue: () => ""
      }
    ]);
    webidl.converters.WebSocketStreamWrite = function(V) {
      if (typeof V === "string") {
        return webidl.converters.USVString(V);
      }
      return webidl.converters.BufferSource(V);
    };
    module.exports = { WebSocketStream };
  }
});

// node_modules/undici/lib/web/eventsource/util.js
var require_util6 = __commonJS({
  "node_modules/undici/lib/web/eventsource/util.js"(exports, module) {
    "use strict";
    function isValidLastEventId(value) {
      return value.indexOf("\0") === -1;
    }
    function isASCIINumber(value) {
      if (value.length === 0) return false;
      for (let i = 0; i < value.length; i++) {
        if (value.charCodeAt(i) < 48 || value.charCodeAt(i) > 57) return false;
      }
      return true;
    }
    module.exports = {
      isValidLastEventId,
      isASCIINumber
    };
  }
});

// node_modules/undici/lib/web/eventsource/eventsource-stream.js
var require_eventsource_stream = __commonJS({
  "node_modules/undici/lib/web/eventsource/eventsource-stream.js"(exports, module) {
    "use strict";
    var { Transform } = __require("stream");
    var { isASCIINumber, isValidLastEventId } = require_util6();
    var BOM = [239, 187, 191];
    var LF = 10;
    var CR = 13;
    var COLON = 58;
    var SPACE = 32;
    var DATA = Buffer.from("data");
    var EVENT = Buffer.from("event");
    var ID = Buffer.from("id");
    var RETRY = Buffer.from("retry");
    function isASCIINumberBytes(buffer2, start) {
      if (start >= buffer2.length) {
        return false;
      }
      for (let i = start; i < buffer2.length; i++) {
        if (buffer2[i] < 48 || buffer2[i] > 57) {
          return false;
        }
      }
      return true;
    }
    function isValidLastEventIdBytes(buffer2, start) {
      for (let i = start; i < buffer2.length; i++) {
        if (buffer2[i] === 0) {
          return false;
        }
      }
      return true;
    }
    function isFieldName(line, length, field) {
      if (length !== field.length) {
        return false;
      }
      for (let i = 0; i < length; i++) {
        if (line[i] !== field[i]) {
          return false;
        }
      }
      return true;
    }
    var EventSourceStream = class extends Transform {
      /**
       * @type {eventSourceSettings}
       */
      state;
      /**
       * Leading byte-order-mark check.
       * @type {boolean}
       */
      checkBOM = true;
      /**
       * @type {boolean}
       */
      crlfCheck = false;
      /**
       * @type {boolean}
       */
      eventEndCheck = false;
      /**
       * @type {Buffer[]}
       */
      chunks = [];
      chunkIndex = 0;
      pos = 0;
      lineChunkIndex = 0;
      linePos = 0;
      event = {
        data: void 0,
        event: void 0,
        id: void 0,
        retry: void 0
      };
      /**
       * @param {object} options
       * @param {boolean} [options.readableObjectMode]
       * @param {eventSourceSettings} [options.eventSourceSettings]
       * @param {(chunk: any, encoding?: BufferEncoding | undefined) => boolean} [options.push]
       */
      constructor(options = {}) {
        options.readableObjectMode = true;
        super(options);
        this.state = options.eventSourceSettings || {};
        if (options.push) {
          this.push = options.push;
        }
      }
      /**
       * @param {Buffer} chunk
       * @param {string} _encoding
       * @param {Function} callback
       * @returns {void}
       */
      _transform(chunk, _encoding, callback) {
        if (chunk.length === 0) {
          callback();
          return;
        }
        this.chunks.push(chunk);
        if (this.checkBOM) {
          if (this.handleBOM()) {
            callback();
            return;
          }
        }
        while (this.hasCurrentByte()) {
          const byte = this.currentByte();
          if (this.eventEndCheck) {
            if (this.crlfCheck) {
              if (byte === LF) {
                this.crlfCheck = false;
                this.consumeCurrentByte();
                continue;
              }
              this.crlfCheck = false;
            }
            if (byte === LF || byte === CR) {
              if (byte === CR) {
                this.crlfCheck = true;
              }
              this.consumeCurrentByte();
              if (this.hasPendingEvent()) {
                this.processEvent(this.event);
              }
              this.clearEvent();
              continue;
            }
            this.eventEndCheck = false;
            continue;
          }
          if (byte === LF || byte === CR) {
            if (byte === CR) {
              this.crlfCheck = true;
            }
            this.parseLine(this.readLine(), this.event);
            this.consumeCurrentByte();
            this.eventEndCheck = true;
            continue;
          }
          this.advanceCursor();
        }
        callback();
      }
      /**
       * @param {Buffer} line
       * @param {EventSourceStreamEvent} event
       */
      parseLine(line, event) {
        if (line.length === 0) {
          return;
        }
        const colonPosition = line.indexOf(COLON);
        if (colonPosition === 0) {
          return;
        }
        let fieldLength = line.length;
        let valueStart = line.length;
        if (colonPosition !== -1) {
          fieldLength = colonPosition;
          valueStart = colonPosition + 1;
          if (line[valueStart] === SPACE) {
            ++valueStart;
          }
        }
        if (isFieldName(line, fieldLength, DATA)) {
          const value = line.toString("utf8", valueStart);
          if (event.data === void 0) {
            event.data = value;
          } else {
            event.data += `
${value}`;
          }
          return;
        }
        if (isFieldName(line, fieldLength, RETRY)) {
          if (isASCIINumberBytes(line, valueStart)) {
            event.retry = line.toString("utf8", valueStart);
          }
          return;
        }
        if (isFieldName(line, fieldLength, ID)) {
          if (isValidLastEventIdBytes(line, valueStart)) {
            event.id = line.toString("utf8", valueStart);
          }
          return;
        }
        if (isFieldName(line, fieldLength, EVENT)) {
          const value = line.toString("utf8", valueStart);
          if (value.length > 0) {
            event.event = value;
          }
        }
      }
      /**
       * @param {EventSourceStreamEvent} event
       */
      processEvent(event) {
        if (event.retry && isASCIINumber(event.retry)) {
          this.state.reconnectionTime = parseInt(event.retry, 10);
        }
        if (event.id !== void 0 && isValidLastEventId(event.id)) {
          this.state.lastEventId = event.id;
        }
        if (event.data !== void 0) {
          this.push({
            type: event.event || "message",
            options: {
              data: event.data,
              lastEventId: this.state.lastEventId,
              origin: this.state.origin
            }
          });
        }
      }
      clearEvent() {
        this.event.data = void 0;
        this.event.event = void 0;
        this.event.id = void 0;
        this.event.retry = void 0;
      }
      hasPendingEvent() {
        return this.event.data !== void 0 || this.event.event !== void 0 || this.event.id !== void 0 || this.event.retry !== void 0;
      }
      hasCurrentByte() {
        return this.chunkIndex < this.chunks.length && this.pos < this.chunks[this.chunkIndex].length;
      }
      currentByte() {
        return this.chunks[this.chunkIndex][this.pos];
      }
      consumeCurrentByte() {
        this.advanceCursor();
        this.syncLineStartToCursor();
      }
      advanceCursor() {
        this.pos++;
        while (this.chunkIndex < this.chunks.length && this.pos >= this.chunks[this.chunkIndex].length) {
          this.chunkIndex++;
          this.pos = 0;
        }
      }
      syncLineStartToCursor() {
        this.lineChunkIndex = this.chunkIndex;
        this.linePos = this.pos;
        this.dropConsumedChunks();
      }
      dropConsumedChunks() {
        while (this.lineChunkIndex > 0) {
          this.chunks.shift();
          this.lineChunkIndex--;
          this.chunkIndex--;
        }
        if (this.chunkIndex === this.chunks.length) {
          this.chunks.length = 0;
          this.chunkIndex = 0;
          this.pos = 0;
          this.lineChunkIndex = 0;
          this.linePos = 0;
        }
      }
      readLine() {
        if (this.lineChunkIndex === this.chunkIndex) {
          return this.chunks[this.chunkIndex].subarray(this.linePos, this.pos);
        }
        const chunks = [];
        let length = 0;
        for (let i = this.lineChunkIndex; i <= this.chunkIndex; i++) {
          const chunk = this.chunks[i];
          const start = i === this.lineChunkIndex ? this.linePos : 0;
          const end = i === this.chunkIndex ? this.pos : chunk.length;
          const slice4 = chunk.subarray(start, end);
          length += slice4.length;
          chunks.push(slice4);
        }
        return Buffer.concat(chunks, length);
      }
      peekBufferedByte(offset) {
        let chunkIndex = this.lineChunkIndex;
        let pos = this.linePos;
        while (chunkIndex < this.chunks.length) {
          const chunk = this.chunks[chunkIndex];
          const remaining = chunk.length - pos;
          if (offset < remaining) {
            return chunk[pos + offset];
          }
          offset -= remaining;
          chunkIndex++;
          pos = 0;
        }
      }
      discardLeadingBytes(count) {
        while (count > 0 && this.lineChunkIndex < this.chunks.length) {
          const chunk = this.chunks[this.lineChunkIndex];
          const remaining = chunk.length - this.linePos;
          if (count < remaining) {
            this.linePos += count;
            count = 0;
          } else {
            count -= remaining;
            this.lineChunkIndex++;
            this.linePos = 0;
          }
        }
        this.chunkIndex = this.lineChunkIndex;
        this.pos = this.linePos;
        this.dropConsumedChunks();
      }
      handleBOM() {
        const first = this.peekBufferedByte(0);
        const second = this.peekBufferedByte(1);
        const third = this.peekBufferedByte(2);
        if (second === void 0) {
          if (first === BOM[0]) {
            return true;
          }
          this.checkBOM = false;
          return true;
        }
        if (third === void 0) {
          if (first === BOM[0] && second === BOM[1]) {
            return true;
          }
          this.checkBOM = false;
          return false;
        }
        if (first === BOM[0] && second === BOM[1] && third === BOM[2]) {
          this.discardLeadingBytes(3);
        }
        this.checkBOM = false;
        return !this.hasCurrentByte();
      }
    };
    module.exports = {
      EventSourceStream
    };
  }
});

// node_modules/undici/lib/web/eventsource/eventsource.js
var require_eventsource = __commonJS({
  "node_modules/undici/lib/web/eventsource/eventsource.js"(exports, module) {
    "use strict";
    var { pipeline } = __require("stream");
    var { fetching } = require_fetch();
    var { makeRequest } = require_request2();
    var { webidl } = require_webidl();
    var { EventSourceStream } = require_eventsource_stream();
    var { parseMIMEType } = require_data_url();
    var { createFastMessageEvent } = require_events();
    var { isNetworkError } = require_response();
    var { kEnumerableProperty } = require_util();
    var { environmentSettingsObject } = require_util2();
    var experimentalWarned = false;
    var defaultReconnectionTime = 3e3;
    var CONNECTING = 0;
    var OPEN = 1;
    var CLOSED = 2;
    var ANONYMOUS = "anonymous";
    var USE_CREDENTIALS = "use-credentials";
    var EventSource = class _EventSource extends EventTarget {
      #events = {
        open: null,
        error: null,
        message: null
      };
      #url;
      #withCredentials = false;
      /**
       * @type {ReadyState}
       */
      #readyState = CONNECTING;
      #request = null;
      #controller = null;
      #dispatcher;
      /**
       * @type {import('./eventsource-stream').eventSourceSettings}
       */
      #state;
      /**
       * Creates a new EventSource object.
       * @param {string} url
       * @param {EventSourceInit} [eventSourceInitDict={}]
       * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface
       */
      constructor(url, eventSourceInitDict = {}) {
        super();
        webidl.util.markAsUncloneable(this);
        const prefix = "EventSource constructor";
        webidl.argumentLengthCheck(arguments, 1, prefix);
        if (!experimentalWarned) {
          experimentalWarned = true;
          process.emitWarning("EventSource is experimental, expect them to change at any time.", {
            code: "UNDICI-ES"
          });
        }
        url = webidl.converters.USVString(url);
        eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, "eventSourceInitDict");
        this.#dispatcher = eventSourceInitDict.node.dispatcher || eventSourceInitDict.dispatcher;
        this.#state = {
          lastEventId: "",
          reconnectionTime: eventSourceInitDict.node.reconnectionTime
        };
        const settings = environmentSettingsObject;
        let urlRecord;
        try {
          urlRecord = new URL(url, settings.settingsObject.baseUrl);
          this.#state.origin = urlRecord.origin;
        } catch (e7) {
          throw new DOMException(e7, "SyntaxError");
        }
        this.#url = urlRecord.href;
        let corsAttributeState = ANONYMOUS;
        if (eventSourceInitDict.withCredentials === true) {
          corsAttributeState = USE_CREDENTIALS;
          this.#withCredentials = true;
        }
        const initRequest = {
          redirect: "follow",
          keepalive: true,
          // @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes
          mode: "cors",
          credentials: corsAttributeState === "anonymous" ? "same-origin" : "omit",
          referrer: "no-referrer"
        };
        initRequest.client = environmentSettingsObject.settingsObject;
        initRequest.headersList = [["accept", { name: "accept", value: "text/event-stream" }]];
        initRequest.cache = "no-store";
        initRequest.initiator = "other";
        initRequest.urlList = [new URL(this.#url)];
        this.#request = makeRequest(initRequest);
        this.#connect();
      }
      /**
       * Returns the state of this EventSource object's connection. It can have the
       * values described below.
       * @returns {ReadyState}
       * @readonly
       */
      get readyState() {
        return this.#readyState;
      }
      /**
       * Returns the URL providing the event stream.
       * @readonly
       * @returns {string}
       */
      get url() {
        return this.#url;
      }
      /**
       * Returns a boolean indicating whether the EventSource object was
       * instantiated with CORS credentials set (true), or not (false, the default).
       */
      get withCredentials() {
        return this.#withCredentials;
      }
      #connect() {
        if (this.#readyState === CLOSED) return;
        this.#readyState = CONNECTING;
        const fetchParams = {
          request: this.#request,
          dispatcher: this.#dispatcher
        };
        const processEventSourceEndOfBody = (response) => {
          if (!isNetworkError(response)) {
            return this.#reconnect();
          }
        };
        fetchParams.processResponseEndOfBody = processEventSourceEndOfBody;
        fetchParams.processResponse = (response) => {
          if (isNetworkError(response)) {
            if (response.aborted) {
              this.close();
              this.dispatchEvent(new Event("error"));
              return;
            } else {
              this.#reconnect();
              return;
            }
          }
          const contentType = response.headersList.get("content-type", true);
          const mimeType = contentType !== null ? parseMIMEType(contentType) : "failure";
          const contentTypeValid = mimeType !== "failure" && mimeType.essence === "text/event-stream";
          if (response.status !== 200 || contentTypeValid === false) {
            this.close();
            this.dispatchEvent(new Event("error"));
            return;
          }
          this.#readyState = OPEN;
          this.dispatchEvent(new Event("open"));
          this.#state.origin = response.urlList[response.urlList.length - 1].origin;
          const eventSourceStream = new EventSourceStream({
            eventSourceSettings: this.#state,
            push: (event) => {
              this.dispatchEvent(createFastMessageEvent(
                event.type,
                event.options
              ));
            }
          });
          pipeline(
            response.body.stream,
            eventSourceStream,
            (error) => {
              if (error?.aborted === false) {
                this.close();
                this.dispatchEvent(new Event("error"));
              }
            }
          );
        };
        this.#controller = fetching(fetchParams);
      }
      /**
       * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
       * @returns {void}
       */
      #reconnect() {
        if (this.#readyState === CLOSED) return;
        this.#readyState = CONNECTING;
        this.dispatchEvent(new Event("error"));
        setTimeout(() => {
          if (this.#readyState !== CONNECTING) return;
          if (this.#state.lastEventId.length) {
            this.#request.headersList.set("last-event-id", this.#state.lastEventId, true);
          }
          this.#connect();
        }, this.#state.reconnectionTime)?.unref();
      }
      /**
       * Closes the connection, if any, and sets the readyState attribute to
       * CLOSED.
       */
      close() {
        webidl.brandCheck(this, _EventSource);
        if (this.#readyState === CLOSED) return;
        this.#readyState = CLOSED;
        this.#controller.abort();
        this.#request = null;
      }
      get onopen() {
        return this.#events.open;
      }
      set onopen(fn) {
        if (this.#events.open) {
          this.removeEventListener("open", this.#events.open);
        }
        const listener = webidl.converters.EventHandlerNonNull(fn);
        if (listener !== null) {
          this.addEventListener("open", listener);
          this.#events.open = fn;
        } else {
          this.#events.open = null;
        }
      }
      get onmessage() {
        return this.#events.message;
      }
      set onmessage(fn) {
        if (this.#events.message) {
          this.removeEventListener("message", this.#events.message);
        }
        const listener = webidl.converters.EventHandlerNonNull(fn);
        if (listener !== null) {
          this.addEventListener("message", listener);
          this.#events.message = fn;
        } else {
          this.#events.message = null;
        }
      }
      get onerror() {
        return this.#events.error;
      }
      set onerror(fn) {
        if (this.#events.error) {
          this.removeEventListener("error", this.#events.error);
        }
        const listener = webidl.converters.EventHandlerNonNull(fn);
        if (listener !== null) {
          this.addEventListener("error", listener);
          this.#events.error = fn;
        } else {
          this.#events.error = null;
        }
      }
    };
    var constantsPropertyDescriptors = {
      CONNECTING: {
        __proto__: null,
        configurable: false,
        enumerable: true,
        value: CONNECTING,
        writable: false
      },
      OPEN: {
        __proto__: null,
        configurable: false,
        enumerable: true,
        value: OPEN,
        writable: false
      },
      CLOSED: {
        __proto__: null,
        configurable: false,
        enumerable: true,
        value: CLOSED,
        writable: false
      }
    };
    Object.defineProperties(EventSource, constantsPropertyDescriptors);
    Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors);
    Object.defineProperties(EventSource.prototype, {
      close: kEnumerableProperty,
      onerror: kEnumerableProperty,
      onmessage: kEnumerableProperty,
      onopen: kEnumerableProperty,
      readyState: kEnumerableProperty,
      url: kEnumerableProperty,
      withCredentials: kEnumerableProperty
    });
    webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([
      {
        key: "withCredentials",
        converter: webidl.converters.boolean,
        defaultValue: () => false
      },
      {
        key: "dispatcher",
        // undici only
        converter: webidl.converters.any
      },
      {
        key: "node",
        // undici only
        converter: webidl.dictionaryConverter([
          {
            key: "reconnectionTime",
            converter: webidl.converters["unsigned long"],
            defaultValue: () => defaultReconnectionTime
          },
          {
            key: "dispatcher",
            converter: webidl.converters.any
          }
        ]),
        defaultValue: () => ({})
      }
    ]);
    module.exports = {
      EventSource,
      defaultReconnectionTime
    };
  }
});

// node_modules/undici/index.js
var require_undici = __commonJS({
  "node_modules/undici/index.js"(exports, module) {
    "use strict";
    var Client = require_client();
    var Dispatcher = require_dispatcher();
    var Pool = require_pool();
    var BalancedPool = require_balanced_pool();
    var RoundRobinPool = require_round_robin_pool();
    var Agent = require_agent();
    var Dispatcher1Wrapper = require_dispatcher1_wrapper();
    var ProxyAgent = require_proxy_agent();
    var Socks5ProxyAgent = require_socks5_proxy_agent();
    var EnvHttpProxyAgent = require_env_http_proxy_agent();
    var RetryAgent = require_retry_agent();
    var H2CClient = require_h2c_client();
    var errors = require_errors();
    var util2 = require_util();
    var { InvalidArgumentError } = errors;
    var api = require_api();
    var buildConnector = require_connect();
    var MockClient = require_mock_client();
    var { MockCallHistory, MockCallHistoryLog } = require_mock_call_history();
    var MockAgent = require_mock_agent();
    var MockPool = require_mock_pool();
    var SnapshotAgent = require_snapshot_agent();
    var mockErrors = require_mock_errors();
    var RetryHandler = require_retry_handler();
    var { getGlobalDispatcher, setGlobalDispatcher } = require_global2();
    var DecoratorHandler = require_decorator_handler();
    var RedirectHandler = require_redirect_handler();
    Object.assign(Dispatcher.prototype, api);
    module.exports.Dispatcher = Dispatcher;
    module.exports.Client = Client;
    module.exports.Pool = Pool;
    module.exports.BalancedPool = BalancedPool;
    module.exports.RoundRobinPool = RoundRobinPool;
    module.exports.Agent = Agent;
    module.exports.Dispatcher1Wrapper = Dispatcher1Wrapper;
    module.exports.ProxyAgent = ProxyAgent;
    module.exports.Socks5ProxyAgent = Socks5ProxyAgent;
    module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent;
    module.exports.RetryAgent = RetryAgent;
    module.exports.H2CClient = H2CClient;
    module.exports.RetryHandler = RetryHandler;
    module.exports.DecoratorHandler = DecoratorHandler;
    module.exports.RedirectHandler = RedirectHandler;
    module.exports.interceptors = {
      redirect: require_redirect(),
      responseError: require_response_error(),
      retry: require_retry(),
      dump: require_dump(),
      dns: require_dns(),
      cache: require_cache2(),
      decompress: require_decompress(),
      deduplicate: require_deduplicate()
    };
    module.exports.cacheStores = {
      MemoryCacheStore: require_memory_cache_store()
    };
    var SqliteCacheStore = require_sqlite_cache_store();
    module.exports.cacheStores.SqliteCacheStore = SqliteCacheStore;
    module.exports.buildConnector = buildConnector;
    module.exports.errors = errors;
    module.exports.util = {
      parseHeaders: util2.parseHeaders,
      headerNameToString: util2.headerNameToString
    };
    function makeDispatcher(fn) {
      return (url, opts, handler) => {
        if (typeof opts === "function") {
          handler = opts;
          opts = null;
        }
        if (!url || typeof url !== "string" && typeof url !== "object" && !(url instanceof URL)) {
          throw new InvalidArgumentError("invalid url");
        }
        if (opts != null && typeof opts !== "object") {
          throw new InvalidArgumentError("invalid opts");
        }
        if (opts && opts.path != null) {
          if (typeof opts.path !== "string") {
            throw new InvalidArgumentError("invalid opts.path");
          }
          let path2 = opts.path;
          if (!opts.path.startsWith("/")) {
            path2 = `/${path2}`;
          }
          url = new URL(util2.parseOrigin(url).origin + path2);
        } else {
          if (!opts) {
            opts = typeof url === "object" ? url : {};
          }
          url = util2.parseURL(url);
        }
        const { agent, dispatcher = getGlobalDispatcher(), ...restOpts } = opts;
        if (agent) {
          throw new InvalidArgumentError("unsupported opts.agent. Did you mean opts.client?");
        }
        return fn.call(dispatcher, {
          ...restOpts,
          origin: url.origin,
          path: url.search ? `${url.pathname}${url.search}` : url.pathname,
          method: opts.method || (opts.body ? "PUT" : "GET")
        }, handler);
      };
    }
    module.exports.setGlobalDispatcher = setGlobalDispatcher;
    module.exports.getGlobalDispatcher = getGlobalDispatcher;
    var fetchImpl = require_fetch().fetch;
    var currentFilename = typeof __filename !== "undefined" ? __filename : void 0;
    function appendFetchStackTrace(err, filename) {
      if (!err || typeof err !== "object") {
        return;
      }
      const stack = typeof err.stack === "string" ? err.stack : "";
      const normalizedFilename = filename.replace(/\\/g, "/");
      if (stack && (stack.includes(filename) || stack.includes(normalizedFilename))) {
        return;
      }
      const capture = {};
      Error.captureStackTrace(capture, appendFetchStackTrace);
      if (!capture.stack) {
        return;
      }
      const captureLines = capture.stack.split("\n").slice(1).join("\n");
      err.stack = stack ? `${stack}
${captureLines}` : capture.stack;
    }
    module.exports.fetch = function fetch2(init, options = void 0) {
      return fetchImpl(init, options).catch((err) => {
        if (currentFilename) {
          appendFetchStackTrace(err, currentFilename);
        } else if (err && typeof err === "object") {
          Error.captureStackTrace(err, module.exports.fetch);
        }
        throw err;
      });
    };
    module.exports.Headers = require_headers().Headers;
    module.exports.Response = require_response().Response;
    module.exports.Request = require_request2().Request;
    module.exports.FormData = require_formdata().FormData;
    var { setGlobalOrigin, getGlobalOrigin } = require_global();
    module.exports.setGlobalOrigin = setGlobalOrigin;
    module.exports.getGlobalOrigin = getGlobalOrigin;
    var { CacheStorage } = require_cachestorage();
    var { kConstruct } = require_symbols();
    module.exports.caches = new CacheStorage(kConstruct);
    var { deleteCookie, getCookies, getSetCookies, setCookie, parseCookie } = require_cookies();
    module.exports.deleteCookie = deleteCookie;
    module.exports.getCookies = getCookies;
    module.exports.getSetCookies = getSetCookies;
    module.exports.setCookie = setCookie;
    module.exports.parseCookie = parseCookie;
    var { parseMIMEType, serializeAMimeType } = require_data_url();
    module.exports.parseMIMEType = parseMIMEType;
    module.exports.serializeAMimeType = serializeAMimeType;
    var { CloseEvent, ErrorEvent, MessageEvent } = require_events();
    var { WebSocket: WebSocket2, ping } = require_websocket2();
    module.exports.WebSocket = WebSocket2;
    module.exports.CloseEvent = CloseEvent;
    module.exports.ErrorEvent = ErrorEvent;
    module.exports.MessageEvent = MessageEvent;
    module.exports.ping = ping;
    module.exports.WebSocketStream = require_websocketstream().WebSocketStream;
    module.exports.WebSocketError = require_websocketerror().WebSocketError;
    module.exports.request = makeDispatcher(api.request);
    module.exports.stream = makeDispatcher(api.stream);
    module.exports.pipeline = makeDispatcher(api.pipeline);
    module.exports.connect = makeDispatcher(api.connect);
    module.exports.upgrade = makeDispatcher(api.upgrade);
    module.exports.MockClient = MockClient;
    module.exports.MockCallHistory = MockCallHistory;
    module.exports.MockCallHistoryLog = MockCallHistoryLog;
    module.exports.MockPool = MockPool;
    module.exports.MockAgent = MockAgent;
    module.exports.SnapshotAgent = SnapshotAgent;
    module.exports.mockErrors = mockErrors;
    var { EventSource } = require_eventsource();
    module.exports.EventSource = EventSource;
    function install() {
      globalThis.fetch = module.exports.fetch;
      globalThis.Headers = module.exports.Headers;
      globalThis.Response = module.exports.Response;
      globalThis.Request = module.exports.Request;
      globalThis.FormData = module.exports.FormData;
      globalThis.WebSocket = module.exports.WebSocket;
      globalThis.CloseEvent = module.exports.CloseEvent;
      globalThis.ErrorEvent = module.exports.ErrorEvent;
      globalThis.MessageEvent = module.exports.MessageEvent;
      globalThis.EventSource = module.exports.EventSource;
    }
    module.exports.install = install;
  }
});

// src/upstream-proxy.ts
async function applyUpstreamProxy(proxyUrl) {
  const url = proxyUrl ?? process.env.BLOCKRUN_UPSTREAM_PROXY;
  if (!url) return void 0;
  let parsed;
  try {
    parsed = new URL(url);
  } catch {
    console.warn(`[ClawRouter] Invalid BLOCKRUN_UPSTREAM_PROXY URL: ${url} \u2014 skipping proxy setup`);
    return void 0;
  }
  const scheme = parsed.protocol;
  try {
    if (scheme === "socks5:" || scheme === "socks4:") {
      const { Socks5ProxyAgent, setGlobalDispatcher } = await Promise.resolve().then(() => __toESM(require_undici(), 1));
      setGlobalDispatcher(new Socks5ProxyAgent(url));
    } else if (scheme === "http:" || scheme === "https:") {
      const { ProxyAgent, setGlobalDispatcher } = await Promise.resolve().then(() => __toESM(require_undici(), 1));
      setGlobalDispatcher(new ProxyAgent(url));
    } else {
      console.warn(
        `[ClawRouter] Unsupported proxy scheme "${scheme}" in BLOCKRUN_UPSTREAM_PROXY \u2014 use http:// or socks5://`
      );
      return void 0;
    }
  } catch (err) {
    console.warn(
      `[ClawRouter] Failed to configure upstream proxy "${url}": ${err instanceof Error ? err.message : err}`
    );
    return void 0;
  }
  return url;
}
var init_upstream_proxy = __esm({
  "src/upstream-proxy.ts"() {
    "use strict";
  }
});

// src/textual-tool-calls.ts
import { randomBytes as randomBytes6 } from "crypto";
function generateId() {
  return `call_${randomBytes6(12).toString("base64url")}`;
}
function coerceValue(raw) {
  const trimmed = raw.trim();
  if (trimmed === "") return raw;
  try {
    return JSON.parse(trimmed);
  } catch {
    return raw;
  }
}
function extractOpenClawCalls(content) {
  const calls = [];
  const matches = [];
  OPENCLAW_TOOL_CALL_RE.lastIndex = 0;
  let match;
  while ((match = OPENCLAW_TOOL_CALL_RE.exec(content)) !== null) {
    const name = match[1]?.trim();
    if (!name) continue;
    const argsBlock = match[2] ?? "";
    const args = {};
    OPENCLAW_ARG_RE.lastIndex = 0;
    let argMatch;
    while ((argMatch = OPENCLAW_ARG_RE.exec(argsBlock)) !== null) {
      const key = argMatch[1]?.trim();
      const valueRaw = argMatch[2] ?? "";
      if (key) {
        args[key] = coerceValue(valueRaw);
      }
    }
    calls.push({
      id: generateId(),
      type: "function",
      function: { name, arguments: JSON.stringify(args) }
    });
    matches.push({ start: match.index, end: match.index + match[0].length });
  }
  return { calls, matches };
}
function extractAnthropicCalls(content) {
  const calls = [];
  const matches = [];
  ANTHROPIC_BLOCK_RE.lastIndex = 0;
  let blockMatch;
  while ((blockMatch = ANTHROPIC_BLOCK_RE.exec(content)) !== null) {
    const inner = blockMatch[1] ?? "";
    let invokeFound = false;
    ANTHROPIC_INVOKE_RE.lastIndex = 0;
    let invokeMatch;
    while ((invokeMatch = ANTHROPIC_INVOKE_RE.exec(inner)) !== null) {
      const name = invokeMatch[1];
      if (!name) continue;
      const invokeInner = invokeMatch[2] ?? "";
      const args = {};
      ANTHROPIC_PARAM_RE.lastIndex = 0;
      let paramMatch;
      while ((paramMatch = ANTHROPIC_PARAM_RE.exec(invokeInner)) !== null) {
        const key = paramMatch[1];
        const valueRaw = paramMatch[2] ?? "";
        if (key) {
          args[key] = coerceValue(valueRaw);
        }
      }
      calls.push({
        id: generateId(),
        type: "function",
        function: { name, arguments: JSON.stringify(args) }
      });
      invokeFound = true;
    }
    if (invokeFound) {
      matches.push({ start: blockMatch.index, end: blockMatch.index + blockMatch[0].length });
    }
  }
  return { calls, matches };
}
function stripRanges(content, ranges) {
  if (ranges.length === 0) return content;
  const sorted = [...ranges].sort((a, b) => a.start - b.start);
  let cleaned = "";
  let cursor = 0;
  for (const r of sorted) {
    if (r.start >= cursor) {
      cleaned += content.slice(cursor, r.start);
      cursor = r.end;
    }
  }
  cleaned += content.slice(cursor);
  return cleaned;
}
function extractTextualToolCalls(content) {
  if (!content) {
    return { toolCalls: [], cleanedContent: "" };
  }
  const openClaw = extractOpenClawCalls(content);
  const anthropic = extractAnthropicCalls(content);
  const toolCalls = [...openClaw.calls, ...anthropic.calls];
  if (toolCalls.length === 0) {
    return { toolCalls: [], cleanedContent: content };
  }
  const cleanedContent = stripRanges(content, [...openClaw.matches, ...anthropic.matches]);
  return { toolCalls, cleanedContent };
}
var OPENCLAW_TOOL_CALL_RE, OPENCLAW_ARG_RE, ANTHROPIC_BLOCK_RE, ANTHROPIC_INVOKE_RE, ANTHROPIC_PARAM_RE;
var init_textual_tool_calls = __esm({
  "src/textual-tool-calls.ts"() {
    "use strict";
    OPENCLAW_TOOL_CALL_RE = /<tool_call>([^<]+?)((?:<arg_key>[\s\S]*?<\/arg_key>\s*<arg_value>[\s\S]*?<\/arg_value>\s*)+)<\/tool_call>/g;
    OPENCLAW_ARG_RE = /<arg_key>([\s\S]*?)<\/arg_key>\s*<arg_value>([\s\S]*?)<\/arg_value>/g;
    ANTHROPIC_BLOCK_RE = /<function_calls\b[^>]*>([\s\S]*?)<\/function_calls\s*>/g;
    ANTHROPIC_INVOKE_RE = /<invoke\s+name=["']([^"']+)["'][^>]*>([\s\S]*?)<\/invoke\s*>/g;
    ANTHROPIC_PARAM_RE = /<parameter\s+name=["']([^"']+)["'][^>]*>([\s\S]*?)<\/parameter\s*>/g;
  }
});

// src/response-store.ts
import { appendFile as appendFile2, mkdir as mkdir3, readFile, readdir as readdir2 } from "fs/promises";
import { homedir as homedir5 } from "os";
import { join as join8 } from "path";
import { randomBytes as randomBytes7 } from "crypto";
function isEnabled() {
  const v = process.env.BLOCKRUN_RESPONSE_STORE;
  return !v || v.toLowerCase() !== "off";
}
async function ensureDir2() {
  if (dirReady2) return;
  await mkdir3(STORE_DIR, { recursive: true });
  dirReady2 = true;
}
function dailyFile(date = /* @__PURE__ */ new Date()) {
  const iso = date.toISOString().slice(0, 10);
  return join8(STORE_DIR, `responses-${iso}.jsonl`);
}
function genId() {
  return `resp_${Date.now()}_${randomBytes7(3).toString("hex")}`;
}
function summarizeRequest(text, max = 80) {
  const oneLine = text.replace(/\s+/g, " ").trim();
  if (oneLine.length <= max) return oneLine;
  return oneLine.slice(0, max - 1) + "\u2026";
}
async function appendResponse(entry) {
  if (!isEnabled()) return null;
  if (!entry.responseText || entry.responseText.length === 0) return null;
  const id = genId();
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
  const full = { id, timestamp, ...entry };
  try {
    await ensureDir2();
    await appendFile2(dailyFile(), JSON.stringify(full) + "\n");
    return id;
  } catch {
    return null;
  }
}
async function readDailyFile(file) {
  try {
    const text = await readFile(file, "utf8");
    return text.split("\n").filter((l2) => l2.trim().length > 0).map((line) => {
      try {
        return JSON.parse(line);
      } catch {
        return null;
      }
    }).filter((e7) => e7 !== null);
  } catch {
    return [];
  }
}
async function listRecent(limit = 20, daysBack = 7) {
  if (!isEnabled()) return [];
  try {
    await ensureDir2();
    const files = await readdir2(STORE_DIR);
    const today = /* @__PURE__ */ new Date();
    const candidateFiles = [];
    for (let i = 0; i < daysBack; i++) {
      const d = new Date(today);
      d.setUTCDate(d.getUTCDate() - i);
      const iso = d.toISOString().slice(0, 10);
      const name = `responses-${iso}.jsonl`;
      if (files.includes(name)) candidateFiles.push(join8(STORE_DIR, name));
    }
    const all = [];
    for (const f of candidateFiles) {
      all.push(...await readDailyFile(f));
    }
    all.sort((a, b) => a.timestamp < b.timestamp ? 1 : -1);
    return all.slice(0, limit);
  } catch {
    return [];
  }
}
async function getLast(sessionId) {
  const recent = await listRecent(50);
  if (recent.length === 0) return null;
  if (sessionId) {
    const match = recent.find((e7) => e7.sessionId === sessionId);
    if (match) return match;
  }
  return recent[0];
}
async function getById(id) {
  const recent = await listRecent(500);
  return recent.find((e7) => e7.id === id) ?? null;
}
var STORE_DIR, dirReady2;
var init_response_store = __esm({
  "src/response-store.ts"() {
    "use strict";
    STORE_DIR = join8(homedir5(), ".openclaw", "blockrun", "responses");
    dirReady2 = false;
  }
});

// src/share-formatters.ts
function isSharePreset(s3) {
  return SHARE_PRESETS.includes(s3);
}
function splitByFences(md) {
  const segments = [];
  const fenceRegex = /(^|\n)(```[a-zA-Z0-9_-]*\n[\s\S]*?\n```)(?=\n|$)/g;
  let lastIndex = 0;
  let match;
  while ((match = fenceRegex.exec(md)) !== null) {
    const fenceStart = match.index + match[1].length;
    if (fenceStart > lastIndex) {
      segments.push({ isFence: false, content: md.slice(lastIndex, fenceStart) });
    }
    const block = match[2];
    const langMatch = block.match(/^```([a-zA-Z0-9_-]*)\n/);
    segments.push({
      isFence: true,
      content: block,
      fenceLang: langMatch ? langMatch[1] : void 0
    });
    lastIndex = fenceStart + block.length;
  }
  if (lastIndex < md.length) {
    segments.push({ isFence: false, content: md.slice(lastIndex) });
  }
  return segments;
}
function fenceInner(block) {
  return block.replace(/^```[a-zA-Z0-9_-]*\n/, "").replace(/\n```$/, "");
}
function splitRow(line) {
  let s3 = line.trim();
  if (s3.startsWith("|")) s3 = s3.slice(1);
  if (s3.endsWith("|")) s3 = s3.slice(0, -1);
  const cells = [];
  let buf = "";
  for (let i = 0; i < s3.length; i++) {
    const ch = s3[i];
    if (ch === "\\" && s3[i + 1] === "|") {
      buf += "|";
      i++;
    } else if (ch === "|") {
      cells.push(buf.trim());
      buf = "";
    } else {
      buf += ch;
    }
  }
  cells.push(buf.trim());
  return cells;
}
function parseTable(block) {
  const lines = block.split("\n").filter((l2) => l2.trim().length > 0);
  if (lines.length < 2) return null;
  const sepCells = splitRow(lines[1]);
  if (sepCells.length === 0 || !sepCells.every((c) => /^:?-+:?$/.test(c))) return null;
  const headers = splitRow(lines[0]);
  const rows = lines.slice(2).map(splitRow);
  return { headers, rows };
}
function visibleWidth(s3) {
  let w = 0;
  for (const ch of s3) {
    const code = ch.codePointAt(0) ?? 0;
    if (code >= 4352 && code <= 4447 || code >= 11904 && code <= 12350 || code >= 12353 && code <= 13311 || code >= 13312 && code <= 19903 || code >= 19968 && code <= 40959 || code >= 40960 && code <= 42191 || code >= 44032 && code <= 55203 || code >= 63744 && code <= 64255 || code >= 65072 && code <= 65103 || code >= 65280 && code <= 65376 || code >= 65504 && code <= 65510 || code >= 131072 && code <= 196605) {
      w += 2;
    } else {
      w += 1;
    }
  }
  return w;
}
function padRight3(s3, width) {
  const pad4 = width - visibleWidth(s3);
  return pad4 > 0 ? s3 + " ".repeat(pad4) : s3;
}
function renderTableMonospace(table) {
  const cols = Math.max(table.headers.length, ...table.rows.map((r) => r.length));
  const grid = [
    [...table.headers, ...Array(cols - table.headers.length).fill("")],
    ...table.rows.map((r) => [...r, ...Array(cols - r.length).fill("")])
  ];
  const widths = [];
  for (let c = 0; c < cols; c++) {
    widths.push(Math.max(...grid.map((row) => visibleWidth(row[c] ?? ""))));
  }
  const renderRow = (row) => row.map((cell, i) => padRight3(cell ?? "", widths[i])).join("  ");
  const sep = widths.map((w) => "-".repeat(w)).join("  ");
  return [renderRow(grid[0]), sep, ...grid.slice(1).map(renderRow)].join("\n");
}
function renderTableKeyValue(table) {
  if (table.headers.length === 2) {
    return table.rows.map((r) => `${r[0] ?? ""}: ${r[1] ?? ""}`).join("\n");
  }
  const blocks = table.rows.map(
    (row) => table.headers.map((h, i) => `${h}: ${row[i] ?? ""}`).join("\n")
  );
  return blocks.join("\n\n");
}
function applyFeishu(text) {
  let s3 = text;
  s3 = s3.replace(/^(#{1,6}) +(.+)$/gm, (_, _h, body) => `**${body.trim()}**`);
  s3 = s3.replace(/^[ \t]*-{3,}[ \t]*$/gm, "");
  return s3;
}
function applySlackText(text) {
  let s3 = text;
  s3 = s3.replace(/&/g, "&amp;");
  const linkPlaceholders = [];
  s3 = s3.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, txt, url) => {
    const i = linkPlaceholders.length;
    linkPlaceholders.push(`<${url}|${txt}>`);
    return `${PH_LINK}${i}${PH_END}`;
  });
  s3 = s3.replace(/</g, "&lt;").replace(/>/g, "&gt;");
  s3 = s3.replace(/^(#{1,6}) +(.+)$/gm, (_, _h, body) => `**${body.trim()}**`);
  const boldPlaceholders = [];
  s3 = s3.replace(/\*\*([^*\n]+)\*\*/g, (_, inner) => {
    const i = boldPlaceholders.length;
    boldPlaceholders.push(inner);
    return `${PH_BOLD}${i}${PH_END}`;
  });
  s3 = s3.replace(/(?<![\w*])\*([^*\n]+)\*(?![\w*])/g, "_$1_");
  s3 = s3.replace(/~~([^~\n]+)~~/g, "~$1~");
  const boldRestoreRe = new RegExp(
    PH_BOLD.replace(/_/g, "\\_") + "(\\d+)" + PH_END.replace(/_/g, "\\_"),
    "g"
  );
  s3 = s3.replace(boldRestoreRe, (_, i) => `*${boldPlaceholders[parseInt(i, 10)]}*`);
  const linkRestoreRe = new RegExp(
    PH_LINK.replace(/_/g, "\\_") + "(\\d+)" + PH_END.replace(/_/g, "\\_"),
    "g"
  );
  s3 = s3.replace(linkRestoreRe, (_, i) => linkPlaceholders[parseInt(i, 10)]);
  s3 = s3.replace(/^([ \t]*)-([ \t]+)/gm, "$1\u2022$2");
  return s3;
}
function applyDiscordText(text) {
  return text;
}
function escapeTelegramText(s3) {
  let out = "";
  for (const ch of s3) {
    if (TELEGRAM_ESCAPE_CHARS.includes(ch)) {
      out += "\\" + ch;
    } else {
      out += ch;
    }
  }
  return out;
}
function applyTelegramText(text) {
  const tokens = [];
  let i = 0;
  const len = text.length;
  const peek = (s3) => text.startsWith(s3, i);
  while (i < len) {
    if (peek("**")) {
      const end = text.indexOf("**", i + 2);
      if (end !== -1) {
        tokens.push({ kind: "bold", raw: text.slice(i, end + 2), inner: text.slice(i + 2, end) });
        i = end + 2;
        continue;
      }
    }
    if (peek("~~")) {
      const end = text.indexOf("~~", i + 2);
      if (end !== -1) {
        tokens.push({ kind: "strike", raw: text.slice(i, end + 2), inner: text.slice(i + 2, end) });
        i = end + 2;
        continue;
      }
    }
    if (peek("`")) {
      const end = text.indexOf("`", i + 1);
      if (end !== -1) {
        tokens.push({ kind: "code", raw: text.slice(i, end + 1), inner: text.slice(i + 1, end) });
        i = end + 1;
        continue;
      }
    }
    if (peek("[")) {
      const close = text.indexOf("](", i + 1);
      if (close !== -1) {
        const end = text.indexOf(")", close + 2);
        if (end !== -1) {
          tokens.push({
            kind: "link",
            raw: text.slice(i, end + 1),
            inner: text.slice(i + 1, close),
            url: text.slice(close + 2, end)
          });
          i = end + 1;
          continue;
        }
      }
    }
    if (text[i] === "*" && text[i + 1] !== "*") {
      const end = text.indexOf("*", i + 1);
      if (end !== -1 && !text.slice(i + 1, end).includes("\n")) {
        tokens.push({ kind: "italic", raw: text.slice(i, end + 1), inner: text.slice(i + 1, end) });
        i = end + 1;
        continue;
      }
    }
    let j = i;
    while (j < len && !text.startsWith("**", j) && !text.startsWith("~~", j) && text[j] !== "`" && text[j] !== "[" && !(text[j] === "*" && text[j + 1] !== "*")) {
      j++;
    }
    tokens.push({ kind: "text", raw: text.slice(i, j) });
    i = j;
  }
  let out = "";
  for (const tok of tokens) {
    switch (tok.kind) {
      case "text":
        out += escapeTelegramText(tok.raw);
        break;
      case "bold":
        out += "*" + escapeTelegramText(tok.inner ?? "") + "*";
        break;
      case "italic":
        out += "_" + escapeTelegramText(tok.inner ?? "") + "_";
        break;
      case "strike":
        out += "~" + escapeTelegramText(tok.inner ?? "") + "~";
        break;
      case "code":
        out += "`" + (tok.inner ?? "").replace(/\\/g, "\\\\").replace(/`/g, "\\`") + "`";
        break;
      case "link":
        out += "[" + escapeTelegramText(tok.inner ?? "") + "](" + (tok.url ?? "").replace(/\\/g, "\\\\").replace(/\)/g, "\\)") + ")";
        break;
    }
  }
  return out;
}
function preProcessTelegram(text) {
  return text.replace(/^(#{1,6}) +(.+)$/gm, (_, _h, body) => `**${body.trim()}**`);
}
function applyWhatsappText(text) {
  let s3 = text;
  s3 = s3.replace(/^(#{1,6}) +(.+)$/gm, (_, _h, body) => `**${body.trim()}**`);
  const boldPlaceholders = [];
  s3 = s3.replace(/\*\*([^*\n]+)\*\*/g, (_, inner) => {
    const i = boldPlaceholders.length;
    boldPlaceholders.push(inner);
    return `${PH_BOLD}${i}${PH_END}`;
  });
  s3 = s3.replace(/(?<![\w*])\*([^*\n]+)\*(?![\w*])/g, "_$1_");
  s3 = s3.replace(/~~([^~\n]+)~~/g, "~$1~");
  const boldRestoreRe = new RegExp(
    PH_BOLD.replace(/_/g, "\\_") + "(\\d+)" + PH_END.replace(/_/g, "\\_"),
    "g"
  );
  s3 = s3.replace(boldRestoreRe, (_, i) => `*${boldPlaceholders[parseInt(i, 10)]}*`);
  s3 = s3.replace(/\[([^\]]+)\]\(([^)]+)\)/g, "$1\n$2");
  return s3;
}
function applyPlainText(text) {
  let s3 = text;
  s3 = s3.replace(/^[ \t]*-{3,}[ \t]*$/gm, "");
  s3 = s3.replace(
    /^# +(.+)$/gm,
    (_, body) => `${body.trim()}
${"=".repeat(visibleWidth(body.trim()))}`
  );
  s3 = s3.replace(
    /^## +(.+)$/gm,
    (_, body) => `${body.trim()}
${"-".repeat(visibleWidth(body.trim()))}`
  );
  s3 = s3.replace(/^#{3,6} +(.+)$/gm, (_, body) => body.trim());
  s3 = s3.replace(/\*\*([^*\n]+)\*\*/g, "$1");
  s3 = s3.replace(/(?<![*\w])\*([^*\n]+)\*(?!\*)/g, "$1");
  s3 = s3.replace(/(?<![_\w])_([^_\n]+)_(?!_)/g, "$1");
  s3 = s3.replace(/~~([^~\n]+)~~/g, "$1");
  s3 = s3.replace(/\[([^\]]+)\]\(([^)]+)\)/g, "$1 ($2)");
  s3 = s3.replace(/`([^`\n]+)`/g, "$1");
  return s3;
}
function transformTablesInProse(text, preset) {
  if (preset === "feishu") return text;
  return text.replace(TABLE_BLOCK_REGEX, (whole, lead, block) => {
    const table = parseTable(block);
    if (!table) return whole;
    if (preset === "plain") {
      return lead + renderTableKeyValue(table);
    }
    const monospace = renderTableMonospace(table);
    return lead + "```\n" + monospace + "\n```\n";
  });
}
function transformFenceForPreset(seg, preset) {
  if (preset === "plain") {
    return fenceInner(seg.content);
  }
  if (preset === "telegram") {
    const inner = fenceInner(seg.content).replace(/\\/g, "\\\\").replace(/`/g, "\\`");
    const lang = seg.fenceLang ? seg.fenceLang : "";
    return "```" + lang + "\n" + inner + "\n```";
  }
  return seg.content;
}
function applyTextRulesPerPreset(text, preset) {
  switch (preset) {
    case "feishu":
      return applyFeishu(text);
    case "slack":
      return applySlackText(text);
    case "discord":
      return applyDiscordText(text);
    case "telegram":
      return applyTelegramText(preProcessTelegram(text));
    case "whatsapp":
      return applyWhatsappText(text);
    case "plain":
      return applyPlainText(text);
  }
}
function transform(md, preset) {
  const originalSegments = splitByFences(md);
  const afterTables = originalSegments.map((seg) => seg.isFence ? seg.content : transformTablesInProse(seg.content, preset)).join("");
  const finalSegments = splitByFences(afterTables);
  return finalSegments.map(
    (seg) => seg.isFence ? transformFenceForPreset(seg, preset) : applyTextRulesPerPreset(seg.content, preset)
  ).join("");
}
var SHARE_PRESETS, PH_BOLD, PH_LINK, PH_END, TABLE_BLOCK_REGEX, TELEGRAM_ESCAPE_CHARS;
var init_share_formatters = __esm({
  "src/share-formatters.ts"() {
    "use strict";
    SHARE_PRESETS = [
      "feishu",
      "slack",
      "discord",
      "telegram",
      "whatsapp",
      "plain"
    ];
    PH_BOLD = "__CR_PH_BOLD_";
    PH_LINK = "__CR_PH_LINK_";
    PH_END = "__";
    TABLE_BLOCK_REGEX = /(^|\n)((?:[ \t]*\|.*\|[ \t]*\n)(?:[ \t]*\|[\s:|-]+\|[ \t]*\n)(?:[ \t]*\|.*\|[ \t]*\n?)*)/g;
    TELEGRAM_ESCAPE_CHARS = "_*[]()~`>#+-=|{}.!";
  }
});

// src/solana-balance.ts
var solana_balance_exports = {};
__export(solana_balance_exports, {
  SolanaBalanceMonitor: () => SolanaBalanceMonitor
});
var SOLANA_USDC_MINT, SOLANA_DEFAULT_RPC, BALANCE_TIMEOUT_MS, CACHE_TTL_MS2, SolanaBalanceMonitor;
var init_solana_balance = __esm({
  "src/solana-balance.ts"() {
    "use strict";
    init_index_node37();
    SOLANA_USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
    SOLANA_DEFAULT_RPC = "https://api.mainnet-beta.solana.com";
    BALANCE_TIMEOUT_MS = 1e4;
    CACHE_TTL_MS2 = 3e4;
    SolanaBalanceMonitor = class {
      rpc;
      walletAddress;
      cachedBalance = null;
      cachedAt = 0;
      constructor(walletAddress, rpcUrl) {
        this.walletAddress = walletAddress;
        const url = rpcUrl || process["env"].CLAWROUTER_SOLANA_RPC_URL || SOLANA_DEFAULT_RPC;
        this.rpc = createSolanaRpc(url);
      }
      async checkBalance() {
        const now = Date.now();
        if (this.cachedBalance !== null && this.cachedBalance > 0n && now - this.cachedAt < CACHE_TTL_MS2) {
          return this.buildInfo(this.cachedBalance);
        }
        const balance = await this.fetchBalance();
        if (balance > 0n) {
          this.cachedBalance = balance;
          this.cachedAt = now;
        }
        return this.buildInfo(balance);
      }
      deductEstimated(amountMicros) {
        if (this.cachedBalance !== null && this.cachedBalance >= amountMicros) {
          this.cachedBalance -= amountMicros;
        }
      }
      invalidate() {
        this.cachedBalance = null;
        this.cachedAt = 0;
      }
      async refresh() {
        this.invalidate();
        return this.checkBalance();
      }
      /**
       * Check if balance is sufficient for an estimated cost.
       */
      async checkSufficient(estimatedCostMicros) {
        const info = await this.checkBalance();
        if (info.balance >= estimatedCostMicros) {
          return { sufficient: true, info };
        }
        const shortfall = estimatedCostMicros - info.balance;
        return {
          sufficient: false,
          info,
          shortfall: this.formatUSDC(shortfall)
        };
      }
      /**
       * Format USDC amount (in micros) as "$X.XX".
       */
      formatUSDC(amountMicros) {
        const dollars = Number(amountMicros) / 1e6;
        return `$${dollars.toFixed(2)}`;
      }
      getWalletAddress() {
        return this.walletAddress;
      }
      /**
       * Check native SOL balance (in lamports). Useful for detecting users who
       * funded with SOL instead of USDC.
       */
      async checkSolBalance() {
        const controller = new AbortController();
        const timer = setTimeout(() => controller.abort(), BALANCE_TIMEOUT_MS);
        try {
          const owner = address(this.walletAddress);
          const response = await this.rpc.getBalance(owner).send({ abortSignal: controller.signal });
          return BigInt(response.value);
        } catch {
          return 0n;
        } finally {
          clearTimeout(timer);
        }
      }
      async fetchBalance() {
        const owner = address(this.walletAddress);
        const mint = address(SOLANA_USDC_MINT);
        const MAX_ATTEMPTS = 3;
        let lastError;
        for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
          try {
            const result = await this.fetchBalanceOnce(owner, mint);
            if (result > 0n) return result;
            if (attempt < MAX_ATTEMPTS - 1) {
              await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
            }
          } catch (err) {
            lastError = err;
            if (attempt < MAX_ATTEMPTS - 1) {
              await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
            }
          }
        }
        if (lastError !== void 0) throw lastError;
        return 0n;
      }
      async fetchBalanceOnce(owner, mint) {
        const controller = new AbortController();
        const timer = setTimeout(() => controller.abort(), BALANCE_TIMEOUT_MS);
        try {
          const response = await this.rpc.getTokenAccountsByOwner(owner, { mint }, { encoding: "jsonParsed" }).send({ abortSignal: controller.signal });
          if (response.value.length === 0) return 0n;
          let total = 0n;
          for (const account of response.value) {
            const parsed = account.account.data;
            total += BigInt(parsed.parsed.info.tokenAmount.amount);
          }
          return total;
        } catch (err) {
          throw new Error(
            `Failed to fetch Solana USDC balance: ${err instanceof Error ? err.message : String(err)}`,
            { cause: err }
          );
        } finally {
          clearTimeout(timer);
        }
      }
      buildInfo(balance) {
        const dollars = Number(balance) / 1e6;
        return {
          balance,
          balanceUSD: `$${dollars.toFixed(2)}`,
          isLow: balance < 1000000n,
          isEmpty: balance < 100n,
          walletAddress: this.walletAddress
        };
      }
    };
  }
});

// node_modules/@solana-program/token/dist/src/index.mjs
var TOKEN_PROGRAM_ADDRESS, ASSOCIATED_TOKEN_ERROR__INVALID_OWNER, associatedTokenErrorMessages, TOKEN_ERROR__NOT_RENT_EXEMPT, TOKEN_ERROR__INSUFFICIENT_FUNDS, TOKEN_ERROR__INVALID_MINT, TOKEN_ERROR__MINT_MISMATCH, TOKEN_ERROR__OWNER_MISMATCH, TOKEN_ERROR__FIXED_SUPPLY, TOKEN_ERROR__ALREADY_IN_USE, TOKEN_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS, TOKEN_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS, TOKEN_ERROR__UNINITIALIZED_STATE, TOKEN_ERROR__NATIVE_NOT_SUPPORTED, TOKEN_ERROR__NON_NATIVE_HAS_BALANCE, TOKEN_ERROR__INVALID_INSTRUCTION, TOKEN_ERROR__INVALID_STATE, TOKEN_ERROR__OVERFLOW, TOKEN_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED, TOKEN_ERROR__MINT_CANNOT_FREEZE, TOKEN_ERROR__ACCOUNT_FROZEN, TOKEN_ERROR__MINT_DECIMALS_MISMATCH, TOKEN_ERROR__NON_NATIVE_NOT_SUPPORTED, tokenErrorMessages;
var init_src = __esm({
  "node_modules/@solana-program/token/dist/src/index.mjs"() {
    "use strict";
    TOKEN_PROGRAM_ADDRESS = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
    ASSOCIATED_TOKEN_ERROR__INVALID_OWNER = 0;
    if (process.env.NODE_ENV !== "production") {
      associatedTokenErrorMessages = {
        [ASSOCIATED_TOKEN_ERROR__INVALID_OWNER]: `Associated token account owner does not match address derivation`
      };
    }
    TOKEN_ERROR__NOT_RENT_EXEMPT = 0;
    TOKEN_ERROR__INSUFFICIENT_FUNDS = 1;
    TOKEN_ERROR__INVALID_MINT = 2;
    TOKEN_ERROR__MINT_MISMATCH = 3;
    TOKEN_ERROR__OWNER_MISMATCH = 4;
    TOKEN_ERROR__FIXED_SUPPLY = 5;
    TOKEN_ERROR__ALREADY_IN_USE = 6;
    TOKEN_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS = 7;
    TOKEN_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS = 8;
    TOKEN_ERROR__UNINITIALIZED_STATE = 9;
    TOKEN_ERROR__NATIVE_NOT_SUPPORTED = 10;
    TOKEN_ERROR__NON_NATIVE_HAS_BALANCE = 11;
    TOKEN_ERROR__INVALID_INSTRUCTION = 12;
    TOKEN_ERROR__INVALID_STATE = 13;
    TOKEN_ERROR__OVERFLOW = 14;
    TOKEN_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED = 15;
    TOKEN_ERROR__MINT_CANNOT_FREEZE = 16;
    TOKEN_ERROR__ACCOUNT_FROZEN = 17;
    TOKEN_ERROR__MINT_DECIMALS_MISMATCH = 18;
    TOKEN_ERROR__NON_NATIVE_NOT_SUPPORTED = 19;
    if (process.env.NODE_ENV !== "production") {
      tokenErrorMessages = {
        [TOKEN_ERROR__ACCOUNT_FROZEN]: `Account is frozen`,
        [TOKEN_ERROR__ALREADY_IN_USE]: `Already in use`,
        [TOKEN_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED]: `Account does not support specified authority type`,
        [TOKEN_ERROR__FIXED_SUPPLY]: `Fixed supply`,
        [TOKEN_ERROR__INSUFFICIENT_FUNDS]: `Insufficient funds`,
        [TOKEN_ERROR__INVALID_INSTRUCTION]: `Invalid instruction`,
        [TOKEN_ERROR__INVALID_MINT]: `Invalid Mint`,
        [TOKEN_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS]: `Invalid number of provided signers`,
        [TOKEN_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS]: `Invalid number of required signers`,
        [TOKEN_ERROR__INVALID_STATE]: `State is invalid for requested operation`,
        [TOKEN_ERROR__MINT_CANNOT_FREEZE]: `This token mint cannot freeze accounts`,
        [TOKEN_ERROR__MINT_DECIMALS_MISMATCH]: `The provided decimals value different from the Mint decimals`,
        [TOKEN_ERROR__MINT_MISMATCH]: `Account not associated with this Mint`,
        [TOKEN_ERROR__NATIVE_NOT_SUPPORTED]: `Instruction does not support native tokens`,
        [TOKEN_ERROR__NON_NATIVE_HAS_BALANCE]: `Non-native account can only be closed if its balance is zero`,
        [TOKEN_ERROR__NON_NATIVE_NOT_SUPPORTED]: `Instruction does not support non-native tokens`,
        [TOKEN_ERROR__NOT_RENT_EXEMPT]: `Lamport balance below rent-exempt threshold`,
        [TOKEN_ERROR__OVERFLOW]: `Operation overflowed`,
        [TOKEN_ERROR__OWNER_MISMATCH]: `Owner does not match`,
        [TOKEN_ERROR__UNINITIALIZED_STATE]: `State is unititialized`
      };
    }
    if (process.env.NODE_ENV !== "production") ;
  }
});

// node_modules/@solana-program/token-2022/dist/src/index.mjs
function getAccountStateDecoder() {
  return getEnumDecoder(AccountState);
}
function getDecryptableBalanceDecoder() {
  return fixDecoderSize(getBytesDecoder(), 36);
}
function getEncryptedBalanceDecoder() {
  return fixDecoderSize(getBytesDecoder(), 64);
}
function getExtensionDecoder() {
  return getDiscriminatedUnionDecoder(
    [
      ["Uninitialized", getUnitDecoder()],
      [
        "TransferFeeConfig",
        addDecoderSizePrefix(
          getStructDecoder([
            ["transferFeeConfigAuthority", getAddressDecoder()],
            ["withdrawWithheldAuthority", getAddressDecoder()],
            ["withheldAmount", getU64Decoder()],
            ["olderTransferFee", getTransferFeeDecoder()],
            ["newerTransferFee", getTransferFeeDecoder()]
          ]),
          getU16Decoder()
        )
      ],
      [
        "TransferFeeAmount",
        addDecoderSizePrefix(
          getStructDecoder([["withheldAmount", getU64Decoder()]]),
          getU16Decoder()
        )
      ],
      [
        "MintCloseAuthority",
        addDecoderSizePrefix(
          getStructDecoder([["closeAuthority", getAddressDecoder()]]),
          getU16Decoder()
        )
      ],
      [
        "ConfidentialTransferMint",
        addDecoderSizePrefix(
          getStructDecoder([
            [
              "authority",
              getOptionDecoder(getAddressDecoder(), {
                prefix: null,
                noneValue: "zeroes"
              })
            ],
            ["autoApproveNewAccounts", getBooleanDecoder()],
            [
              "auditorElgamalPubkey",
              getOptionDecoder(getAddressDecoder(), {
                prefix: null,
                noneValue: "zeroes"
              })
            ]
          ]),
          getU16Decoder()
        )
      ],
      [
        "ConfidentialTransferAccount",
        addDecoderSizePrefix(
          getStructDecoder([
            ["approved", getBooleanDecoder()],
            ["elgamalPubkey", getAddressDecoder()],
            ["pendingBalanceLow", getEncryptedBalanceDecoder()],
            ["pendingBalanceHigh", getEncryptedBalanceDecoder()],
            ["availableBalance", getEncryptedBalanceDecoder()],
            ["decryptableAvailableBalance", getDecryptableBalanceDecoder()],
            ["allowConfidentialCredits", getBooleanDecoder()],
            ["allowNonConfidentialCredits", getBooleanDecoder()],
            ["pendingBalanceCreditCounter", getU64Decoder()],
            ["maximumPendingBalanceCreditCounter", getU64Decoder()],
            ["expectedPendingBalanceCreditCounter", getU64Decoder()],
            ["actualPendingBalanceCreditCounter", getU64Decoder()]
          ]),
          getU16Decoder()
        )
      ],
      [
        "DefaultAccountState",
        addDecoderSizePrefix(
          getStructDecoder([["state", getAccountStateDecoder()]]),
          getU16Decoder()
        )
      ],
      [
        "ImmutableOwner",
        addDecoderSizePrefix(getStructDecoder([]), getU16Decoder())
      ],
      [
        "MemoTransfer",
        addDecoderSizePrefix(
          getStructDecoder([
            ["requireIncomingTransferMemos", getBooleanDecoder()]
          ]),
          getU16Decoder()
        )
      ],
      [
        "NonTransferable",
        addDecoderSizePrefix(getStructDecoder([]), getU16Decoder())
      ],
      [
        "InterestBearingConfig",
        addDecoderSizePrefix(
          getStructDecoder([
            ["rateAuthority", getAddressDecoder()],
            ["initializationTimestamp", getU64Decoder()],
            ["preUpdateAverageRate", getI16Decoder()],
            ["lastUpdateTimestamp", getU64Decoder()],
            ["currentRate", getI16Decoder()]
          ]),
          getU16Decoder()
        )
      ],
      [
        "CpiGuard",
        addDecoderSizePrefix(
          getStructDecoder([["lockCpi", getBooleanDecoder()]]),
          getU16Decoder()
        )
      ],
      [
        "PermanentDelegate",
        addDecoderSizePrefix(
          getStructDecoder([["delegate", getAddressDecoder()]]),
          getU16Decoder()
        )
      ],
      [
        "NonTransferableAccount",
        addDecoderSizePrefix(getStructDecoder([]), getU16Decoder())
      ],
      [
        "TransferHook",
        addDecoderSizePrefix(
          getStructDecoder([
            ["authority", getAddressDecoder()],
            ["programId", getAddressDecoder()]
          ]),
          getU16Decoder()
        )
      ],
      [
        "TransferHookAccount",
        addDecoderSizePrefix(
          getStructDecoder([["transferring", getBooleanDecoder()]]),
          getU16Decoder()
        )
      ],
      [
        "ConfidentialTransferFee",
        addDecoderSizePrefix(
          getStructDecoder([
            [
              "authority",
              getOptionDecoder(getAddressDecoder(), {
                prefix: null,
                noneValue: "zeroes"
              })
            ],
            ["elgamalPubkey", getAddressDecoder()],
            ["harvestToMintEnabled", getBooleanDecoder()],
            ["withheldAmount", getEncryptedBalanceDecoder()]
          ]),
          getU16Decoder()
        )
      ],
      [
        "ConfidentialTransferFeeAmount",
        addDecoderSizePrefix(
          getStructDecoder([["withheldAmount", getEncryptedBalanceDecoder()]]),
          getU16Decoder()
        )
      ],
      [
        "MetadataPointer",
        addDecoderSizePrefix(
          getStructDecoder([
            [
              "authority",
              getOptionDecoder(getAddressDecoder(), {
                prefix: null,
                noneValue: "zeroes"
              })
            ],
            [
              "metadataAddress",
              getOptionDecoder(getAddressDecoder(), {
                prefix: null,
                noneValue: "zeroes"
              })
            ]
          ]),
          getU16Decoder()
        )
      ],
      [
        "TokenMetadata",
        addDecoderSizePrefix(
          getStructDecoder([
            [
              "updateAuthority",
              getOptionDecoder(getAddressDecoder(), {
                prefix: null,
                noneValue: "zeroes"
              })
            ],
            ["mint", getAddressDecoder()],
            ["name", addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],
            ["symbol", addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],
            ["uri", addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())],
            [
              "additionalMetadata",
              getMapDecoder(
                addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder()),
                addDecoderSizePrefix(getUtf8Decoder(), getU32Decoder())
              )
            ]
          ]),
          getU16Decoder()
        )
      ],
      [
        "GroupPointer",
        addDecoderSizePrefix(
          getStructDecoder([
            [
              "authority",
              getOptionDecoder(getAddressDecoder(), {
                prefix: null,
                noneValue: "zeroes"
              })
            ],
            [
              "groupAddress",
              getOptionDecoder(getAddressDecoder(), {
                prefix: null,
                noneValue: "zeroes"
              })
            ]
          ]),
          getU16Decoder()
        )
      ],
      [
        "TokenGroup",
        addDecoderSizePrefix(
          getStructDecoder([
            [
              "updateAuthority",
              getOptionDecoder(getAddressDecoder(), {
                prefix: null,
                noneValue: "zeroes"
              })
            ],
            ["mint", getAddressDecoder()],
            ["size", getU64Decoder()],
            ["maxSize", getU64Decoder()]
          ]),
          getU16Decoder()
        )
      ],
      [
        "GroupMemberPointer",
        addDecoderSizePrefix(
          getStructDecoder([
            [
              "authority",
              getOptionDecoder(getAddressDecoder(), {
                prefix: null,
                noneValue: "zeroes"
              })
            ],
            [
              "memberAddress",
              getOptionDecoder(getAddressDecoder(), {
                prefix: null,
                noneValue: "zeroes"
              })
            ]
          ]),
          getU16Decoder()
        )
      ],
      [
        "TokenGroupMember",
        addDecoderSizePrefix(
          getStructDecoder([
            ["mint", getAddressDecoder()],
            ["group", getAddressDecoder()],
            ["memberNumber", getU64Decoder()]
          ]),
          getU16Decoder()
        )
      ],
      ["ConfidentialMintBurn", getUnitDecoder()],
      [
        "ScaledUiAmountConfig",
        addDecoderSizePrefix(
          getStructDecoder([
            ["authority", getAddressDecoder()],
            ["multiplier", getF64Decoder()],
            ["newMultiplierEffectiveTimestamp", getU64Decoder()],
            ["newMultiplier", getF64Decoder()]
          ]),
          getU16Decoder()
        )
      ],
      [
        "PausableConfig",
        addDecoderSizePrefix(
          getStructDecoder([
            [
              "authority",
              getOptionDecoder(getAddressDecoder(), {
                prefix: null,
                noneValue: "zeroes"
              })
            ],
            ["paused", getBooleanDecoder()]
          ]),
          getU16Decoder()
        )
      ],
      ["PausableAccount", getUnitDecoder()]
    ],
    { size: getU16Decoder() }
  );
}
function getTransferFeeDecoder() {
  return getStructDecoder([
    ["epoch", getU64Decoder()],
    ["maximumFee", getU64Decoder()],
    ["transferFeeBasisPoints", getU16Decoder()]
  ]);
}
function getMintDecoder() {
  return getStructDecoder([
    [
      "mintAuthority",
      getOptionDecoder(getAddressDecoder(), {
        prefix: getU32Decoder(),
        noneValue: "zeroes"
      })
    ],
    ["supply", getU64Decoder()],
    ["decimals", getU8Decoder()],
    ["isInitialized", getBooleanDecoder()],
    [
      "freezeAuthority",
      getOptionDecoder(getAddressDecoder(), {
        prefix: getU32Decoder(),
        noneValue: "zeroes"
      })
    ],
    [
      "extensions",
      getOptionDecoder(
        getHiddenPrefixDecoder(
          getArrayDecoder(getExtensionDecoder(), { size: "remainder" }),
          [getConstantDecoder(padLeftEncoder(getU8Encoder(), 83).encode(1))]
        ),
        { prefix: null }
      )
    ]
  ]);
}
function decodeMint(encodedAccount) {
  return decodeAccount(
    encodedAccount,
    getMintDecoder()
  );
}
async function fetchMint(rpc, address2, config) {
  const maybeAccount = await fetchMaybeMint(rpc, address2, config);
  assertAccountExists(maybeAccount);
  return maybeAccount;
}
async function fetchMaybeMint(rpc, address2, config) {
  const maybeAccount = await fetchEncodedAccount(rpc, address2, config);
  return decodeMint(maybeAccount);
}
function expectAddress(value) {
  if (!value) {
    throw new Error("Expected a Address.");
  }
  if (typeof value === "object" && "address" in value) {
    return value.address;
  }
  if (Array.isArray(value)) {
    return value[0];
  }
  return value;
}
function getAccountMetaFactory(programAddress, optionalAccountStrategy) {
  return (account) => {
    if (!account.value) {
      return Object.freeze({
        address: programAddress,
        role: AccountRole.READONLY
      });
    }
    const writableRole = account.isWritable ? AccountRole.WRITABLE : AccountRole.READONLY;
    return Object.freeze({
      address: expectAddress(account.value),
      role: isTransactionSigner2(account.value) ? upgradeRoleToSigner(writableRole) : writableRole,
      ...isTransactionSigner2(account.value) ? { signer: account.value } : {}
    });
  };
}
function isTransactionSigner2(value) {
  return !!value && typeof value === "object" && "address" in value && isTransactionSigner(value);
}
async function findAssociatedTokenPda(seeds, config = {}) {
  const {
    programAddress = "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
  } = config;
  return await getProgramDerivedAddress({
    programAddress,
    seeds: [
      getAddressEncoder().encode(seeds.owner),
      getAddressEncoder().encode(seeds.tokenProgram),
      getAddressEncoder().encode(seeds.mint)
    ]
  });
}
function getTransferCheckedInstructionDataEncoder() {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", getU8Encoder()],
      ["amount", getU64Encoder()],
      ["decimals", getU8Encoder()]
    ]),
    (value) => ({ ...value, discriminator: TRANSFER_CHECKED_DISCRIMINATOR })
  );
}
function getTransferCheckedInstruction(input, config) {
  const programAddress = config?.programAddress ?? TOKEN_2022_PROGRAM_ADDRESS;
  const originalAccounts = {
    source: { value: input.source ?? null, isWritable: true },
    mint: { value: input.mint ?? null, isWritable: false },
    destination: { value: input.destination ?? null, isWritable: true },
    authority: { value: input.authority ?? null, isWritable: false }
  };
  const accounts = originalAccounts;
  const args = { ...input };
  const remainingAccounts = (args.multiSigners ?? []).map(
    (signer) => ({
      address: signer.address,
      role: AccountRole.READONLY_SIGNER,
      signer
    })
  );
  const getAccountMeta = getAccountMetaFactory(programAddress);
  return Object.freeze({
    accounts: [
      getAccountMeta(accounts.source),
      getAccountMeta(accounts.mint),
      getAccountMeta(accounts.destination),
      getAccountMeta(accounts.authority),
      ...remainingAccounts
    ],
    data: getTransferCheckedInstructionDataEncoder().encode(
      args
    ),
    programAddress
  });
}
var AccountState, TOKEN_2022_PROGRAM_ADDRESS, ASSOCIATED_TOKEN_ERROR__INVALID_OWNER2, associatedTokenErrorMessages2, TOKEN_2022_ERROR__NOT_RENT_EXEMPT, TOKEN_2022_ERROR__INSUFFICIENT_FUNDS, TOKEN_2022_ERROR__INVALID_MINT, TOKEN_2022_ERROR__MINT_MISMATCH, TOKEN_2022_ERROR__OWNER_MISMATCH, TOKEN_2022_ERROR__FIXED_SUPPLY, TOKEN_2022_ERROR__ALREADY_IN_USE, TOKEN_2022_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS, TOKEN_2022_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS, TOKEN_2022_ERROR__UNINITIALIZED_STATE, TOKEN_2022_ERROR__NATIVE_NOT_SUPPORTED, TOKEN_2022_ERROR__NON_NATIVE_HAS_BALANCE, TOKEN_2022_ERROR__INVALID_INSTRUCTION, TOKEN_2022_ERROR__INVALID_STATE, TOKEN_2022_ERROR__OVERFLOW, TOKEN_2022_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED, TOKEN_2022_ERROR__MINT_CANNOT_FREEZE, TOKEN_2022_ERROR__ACCOUNT_FROZEN, TOKEN_2022_ERROR__MINT_DECIMALS_MISMATCH, TOKEN_2022_ERROR__NON_NATIVE_NOT_SUPPORTED, token2022ErrorMessages, EMIT_TOKEN_METADATA_DISCRIMINATOR, INITIALIZE_TOKEN_GROUP_DISCRIMINATOR, INITIALIZE_TOKEN_GROUP_MEMBER_DISCRIMINATOR, INITIALIZE_TOKEN_METADATA_DISCRIMINATOR, REMOVE_TOKEN_METADATA_KEY_DISCRIMINATOR, TRANSFER_CHECKED_DISCRIMINATOR, UPDATE_TOKEN_GROUP_MAX_SIZE_DISCRIMINATOR, UPDATE_TOKEN_GROUP_UPDATE_AUTHORITY_DISCRIMINATOR, UPDATE_TOKEN_METADATA_FIELD_DISCRIMINATOR, UPDATE_TOKEN_METADATA_UPDATE_AUTHORITY_DISCRIMINATOR, SECONDS_PER_YEAR;
var init_src2 = __esm({
  "node_modules/@solana-program/token-2022/dist/src/index.mjs"() {
    "use strict";
    init_index_node37();
    AccountState = /* @__PURE__ */ ((AccountState2) => {
      AccountState2[AccountState2["Uninitialized"] = 0] = "Uninitialized";
      AccountState2[AccountState2["Initialized"] = 1] = "Initialized";
      AccountState2[AccountState2["Frozen"] = 2] = "Frozen";
      return AccountState2;
    })(AccountState || {});
    TOKEN_2022_PROGRAM_ADDRESS = "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb";
    ASSOCIATED_TOKEN_ERROR__INVALID_OWNER2 = 0;
    if (process.env.NODE_ENV !== "production") {
      associatedTokenErrorMessages2 = {
        [ASSOCIATED_TOKEN_ERROR__INVALID_OWNER2]: `Associated token account owner does not match address derivation`
      };
    }
    TOKEN_2022_ERROR__NOT_RENT_EXEMPT = 0;
    TOKEN_2022_ERROR__INSUFFICIENT_FUNDS = 1;
    TOKEN_2022_ERROR__INVALID_MINT = 2;
    TOKEN_2022_ERROR__MINT_MISMATCH = 3;
    TOKEN_2022_ERROR__OWNER_MISMATCH = 4;
    TOKEN_2022_ERROR__FIXED_SUPPLY = 5;
    TOKEN_2022_ERROR__ALREADY_IN_USE = 6;
    TOKEN_2022_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS = 7;
    TOKEN_2022_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS = 8;
    TOKEN_2022_ERROR__UNINITIALIZED_STATE = 9;
    TOKEN_2022_ERROR__NATIVE_NOT_SUPPORTED = 10;
    TOKEN_2022_ERROR__NON_NATIVE_HAS_BALANCE = 11;
    TOKEN_2022_ERROR__INVALID_INSTRUCTION = 12;
    TOKEN_2022_ERROR__INVALID_STATE = 13;
    TOKEN_2022_ERROR__OVERFLOW = 14;
    TOKEN_2022_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED = 15;
    TOKEN_2022_ERROR__MINT_CANNOT_FREEZE = 16;
    TOKEN_2022_ERROR__ACCOUNT_FROZEN = 17;
    TOKEN_2022_ERROR__MINT_DECIMALS_MISMATCH = 18;
    TOKEN_2022_ERROR__NON_NATIVE_NOT_SUPPORTED = 19;
    if (process.env.NODE_ENV !== "production") {
      token2022ErrorMessages = {
        [TOKEN_2022_ERROR__ACCOUNT_FROZEN]: `Account is frozen`,
        [TOKEN_2022_ERROR__ALREADY_IN_USE]: `Already in use`,
        [TOKEN_2022_ERROR__AUTHORITY_TYPE_NOT_SUPPORTED]: `Account does not support specified authority type`,
        [TOKEN_2022_ERROR__FIXED_SUPPLY]: `Fixed supply`,
        [TOKEN_2022_ERROR__INSUFFICIENT_FUNDS]: `Insufficient funds`,
        [TOKEN_2022_ERROR__INVALID_INSTRUCTION]: `Invalid instruction`,
        [TOKEN_2022_ERROR__INVALID_MINT]: `Invalid Mint`,
        [TOKEN_2022_ERROR__INVALID_NUMBER_OF_PROVIDED_SIGNERS]: `Invalid number of provided signers`,
        [TOKEN_2022_ERROR__INVALID_NUMBER_OF_REQUIRED_SIGNERS]: `Invalid number of required signers`,
        [TOKEN_2022_ERROR__INVALID_STATE]: `State is invalid for requested operation`,
        [TOKEN_2022_ERROR__MINT_CANNOT_FREEZE]: `This token mint cannot freeze accounts`,
        [TOKEN_2022_ERROR__MINT_DECIMALS_MISMATCH]: `The provided decimals value different from the Mint decimals`,
        [TOKEN_2022_ERROR__MINT_MISMATCH]: `Account not associated with this Mint`,
        [TOKEN_2022_ERROR__NATIVE_NOT_SUPPORTED]: `Instruction does not support native tokens`,
        [TOKEN_2022_ERROR__NON_NATIVE_HAS_BALANCE]: `Non-native account can only be closed if its balance is zero`,
        [TOKEN_2022_ERROR__NON_NATIVE_NOT_SUPPORTED]: `Instruction does not support non-native tokens`,
        [TOKEN_2022_ERROR__NOT_RENT_EXEMPT]: `Lamport balance below rent-exempt threshold`,
        [TOKEN_2022_ERROR__OVERFLOW]: `Operation overflowed`,
        [TOKEN_2022_ERROR__OWNER_MISMATCH]: `Owner does not match`,
        [TOKEN_2022_ERROR__UNINITIALIZED_STATE]: `State is unititialized`
      };
    }
    EMIT_TOKEN_METADATA_DISCRIMINATOR = new Uint8Array([
      250,
      166,
      180,
      250,
      13,
      12,
      184,
      70
    ]);
    INITIALIZE_TOKEN_GROUP_DISCRIMINATOR = new Uint8Array([
      121,
      113,
      108,
      39,
      54,
      51,
      0,
      4
    ]);
    INITIALIZE_TOKEN_GROUP_MEMBER_DISCRIMINATOR = new Uint8Array([
      152,
      32,
      222,
      176,
      223,
      237,
      116,
      134
    ]);
    INITIALIZE_TOKEN_METADATA_DISCRIMINATOR = new Uint8Array([
      210,
      225,
      30,
      162,
      88,
      184,
      77,
      141
    ]);
    REMOVE_TOKEN_METADATA_KEY_DISCRIMINATOR = new Uint8Array([
      234,
      18,
      32,
      56,
      89,
      141,
      37,
      181
    ]);
    TRANSFER_CHECKED_DISCRIMINATOR = 12;
    UPDATE_TOKEN_GROUP_MAX_SIZE_DISCRIMINATOR = new Uint8Array([
      108,
      37,
      171,
      143,
      248,
      30,
      18,
      110
    ]);
    UPDATE_TOKEN_GROUP_UPDATE_AUTHORITY_DISCRIMINATOR = new Uint8Array(
      [161, 105, 88, 1, 237, 221, 216, 203]
    );
    UPDATE_TOKEN_METADATA_FIELD_DISCRIMINATOR = new Uint8Array([
      221,
      233,
      49,
      45,
      181,
      202,
      220,
      200
    ]);
    UPDATE_TOKEN_METADATA_UPDATE_AUTHORITY_DISCRIMINATOR = new Uint8Array([215, 228, 166, 228, 84, 100, 86, 123]);
    SECONDS_PER_YEAR = 60 * 60 * 24 * 365.24;
  }
});

// node_modules/@x402/core/dist/esm/utils/index.mjs
var init_utils12 = __esm({
  "node_modules/@x402/core/dist/esm/utils/index.mjs"() {
    "use strict";
    init_chunk_4BKQ2IT7();
    init_chunk_BJTO5JO5();
  }
});

// node_modules/@x402/svm/dist/esm/chunk-6JPFBIJG.mjs
function normalizeNetwork(network) {
  if (network.includes(":")) {
    const supported = [SOLANA_MAINNET_CAIP2, SOLANA_DEVNET_CAIP2, SOLANA_TESTNET_CAIP2];
    if (!supported.includes(network)) {
      throw new Error(`Unsupported SVM network: ${network}`);
    }
    return network;
  }
  const caip2Network = V1_TO_V2_NETWORK_MAP[network];
  if (!caip2Network) {
    throw new Error(`Unsupported SVM network: ${network}`);
  }
  return caip2Network;
}
function createRpcClient(network, customRpcUrl) {
  const caip2Network = normalizeNetwork(network);
  switch (caip2Network) {
    case SOLANA_DEVNET_CAIP2: {
      const url = customRpcUrl || DEVNET_RPC_URL;
      return createSolanaRpc(devnet(url));
    }
    case SOLANA_TESTNET_CAIP2: {
      const url = customRpcUrl || TESTNET_RPC_URL;
      return createSolanaRpc(testnet(url));
    }
    case SOLANA_MAINNET_CAIP2: {
      const url = customRpcUrl || MAINNET_RPC_URL;
      return createSolanaRpc(mainnet(url));
    }
    default:
      throw new Error(`Unsupported network: ${network}`);
  }
}
var MEMO_PROGRAM_ADDRESS, DEVNET_RPC_URL, TESTNET_RPC_URL, MAINNET_RPC_URL, DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS, DEFAULT_COMPUTE_UNIT_LIMIT, MAX_MEMO_BYTES, SOLANA_MAINNET_CAIP2, SOLANA_DEVNET_CAIP2, SOLANA_TESTNET_CAIP2, V1_TO_V2_NETWORK_MAP;
var init_chunk_6JPFBIJG = __esm({
  "node_modules/@x402/svm/dist/esm/chunk-6JPFBIJG.mjs"() {
    "use strict";
    init_index_node37();
    init_utils12();
    MEMO_PROGRAM_ADDRESS = "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr";
    DEVNET_RPC_URL = "https://api.devnet.solana.com";
    TESTNET_RPC_URL = "https://api.testnet.solana.com";
    MAINNET_RPC_URL = "https://api.mainnet-beta.solana.com";
    DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 1;
    DEFAULT_COMPUTE_UNIT_LIMIT = 2e4;
    MAX_MEMO_BYTES = 256;
    SOLANA_MAINNET_CAIP2 = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
    SOLANA_DEVNET_CAIP2 = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
    SOLANA_TESTNET_CAIP2 = "solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";
    V1_TO_V2_NETWORK_MAP = {
      solana: SOLANA_MAINNET_CAIP2,
      "solana-devnet": SOLANA_DEVNET_CAIP2,
      "solana-testnet": SOLANA_TESTNET_CAIP2
    };
  }
});

// node_modules/@solana-program/compute-budget/dist/src/index.mjs
function getSetComputeUnitLimitInstructionDataEncoder() {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", getU8Encoder()],
      ["units", getU32Encoder()]
    ]),
    (value) => ({
      ...value,
      discriminator: SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR
    })
  );
}
function getSetComputeUnitLimitInstruction(input, config) {
  const programAddress = config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;
  const args = { ...input };
  return Object.freeze({
    data: getSetComputeUnitLimitInstructionDataEncoder().encode(
      args
    ),
    programAddress
  });
}
function getSetComputeUnitPriceInstructionDataEncoder() {
  return transformEncoder(
    getStructEncoder([
      ["discriminator", getU8Encoder()],
      ["microLamports", getU64Encoder()]
    ]),
    (value) => ({
      ...value,
      discriminator: SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR
    })
  );
}
function getSetComputeUnitPriceInstruction(input, config) {
  const programAddress = config?.programAddress ?? COMPUTE_BUDGET_PROGRAM_ADDRESS;
  const args = { ...input };
  return Object.freeze({
    data: getSetComputeUnitPriceInstructionDataEncoder().encode(
      args
    ),
    programAddress
  });
}
function setTransactionMessageComputeUnitPrice(microLamports, transactionMessage) {
  return appendTransactionMessageInstruction(
    getSetComputeUnitPriceInstruction({ microLamports }),
    transactionMessage
  );
}
var COMPUTE_BUDGET_PROGRAM_ADDRESS, SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR, SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR;
var init_src3 = __esm({
  "node_modules/@solana-program/compute-budget/dist/src/index.mjs"() {
    "use strict";
    init_index_node37();
    COMPUTE_BUDGET_PROGRAM_ADDRESS = "ComputeBudget111111111111111111111111111111";
    SET_COMPUTE_UNIT_LIMIT_DISCRIMINATOR = 2;
    SET_COMPUTE_UNIT_PRICE_DISCRIMINATOR = 3;
  }
});

// node_modules/@x402/svm/dist/esm/chunk-MPB7KQPX.mjs
var ExactSvmScheme;
var init_chunk_MPB7KQPX = __esm({
  "node_modules/@x402/svm/dist/esm/chunk-MPB7KQPX.mjs"() {
    "use strict";
    init_chunk_6JPFBIJG();
    init_src3();
    init_src();
    init_src2();
    init_index_node37();
    ExactSvmScheme = class {
      /**
       * Creates a new ExactSvmClient instance.
       *
       * @param signer - The SVM signer for client operations
       * @param config - Optional configuration with custom RPC URL
       * @returns ExactSvmClient instance
       */
      constructor(signer, config) {
        this.signer = signer;
        this.config = config;
        this.scheme = "exact";
      }
      /**
       * Creates a payment payload for the Exact scheme.
       *
       * @param x402Version - The x402 protocol version
       * @param paymentRequirements - The payment requirements
       * @returns Promise resolving to a payment payload
       */
      async createPaymentPayload(x402Version2, paymentRequirements) {
        const rpc = createRpcClient(paymentRequirements.network, this.config?.rpcUrl);
        const tokenMint = await fetchMint(rpc, paymentRequirements.asset);
        const tokenProgramAddress = tokenMint.programAddress;
        if (tokenProgramAddress.toString() !== TOKEN_PROGRAM_ADDRESS.toString() && tokenProgramAddress.toString() !== TOKEN_2022_PROGRAM_ADDRESS.toString()) {
          throw new Error("Asset was not created by a known token program");
        }
        const [sourceATA] = await findAssociatedTokenPda({
          mint: paymentRequirements.asset,
          owner: this.signer.address,
          tokenProgram: tokenProgramAddress
        });
        const [destinationATA] = await findAssociatedTokenPda({
          mint: paymentRequirements.asset,
          owner: paymentRequirements.payTo,
          tokenProgram: tokenProgramAddress
        });
        const transferIx = getTransferCheckedInstruction(
          {
            source: sourceATA,
            mint: paymentRequirements.asset,
            destination: destinationATA,
            authority: this.signer,
            amount: BigInt(paymentRequirements.amount),
            decimals: tokenMint.data.decimals
          },
          { programAddress: tokenProgramAddress }
        );
        const feePayer = paymentRequirements.extra?.feePayer;
        if (!feePayer) {
          throw new Error("feePayer is required in paymentRequirements.extra for SVM transactions");
        }
        const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
        const sellerMemo = paymentRequirements.extra?.memo;
        let memoData;
        if (sellerMemo) {
          memoData = new TextEncoder().encode(sellerMemo);
          if (memoData.byteLength > MAX_MEMO_BYTES) {
            throw new Error(`extra.memo exceeds maximum ${MAX_MEMO_BYTES} bytes`);
          }
        } else {
          const nonce = crypto.getRandomValues(new Uint8Array(16));
          memoData = new TextEncoder().encode(
            Array.from(nonce).map((b) => b.toString(16).padStart(2, "0")).join("")
          );
        }
        const memoIx = {
          programAddress: MEMO_PROGRAM_ADDRESS,
          accounts: [],
          data: memoData
        };
        const tx = pipe(
          createTransactionMessage({ version: 0 }),
          (tx2) => setTransactionMessageComputeUnitPrice(DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS, tx2),
          (tx2) => setTransactionMessageFeePayer(feePayer, tx2),
          (tx2) => prependTransactionMessageInstruction(
            getSetComputeUnitLimitInstruction({ units: DEFAULT_COMPUTE_UNIT_LIMIT }),
            tx2
          ),
          (tx2) => appendTransactionMessageInstructions([transferIx, memoIx], tx2),
          (tx2) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx2)
        );
        const signedTransaction = await partiallySignTransactionMessageWithSigners(tx);
        const base64EncodedWireTransaction = getBase64EncodedWireTransaction(signedTransaction);
        const payload = {
          transaction: base64EncodedWireTransaction
        };
        return {
          x402Version: x402Version2,
          payload
        };
      }
    };
  }
});

// node_modules/@x402/svm/dist/esm/chunk-WWACQNRQ.mjs
var NETWORKS2;
var init_chunk_WWACQNRQ = __esm({
  "node_modules/@x402/svm/dist/esm/chunk-WWACQNRQ.mjs"() {
    "use strict";
    NETWORKS2 = ["solana", "solana-devnet", "solana-testnet"];
  }
});

// node_modules/@x402/svm/dist/esm/chunk-TOJMXN7W.mjs
var ExactSvmSchemeV1;
var init_chunk_TOJMXN7W = __esm({
  "node_modules/@x402/svm/dist/esm/chunk-TOJMXN7W.mjs"() {
    "use strict";
    init_chunk_6JPFBIJG();
    init_src3();
    init_src();
    init_src2();
    init_index_node37();
    ExactSvmSchemeV1 = class {
      /**
       * Creates a new ExactSvmClientV1 instance.
       *
       * @param signer - The SVM signer for client operations
       * @param config - Optional configuration with custom RPC URL
       * @returns ExactSvmClientV1 instance
       */
      constructor(signer, config) {
        this.signer = signer;
        this.config = config;
        this.scheme = "exact";
      }
      /**
       * Creates a payment payload for the Exact scheme (V1).
       *
       * @param x402Version - The x402 protocol version
       * @param paymentRequirements - The payment requirements
       * @returns Promise resolving to a payment payload
       */
      async createPaymentPayload(x402Version2, paymentRequirements) {
        const selectedV1 = paymentRequirements;
        const rpc = createRpcClient(selectedV1.network, this.config?.rpcUrl);
        const tokenMint = await fetchMint(rpc, selectedV1.asset);
        const tokenProgramAddress = tokenMint.programAddress;
        if (tokenProgramAddress.toString() !== TOKEN_PROGRAM_ADDRESS.toString() && tokenProgramAddress.toString() !== TOKEN_2022_PROGRAM_ADDRESS.toString()) {
          throw new Error("Asset was not created by a known token program");
        }
        const [sourceATA] = await findAssociatedTokenPda({
          mint: selectedV1.asset,
          owner: this.signer.address,
          tokenProgram: tokenProgramAddress
        });
        const [destinationATA] = await findAssociatedTokenPda({
          mint: selectedV1.asset,
          owner: selectedV1.payTo,
          tokenProgram: tokenProgramAddress
        });
        const transferIx = getTransferCheckedInstruction(
          {
            source: sourceATA,
            mint: selectedV1.asset,
            destination: destinationATA,
            authority: this.signer,
            amount: BigInt(selectedV1.maxAmountRequired),
            decimals: tokenMint.data.decimals
          },
          { programAddress: tokenProgramAddress }
        );
        const feePayer = selectedV1.extra?.feePayer;
        if (!feePayer) {
          throw new Error("feePayer is required in paymentRequirements.extra for SVM transactions");
        }
        const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
        const sellerMemo = selectedV1.extra?.memo;
        let memoData;
        if (sellerMemo) {
          memoData = new TextEncoder().encode(sellerMemo);
          if (memoData.byteLength > MAX_MEMO_BYTES) {
            throw new Error(`extra.memo exceeds maximum ${MAX_MEMO_BYTES} bytes`);
          }
        } else {
          const nonce = crypto.getRandomValues(new Uint8Array(16));
          memoData = new TextEncoder().encode(
            Array.from(nonce).map((b) => b.toString(16).padStart(2, "0")).join("")
          );
        }
        const memoIx = {
          programAddress: MEMO_PROGRAM_ADDRESS,
          accounts: [],
          data: memoData
        };
        const tx = pipe(
          createTransactionMessage({ version: 0 }),
          (tx2) => setTransactionMessageComputeUnitPrice(DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS, tx2),
          (tx2) => setTransactionMessageFeePayer(feePayer, tx2),
          (tx2) => prependTransactionMessageInstruction(
            getSetComputeUnitLimitInstruction({ units: DEFAULT_COMPUTE_UNIT_LIMIT }),
            tx2
          ),
          (tx2) => appendTransactionMessageInstructions([transferIx, memoIx], tx2),
          (tx2) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, tx2)
        );
        const signedTransaction = await partiallySignTransactionMessageWithSigners(tx);
        const base64EncodedWireTransaction = getBase64EncodedWireTransaction(signedTransaction);
        const payload = {
          transaction: base64EncodedWireTransaction
        };
        return {
          x402Version: x402Version2,
          scheme: selectedV1.scheme,
          network: selectedV1.network,
          payload
        };
      }
    };
  }
});

// node_modules/@x402/svm/dist/esm/chunk-BTZ3CTLR.mjs
var init_chunk_BTZ3CTLR = __esm({
  "node_modules/@x402/svm/dist/esm/chunk-BTZ3CTLR.mjs"() {
    "use strict";
    init_chunk_6JPFBIJG();
  }
});

// node_modules/@x402/svm/dist/esm/chunk-BC643GBZ.mjs
var init_chunk_BC643GBZ = __esm({
  "node_modules/@x402/svm/dist/esm/chunk-BC643GBZ.mjs"() {
    "use strict";
    init_chunk_BTZ3CTLR();
    init_chunk_6JPFBIJG();
  }
});

// node_modules/@x402/svm/dist/esm/exact/client/index.mjs
var client_exports = {};
__export(client_exports, {
  ExactSvmScheme: () => ExactSvmScheme,
  registerExactSvmScheme: () => registerExactSvmScheme
});
function registerExactSvmScheme(client, config) {
  if (config.networks && config.networks.length > 0) {
    config.networks.forEach((network) => {
      client.register(network, new ExactSvmScheme(config.signer));
    });
  } else {
    client.register("solana:*", new ExactSvmScheme(config.signer));
  }
  NETWORKS2.forEach((network) => {
    client.registerV1(network, new ExactSvmSchemeV1(config.signer));
  });
  if (config.policies) {
    config.policies.forEach((policy) => {
      client.registerPolicy(policy);
    });
  }
  return client;
}
var init_client3 = __esm({
  "node_modules/@x402/svm/dist/esm/exact/client/index.mjs"() {
    "use strict";
    init_chunk_MPB7KQPX();
    init_chunk_WWACQNRQ();
    init_chunk_TOJMXN7W();
    init_chunk_BC643GBZ();
    init_chunk_BTZ3CTLR();
    init_chunk_6JPFBIJG();
  }
});

// src/proxy.ts
import { AsyncLocalStorage } from "async_hooks";
import { createServer } from "http";
import { finished } from "stream";
import { homedir as homedir6 } from "os";
import { join as join9 } from "path";
import { mkdir as mkdir4, writeFile as writeFile2, readFile as readFile2, stat as fsStat } from "fs/promises";
import { readFileSync as readFileSync2, existsSync } from "fs";
function pickFreeModel(excludeList) {
  for (const m of FREE_MODELS) {
    if (!excludeList?.has(m)) return m;
  }
  return void 0;
}
function toUpstreamModelId(modelId) {
  if (modelId.startsWith("free/")) {
    return "nvidia/" + modelId.slice("free/".length);
  }
  return modelId;
}
function timeoutForModel(modelId) {
  return REASONING_MODEL_IDS.has(modelId) ? REASONING_MODEL_TIMEOUT_MS : PER_MODEL_TIMEOUT_MS;
}
async function readBodyWithTimeout(body, timeoutMs = MODEL_BODY_READ_TIMEOUT_MS) {
  if (!body) return [];
  const reader = body.getReader();
  const chunks = [];
  let timer;
  try {
    while (true) {
      const result = await Promise.race([
        reader.read(),
        new Promise((_, reject) => {
          timer = setTimeout(() => reject(new Error("Body read timeout")), timeoutMs);
        })
      ]);
      clearTimeout(timer);
      if (result.done) break;
      chunks.push(result.value);
    }
  } finally {
    clearTimeout(timer);
    reader.releaseLock();
  }
  return chunks;
}
function transformPaymentError(errorBody) {
  try {
    const parsed = JSON.parse(errorBody);
    if (parsed.error === "Payment verification failed" && parsed.details) {
      const match = parsed.details.match(/Verification failed:\s*(\{.*\})/s);
      if (match) {
        const innerJson = JSON.parse(match[1]);
        if (innerJson.invalidReason === "insufficient_funds" && innerJson.invalidMessage) {
          const balanceMatch = innerJson.invalidMessage.match(
            /insufficient balance:\s*(\d+)\s*<\s*(\d+)/i
          );
          if (balanceMatch) {
            const currentMicros = parseInt(balanceMatch[1], 10);
            const requiredMicros = parseInt(balanceMatch[2], 10);
            const currentUSD = (currentMicros / 1e6).toFixed(6);
            const requiredUSD = (requiredMicros / 1e6).toFixed(6);
            const wallet = innerJson.payer || "unknown";
            const shortWallet = wallet.length > 12 ? `${wallet.slice(0, 6)}...${wallet.slice(-4)}` : wallet;
            return JSON.stringify({
              error: {
                message: `Insufficient USDC balance. Current: $${currentUSD}, Required: ~$${requiredUSD}`,
                type: "insufficient_funds",
                wallet,
                current_balance_usd: currentUSD,
                required_usd: requiredUSD,
                help: `Fund wallet ${shortWallet} with USDC on Base, or use free model: /model free`
              }
            });
          }
        }
        if (innerJson.invalidReason === "invalid_payload") {
          return JSON.stringify({
            error: {
              message: "Payment signature invalid. This may be a temporary issue.",
              type: "invalid_payload",
              help: "Try again. If this persists, reinstall ClawRouter: curl -fsSL https://blockrun.ai/ClawRouter-update | bash"
            }
          });
        }
        if (innerJson.invalidReason === "transaction_simulation_failed") {
          console.error(
            `[ClawRouter] Solana transaction simulation failed: ${innerJson.invalidMessage || "unknown"}`
          );
          return JSON.stringify({
            error: {
              message: "Solana payment simulation failed. Retrying with a different model.",
              type: "transaction_simulation_failed",
              help: "This is usually temporary. If it persists, check your Solana USDC balance or try: /model free"
            }
          });
        }
      }
    }
    if (parsed.error === "Payment verification failed" && parsed.code === "PAYMENT_INVALID" && parsed.debug) {
      const debugLower = parsed.debug.toLowerCase();
      const wallet = parsed.payer || "unknown";
      const shortWallet = wallet.length > 12 ? `${wallet.slice(0, 6)}...${wallet.slice(-4)}` : wallet;
      const chain3 = wallet.startsWith("0x") ? "Base" : "Solana";
      if (debugLower.includes("insufficient")) {
        return JSON.stringify({
          error: {
            message: `Insufficient ${chain3} USDC balance.`,
            type: "insufficient_funds",
            wallet,
            help: chain3 === "Solana" ? `Fund wallet ${shortWallet} with USDC on Solana, or switch to Base: /wallet base` : `Fund wallet ${shortWallet} with USDC on Base, or use free model: /model free`
          }
        });
      }
      if (debugLower.includes("transaction_simulation_failed") || debugLower.includes("simulation")) {
        console.error(`[ClawRouter] ${chain3} transaction simulation failed: ${parsed.debug}`);
        return JSON.stringify({
          error: {
            message: `${chain3} payment simulation failed. Retrying with a different model.`,
            type: "transaction_simulation_failed",
            help: "This is usually temporary. If it persists, try: /model free"
          }
        });
      }
      if (debugLower.includes("invalid signature") || debugLower.includes("invalid_signature")) {
        return JSON.stringify({
          error: {
            message: `${chain3} payment signature invalid.`,
            type: "invalid_payload",
            help: "Try again. If this persists, reinstall ClawRouter: curl -fsSL https://blockrun.ai/ClawRouter-update | bash"
          }
        });
      }
      if (debugLower.includes("expired")) {
        return JSON.stringify({
          error: {
            message: `${chain3} payment expired. Retrying.`,
            type: "expired",
            help: "This is usually temporary."
          }
        });
      }
      console.error(
        `[ClawRouter] ${chain3} payment verification failed: ${parsed.debug} payer=${wallet}`
      );
      return JSON.stringify({
        error: {
          message: `${chain3} payment verification failed: ${parsed.debug}`,
          type: "payment_invalid",
          wallet,
          help: chain3 === "Solana" ? "Try again or switch to Base: /wallet base" : "Try again. If this persists, try: /model free"
        }
      });
    }
    if (parsed.error === "Settlement failed" || parsed.error === "Payment settlement failed" || parsed.details?.includes("Settlement failed") || parsed.details?.includes("transaction_simulation_failed")) {
      const details = parsed.details || "";
      const gasError = details.includes("unable to estimate gas");
      return JSON.stringify({
        error: {
          message: gasError ? "Payment failed: network congestion or gas issue. Try again." : "Payment settlement failed. Try again in a moment.",
          type: "settlement_failed",
          help: "This is usually temporary. If it persists, try: /model free"
        }
      });
    }
  } catch {
  }
  return errorBody;
}
function categorizeError(status, body) {
  if (status === 401) return "auth_failure";
  if (status === 402) return "payment_error";
  if (status === 403) {
    if (/plan.*limit|quota.*exceeded|subscription|allowance/i.test(body)) return "quota_exceeded";
    return "auth_failure";
  }
  if (status === 429) return "rate_limited";
  if (status === 529) return "overloaded";
  if (status === 503 && /overload|capacity|too.*many.*request/i.test(body)) return "overloaded";
  if (status >= 500) return "server_error";
  if (status === 400 || status === 413) {
    if (PROVIDER_ERROR_PATTERNS.some((p) => p.test(body))) return "config_error";
    return null;
  }
  return null;
}
function recordProviderError(modelId, category) {
  if (!perProviderErrors.has(modelId)) {
    perProviderErrors.set(modelId, {
      auth_failure: 0,
      quota_exceeded: 0,
      rate_limited: 0,
      overloaded: 0,
      server_error: 0,
      payment_error: 0,
      config_error: 0
    });
  }
  perProviderErrors.get(modelId)[category]++;
}
function isRateLimited(modelId) {
  const hitTime = rateLimitedModels.get(modelId);
  if (!hitTime) return false;
  const elapsed = Date.now() - hitTime;
  if (elapsed >= RATE_LIMIT_COOLDOWN_MS) {
    rateLimitedModels.delete(modelId);
    return false;
  }
  return true;
}
function markRateLimited(modelId) {
  rateLimitedModels.set(modelId, Date.now());
  console.log(`[ClawRouter] Model ${modelId} rate-limited, will deprioritize for 60s`);
}
function markOverloaded(modelId) {
  overloadedModels.set(modelId, Date.now());
  console.log(`[ClawRouter] Model ${modelId} overloaded, will deprioritize for 15s`);
}
function isOverloaded(modelId) {
  const hitTime = overloadedModels.get(modelId);
  if (!hitTime) return false;
  if (Date.now() - hitTime >= OVERLOAD_COOLDOWN_MS) {
    overloadedModels.delete(modelId);
    return false;
  }
  return true;
}
function prioritizeNonRateLimited(models) {
  const available = [];
  const degraded = [];
  for (const model of models) {
    if (isRateLimited(model) || isOverloaded(model)) {
      degraded.push(model);
    } else {
      available.push(model);
    }
  }
  return [...available, ...degraded];
}
function canWrite(res) {
  return !res.writableEnded && !res.destroyed && res.socket !== null && !res.socket.destroyed && res.socket.writable;
}
function safeWrite(res, data) {
  if (!canWrite(res)) {
    const bytes = typeof data === "string" ? Buffer.byteLength(data) : data.length;
    console.warn(`[ClawRouter] safeWrite: socket not writable, dropping ${bytes} bytes`);
    return false;
  }
  return res.write(data);
}
function getProxyPort() {
  return PROXY_PORT;
}
async function checkExistingProxy(port) {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), HEALTH_CHECK_TIMEOUT_MS);
  try {
    const response = await fetch(`http://127.0.0.1:${port}/health`, {
      signal: controller.signal
    });
    clearTimeout(timeoutId);
    if (response.ok) {
      const data = await response.json();
      if (data.status === "ok" && data.wallet) {
        return { wallet: data.wallet, paymentChain: data.paymentChain };
      }
    }
    return void 0;
  } catch {
    clearTimeout(timeoutId);
    return void 0;
  }
}
function extractAssistantContent(payload) {
  if (!payload || typeof payload !== "object") return void 0;
  const record = payload;
  const choices = record.choices;
  if (!Array.isArray(choices) || choices.length === 0) return void 0;
  const firstChoice = choices[0];
  if (!firstChoice || typeof firstChoice !== "object") return void 0;
  const choice = firstChoice;
  const message = choice.message;
  if (!message || typeof message !== "object") return void 0;
  const content = message.content;
  return typeof content === "string" ? content : void 0;
}
function hasKnownLoopSignature(text) {
  const matchCount = DEGRADED_LOOP_PATTERNS.reduce(
    (count, pattern) => pattern.test(text) ? count + 1 : count,
    0
  );
  if (matchCount >= 2) return true;
  const lines = text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
  if (lines.length < 8) return false;
  const counts = /* @__PURE__ */ new Map();
  for (const line of lines) {
    counts.set(line, (counts.get(line) ?? 0) + 1);
  }
  const maxRepeat = Math.max(...counts.values());
  const uniqueRatio = counts.size / lines.length;
  return maxRepeat >= 3 && uniqueRatio <= 0.45;
}
function detectDegradedSuccessResponse(body) {
  const trimmed = body.trim();
  if (!trimmed) return void 0;
  if (DEGRADED_RESPONSE_PATTERNS.some((pattern) => pattern.test(trimmed))) {
    return "degraded response: overloaded placeholder";
  }
  if (hasKnownLoopSignature(trimmed)) {
    return "degraded response: repetitive loop output";
  }
  try {
    const parsed = JSON.parse(trimmed);
    const errorField = parsed.error;
    let errorText = "";
    if (typeof errorField === "string") {
      errorText = errorField;
    } else if (errorField && typeof errorField === "object") {
      const errObj = errorField;
      errorText = [
        typeof errObj.message === "string" ? errObj.message : "",
        typeof errObj.type === "string" ? errObj.type : "",
        typeof errObj.code === "string" ? errObj.code : ""
      ].filter(Boolean).join(" ");
    }
    if (errorText && PROVIDER_ERROR_PATTERNS.some((pattern) => pattern.test(errorText))) {
      return `degraded response: ${errorText.slice(0, 120)}`;
    }
    const choices = parsed.choices;
    if (Array.isArray(choices) && choices.length > 0) {
      const choice = choices[0];
      const msg = choice.message ?? choice.delta;
      if (msg) {
        const content = msg.content;
        const toolCalls = msg.tool_calls;
        const hasContent = typeof content === "string" && content.trim().length > 0;
        const hasToolCalls = Array.isArray(toolCalls) && toolCalls.length > 0;
        const finishReason = choice.finish_reason;
        if (!hasContent && !hasToolCalls && finishReason === "stop") {
          return "degraded response: empty turn (no content or tool calls)";
        }
      }
    }
    const assistantContent = extractAssistantContent(parsed);
    if (!assistantContent) return void 0;
    if (DEGRADED_RESPONSE_PATTERNS.some((pattern) => pattern.test(assistantContent))) {
      return "degraded response: overloaded assistant content";
    }
    if (hasKnownLoopSignature(assistantContent)) {
      return "degraded response: repetitive assistant loop";
    }
  } catch {
  }
  return void 0;
}
function sanitizeToolId(id) {
  if (!id || typeof id !== "string") return id;
  if (VALID_TOOL_ID_PATTERN.test(id)) return id;
  return id.replace(/[^a-zA-Z0-9_-]/g, "_");
}
function sanitizeToolIds(messages) {
  if (!messages || messages.length === 0) return messages;
  let hasChanges = false;
  const sanitized = messages.map((msg) => {
    const typedMsg = msg;
    let msgChanged = false;
    let newMsg = { ...msg };
    if (typedMsg.tool_calls && Array.isArray(typedMsg.tool_calls)) {
      const newToolCalls = typedMsg.tool_calls.map((tc) => {
        if (tc.id && typeof tc.id === "string") {
          const sanitized2 = sanitizeToolId(tc.id);
          if (sanitized2 !== tc.id) {
            msgChanged = true;
            return { ...tc, id: sanitized2 };
          }
        }
        return tc;
      });
      if (msgChanged) {
        newMsg = { ...newMsg, tool_calls: newToolCalls };
      }
    }
    if (typedMsg.tool_call_id && typeof typedMsg.tool_call_id === "string") {
      const sanitized2 = sanitizeToolId(typedMsg.tool_call_id);
      if (sanitized2 !== typedMsg.tool_call_id) {
        msgChanged = true;
        newMsg = { ...newMsg, tool_call_id: sanitized2 };
      }
    }
    if (Array.isArray(typedMsg.content)) {
      const newContent = typedMsg.content.map((block) => {
        if (!block || typeof block !== "object") return block;
        let blockChanged = false;
        let newBlock = { ...block };
        if (block.type === "tool_use" && block.id && typeof block.id === "string") {
          const sanitized2 = sanitizeToolId(block.id);
          if (sanitized2 !== block.id) {
            blockChanged = true;
            newBlock = { ...newBlock, id: sanitized2 };
          }
        }
        if (block.type === "tool_result" && block.tool_use_id && typeof block.tool_use_id === "string") {
          const sanitized2 = sanitizeToolId(block.tool_use_id);
          if (sanitized2 !== block.tool_use_id) {
            blockChanged = true;
            newBlock = { ...newBlock, tool_use_id: sanitized2 };
          }
        }
        if (blockChanged) {
          msgChanged = true;
          return newBlock;
        }
        return block;
      });
      if (msgChanged) {
        newMsg = { ...newMsg, content: newContent };
      }
    }
    if (msgChanged) {
      hasChanges = true;
      return newMsg;
    }
    return msg;
  });
  return hasChanges ? sanitized : messages;
}
function normalizeMessageRoles(messages) {
  if (!messages || messages.length === 0) return messages;
  let hasChanges = false;
  const normalized = messages.map((msg) => {
    if (VALID_ROLES.has(msg.role)) return msg;
    const mappedRole = ROLE_MAPPINGS[msg.role];
    if (mappedRole) {
      hasChanges = true;
      return { ...msg, role: mappedRole };
    }
    hasChanges = true;
    return { ...msg, role: "user" };
  });
  return hasChanges ? normalized : messages;
}
function normalizeMessagesForGoogle(messages) {
  if (!messages || messages.length === 0) return messages;
  let firstNonSystemIdx = -1;
  for (let i = 0; i < messages.length; i++) {
    if (messages[i].role !== "system") {
      firstNonSystemIdx = i;
      break;
    }
  }
  if (firstNonSystemIdx === -1) return messages;
  const firstRole = messages[firstNonSystemIdx].role;
  if (firstRole === "user") return messages;
  if (firstRole === "assistant" || firstRole === "model") {
    const normalized = [...messages];
    normalized.splice(firstNonSystemIdx, 0, {
      role: "user",
      content: "(continuing conversation)"
    });
    return normalized;
  }
  return messages;
}
function isGoogleModel(modelId) {
  return modelId.startsWith("google/") || modelId.startsWith("gemini");
}
function normalizeMessagesForThinking(messages) {
  if (!messages || messages.length === 0) return messages;
  let hasChanges = false;
  const normalized = messages.map((msg) => {
    if (msg.role !== "assistant" || msg.reasoning_content !== void 0) {
      return msg;
    }
    hasChanges = true;
    return { ...msg, reasoning_content: "" };
  });
  return hasChanges ? normalized : messages;
}
function debrandSystemMessages(messages, resolvedModel) {
  const PROFILE_NAMES = ["auto", "free", "eco", "premium"];
  const profilePattern = new RegExp(`\\bblockrun/(${PROFILE_NAMES.join("|")})\\b`, "gi");
  const prefixPattern = /\bblockrun\/(?=[a-z])/gi;
  let hasChanges = false;
  const result = messages.map((msg) => {
    if (msg.role !== "system" || typeof msg.content !== "string") return msg;
    let content = msg.content;
    const afterProfiles = content.replace(profilePattern, resolvedModel);
    const afterPrefix = afterProfiles.replace(prefixPattern, "");
    if (afterPrefix !== content) {
      hasChanges = true;
      content = afterPrefix;
    }
    return content !== msg.content ? { ...msg, content } : msg;
  });
  return hasChanges ? result : messages;
}
function truncateMessages(messages) {
  if (!messages || messages.length <= MAX_MESSAGES) {
    return {
      messages,
      wasTruncated: false,
      originalCount: messages?.length ?? 0,
      truncatedCount: messages?.length ?? 0
    };
  }
  const systemMsgs = messages.filter((m) => m.role === "system");
  const conversationMsgs = messages.filter((m) => m.role !== "system");
  const maxConversation = MAX_MESSAGES - systemMsgs.length;
  const truncatedConversation = conversationMsgs.slice(-maxConversation);
  const result = [...systemMsgs, ...truncatedConversation];
  console.log(
    `[ClawRouter] Truncated messages: ${messages.length} \u2192 ${result.length} (kept ${systemMsgs.length} system + ${truncatedConversation.length} recent)`
  );
  return {
    messages: result,
    wasTruncated: true,
    originalCount: messages.length,
    truncatedCount: result.length
  };
}
function stripThinkingTokens(content) {
  if (!content) return content;
  let cleaned = content.replace(KIMI_BLOCK_RE, "");
  cleaned = cleaned.replace(KIMI_TOKEN_RE, "");
  cleaned = cleaned.replace(THINKING_BLOCK_RE, "");
  cleaned = cleaned.replace(THINKING_TAG_RE, "");
  return cleaned;
}
function buildModelPricing() {
  const map = /* @__PURE__ */ new Map();
  for (const m of BLOCKRUN_MODELS) {
    if (m.id === AUTO_MODEL) continue;
    const promoPrice = getActivePromoPrice(m);
    map.set(m.id, {
      inputPrice: m.inputPrice,
      outputPrice: m.outputPrice,
      ...promoPrice !== void 0 && { flatPrice: promoPrice }
    });
  }
  return map;
}
function buildProxyModelList(createdAt = Math.floor(Date.now() / 1e3)) {
  const seen = /* @__PURE__ */ new Set();
  return OPENCLAW_MODELS.filter((model) => {
    if (seen.has(model.id)) return false;
    seen.add(model.id);
    return true;
  }).map((model) => ({
    id: model.id,
    object: "model",
    created: createdAt,
    owned_by: model.id.includes("/") ? model.id.split("/")[0] ?? "blockrun" : "blockrun"
  }));
}
function mergeRoutingConfig(overrides) {
  if (!overrides) return DEFAULT_ROUTING_CONFIG;
  const mergeTiers = (defaults, user) => {
    if (user === null) return null;
    if (user === void 0) return defaults ?? null;
    return { ...defaults ?? {}, ...user };
  };
  return {
    ...DEFAULT_ROUTING_CONFIG,
    ...overrides,
    classifier: { ...DEFAULT_ROUTING_CONFIG.classifier, ...overrides.classifier },
    scoring: { ...DEFAULT_ROUTING_CONFIG.scoring, ...overrides.scoring },
    tiers: mergeTiers(DEFAULT_ROUTING_CONFIG.tiers, overrides.tiers) ?? DEFAULT_ROUTING_CONFIG.tiers,
    agenticTiers: mergeTiers(DEFAULT_ROUTING_CONFIG.agenticTiers, overrides.agenticTiers),
    ecoTiers: mergeTiers(DEFAULT_ROUTING_CONFIG.ecoTiers, overrides.ecoTiers),
    premiumTiers: mergeTiers(DEFAULT_ROUTING_CONFIG.premiumTiers, overrides.premiumTiers),
    overrides: { ...DEFAULT_ROUTING_CONFIG.overrides, ...overrides.overrides }
  };
}
function buildCostBreakdown(params) {
  const { actualModelUsed, routingProfile, modelPricing, inputTokens, outputTokens, tier } = params;
  if (typeof inputTokens !== "number" || typeof outputTokens !== "number" || inputTokens < 0 || outputTokens < 0) {
    return void 0;
  }
  const pricing = modelPricing.get(actualModelUsed);
  const inputPrice = pricing?.inputPrice ?? 0;
  const outputPrice = pricing?.outputPrice ?? 0;
  const input = inputTokens / 1e6 * inputPrice;
  const output = outputTokens / 1e6 * outputPrice;
  const costs = calculateModelCost(
    actualModelUsed,
    modelPricing,
    inputTokens,
    outputTokens,
    routingProfile
  );
  const total = costs.costEstimate;
  const baseline = costs.baselineCost;
  const savingsPct = routingProfile === "premium" || baseline <= 0 ? void 0 : Math.max(0, Math.min(100, Math.round(costs.savings * 100)));
  return {
    total,
    input,
    output,
    baseline,
    ...savingsPct !== void 0 ? { savings_pct: savingsPct } : {},
    model: actualModelUsed,
    ...tier ? { tier } : {}
  };
}
function estimateAmount(modelId, bodyLength, maxTokens) {
  const model = BLOCKRUN_MODELS.find((m) => m.id === modelId);
  if (!model) return void 0;
  let costUsd;
  const promoPrice = getActivePromoPrice(model);
  if (promoPrice !== void 0) {
    costUsd = promoPrice;
  } else {
    const estimatedInputTokens = Math.ceil(bodyLength / 4);
    const estimatedOutputTokens = maxTokens || model.maxOutput || 4096;
    costUsd = estimatedInputTokens / 1e6 * model.inputPrice + estimatedOutputTokens / 1e6 * model.outputPrice;
  }
  const amountMicros = Math.max(1e3, Math.ceil(costUsd * 1.2 * 1e6));
  return amountMicros.toString();
}
function estimatePhoneCost(urlPath) {
  const op = urlPath.replace(/^\/v1\//, "").split("?")[0];
  for (const key of Object.keys(PHONE_PRICING).sort((a, b) => b.length - a.length)) {
    if (op === key || op.startsWith(`${key}/`)) return PHONE_PRICING[key];
  }
  return 0.05;
}
function resolvePhoneTelemetryCost(args) {
  if (args.paidAmount > 0) return args.paidAmount;
  const upstreamSucceeded = args.upstreamStatus >= 200 && args.upstreamStatus < 300;
  const isPostRequest = (args.method ?? "").toUpperCase() === "POST";
  if (args.isPhone && upstreamSucceeded && isPostRequest) {
    return estimatePhoneCost(args.urlPath);
  }
  return args.paidAmount;
}
function estimateVideoCost(model, durationSeconds, hasImageInput) {
  const p = VIDEO_PRICING[model];
  if (!p) return 0.4 * 1.05;
  const dur = durationSeconds ?? p.defaultDurationSeconds;
  const rate = hasImageInput && p.pricePerSecondImageInput ? p.pricePerSecondImageInput : p.pricePerSecond;
  return rate * dur * 1.05;
}
function estimateImageCost(model, size5, n = 1) {
  const pricing = IMAGE_PRICING[model];
  if (!pricing) return 0.04 * n * 1.05;
  const sizePrice = size5 && pricing.sizes ? pricing.sizes[size5] : void 0;
  const pricePerImage = sizePrice ?? pricing.default;
  return pricePerImage * n * 1.05;
}
async function proxyPaidApiRequest(req, res, apiBase, payFetch, getActualPaymentUsd) {
  const startTime = Date.now();
  const upstreamUrl = `${apiBase}${req.url}`;
  const isBlockrunExa = req.url?.startsWith("/v1/exa/") ?? false;
  const isModalSandbox = req.url?.startsWith("/v1/modal/") ?? false;
  const isPhone = (req.url?.startsWith("/v1/phone/") ?? false) || (req.url?.startsWith("/v1/voice/") ?? false);
  const isSurf = req.url?.startsWith("/v1/surf/") ?? false;
  const requestLabel = isBlockrunExa ? "BlockRun Exa" : isModalSandbox ? "Modal Sandbox" : isPhone ? "Phone/Voice" : isSurf ? "Surf" : "Partner";
  const bodyChunks = [];
  for await (const chunk of req) {
    bodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  }
  const body = Buffer.concat(bodyChunks);
  const headers = {};
  for (const [key, value] of Object.entries(req.headers)) {
    if (key === "host" || key === "connection" || key === "transfer-encoding" || key === "content-length")
      continue;
    if (key.startsWith("x-stainless-") || key.startsWith("anthropic-")) continue;
    if (typeof value === "string") headers[key] = value;
  }
  if (!headers["content-type"]) headers["content-type"] = "application/json";
  headers["user-agent"] = USER_AGENT;
  console.log(`[ClawRouter] ${requestLabel} request: ${req.method} ${req.url}`);
  const upstream = await payFetch(upstreamUrl, {
    method: req.method ?? "POST",
    headers,
    body: body.length > 0 ? new Uint8Array(body) : void 0
  });
  const responseHeaders = {};
  upstream.headers.forEach((value, key) => {
    if (key === "transfer-encoding" || key === "connection" || key === "content-encoding") return;
    responseHeaders[key] = value;
  });
  res.writeHead(upstream.status, responseHeaders);
  if (upstream.body) {
    const chunks = await readBodyWithTimeout(upstream.body, ERROR_BODY_READ_TIMEOUT_MS);
    for (const chunk of chunks) {
      safeWrite(res, Buffer.from(chunk));
    }
  }
  res.end();
  const latencyMs = Date.now() - startTime;
  console.log(`[ClawRouter] ${requestLabel} response: ${upstream.status} (${latencyMs}ms)`);
  const paidAmount = getActualPaymentUsd();
  const requestCost = resolvePhoneTelemetryCost({
    paidAmount,
    isPhone,
    upstreamStatus: upstream.status,
    method: req.method,
    urlPath: req.url ?? ""
  });
  logUsage({
    timestamp: (/* @__PURE__ */ new Date()).toISOString(),
    model: isBlockrunExa ? "blockrun-exa" : isModalSandbox ? "modal-sandbox" : isPhone ? (req.url ?? "").replace(/^\/v1\//, "").split("?")[0] : isSurf ? (req.url ?? "").replace(/^\/v1\//, "").split("?")[0] : "partner",
    tier: isPhone ? "PHONE" : isSurf ? "SURF" : "PARTNER",
    cost: requestCost,
    baselineCost: requestCost,
    savings: 0,
    latencyMs,
    partnerId: (req.url?.split("?")[0] ?? "").replace(/^\/v1\//, "").replace(/\//g, "_") || "unknown",
    service: isBlockrunExa ? "web_search" : isModalSandbox ? "modal" : isPhone ? "phone" : isSurf ? "surf" : "partner"
  }).catch(() => {
  });
}
function readImageFileAsDataUri(filePath) {
  const resolved = filePath.startsWith("~/") ? join9(homedir6(), filePath.slice(2)) : filePath;
  if (!existsSync(resolved)) {
    throw new Error(`Image file not found: ${resolved}`);
  }
  const ext = resolved.split(".").pop()?.toLowerCase() ?? "png";
  const mimeMap = {
    png: "image/png",
    jpg: "image/jpeg",
    jpeg: "image/jpeg",
    webp: "image/webp"
  };
  const mime = mimeMap[ext] ?? "image/png";
  const data = readFileSync2(resolved);
  return `data:${mime};base64,${data.toString("base64")}`;
}
async function uploadDataUriToHost(dataUri) {
  const match = dataUri.match(/^data:(image\/\w+);base64,(.+)$/);
  if (!match) throw new Error("Invalid data URI format");
  const [, mimeType, b64Data] = match;
  const ext = mimeType === "image/jpeg" ? "jpg" : mimeType.split("/")[1] ?? "png";
  const buffer2 = Buffer.from(b64Data, "base64");
  const blob = new Blob([buffer2], { type: mimeType });
  const form = new FormData();
  form.append("reqtype", "fileupload");
  form.append("fileToUpload", blob, `image.${ext}`);
  const uploadController = new AbortController();
  const uploadTimeout = setTimeout(() => uploadController.abort(), 3e4);
  try {
    const resp = await fetch("https://catbox.moe/user/api.php", {
      method: "POST",
      body: form,
      signal: uploadController.signal
    });
    if (!resp.ok) throw new Error(`catbox.moe upload failed: HTTP ${resp.status}`);
    const result = await resp.text();
    if (result.startsWith("https://")) {
      return result.trim();
    }
    throw new Error(`catbox.moe upload failed: ${result}`);
  } finally {
    clearTimeout(uploadTimeout);
  }
}
async function startProxy(options) {
  const upstreamProxy = await applyUpstreamProxy(options.upstreamProxy);
  if (upstreamProxy) {
    console.log(`[ClawRouter] Upstream proxy: ${upstreamProxy}`);
  }
  const walletKey = typeof options.wallet === "string" ? options.wallet : options.wallet.key;
  const solanaPrivateKeyBytes = typeof options.wallet === "string" ? void 0 : options.wallet.solanaPrivateKeyBytes;
  const paymentChain = options.paymentChain ?? await resolvePaymentChain();
  const apiBase = options.apiBase ?? (paymentChain === "solana" && solanaPrivateKeyBytes ? BLOCKRUN_SOLANA_API : BLOCKRUN_API);
  if (paymentChain === "solana" && !solanaPrivateKeyBytes) {
    console.warn(
      `[ClawRouter] \u26A0 Payment chain is Solana but no mnemonic found \u2014 falling back to Base (EVM).`
    );
    console.warn(
      `[ClawRouter]   To fix: run "npx @blockrun/clawrouter wallet recover" if your mnemonic exists,`
    );
    console.warn(`[ClawRouter]   or run "npx @blockrun/clawrouter chain base" to switch to EVM.`);
  } else if (paymentChain === "solana") {
    console.log(`[ClawRouter] Payment chain: Solana (${BLOCKRUN_SOLANA_API})`);
  }
  const listenPort = options.port ?? getProxyPort();
  const existingProxy = await checkExistingProxy(listenPort);
  if (existingProxy) {
    const account2 = privateKeyToAccount(walletKey);
    const baseUrl2 = `http://127.0.0.1:${listenPort}`;
    if (existingProxy.wallet !== account2.address) {
      console.warn(
        `[ClawRouter] Existing proxy on port ${listenPort} uses wallet ${existingProxy.wallet}, but current config uses ${account2.address}. Reusing existing proxy.`
      );
    }
    if (existingProxy.paymentChain) {
      if (existingProxy.paymentChain !== paymentChain) {
        throw new Error(
          `Existing proxy on port ${listenPort} is using ${existingProxy.paymentChain} but ${paymentChain} was requested. Stop the existing proxy first or use a different port.`
        );
      }
    } else if (paymentChain !== "base") {
      console.warn(
        `[ClawRouter] Existing proxy on port ${listenPort} does not report paymentChain (pre-v0.11 instance). Assuming Base.`
      );
      throw new Error(
        `Existing proxy on port ${listenPort} is a pre-v0.11 instance (assumed Base) but ${paymentChain} was requested. Stop the existing proxy first or use a different port.`
      );
    }
    let reuseSolanaAddress;
    if (solanaPrivateKeyBytes) {
      const { createKeyPairSignerFromPrivateKeyBytes: createKeyPairSignerFromPrivateKeyBytes2 } = await Promise.resolve().then(() => (init_index_node37(), index_node_exports));
      const solanaSigner = await createKeyPairSignerFromPrivateKeyBytes2(solanaPrivateKeyBytes);
      reuseSolanaAddress = solanaSigner.address;
    }
    let balanceMonitor2;
    if (paymentChain === "solana" && reuseSolanaAddress) {
      const { SolanaBalanceMonitor: SolanaBalanceMonitor2 } = await Promise.resolve().then(() => (init_solana_balance(), solana_balance_exports));
      balanceMonitor2 = new SolanaBalanceMonitor2(reuseSolanaAddress);
    } else {
      balanceMonitor2 = new BalanceMonitor(account2.address);
    }
    options.onReady?.(listenPort);
    return {
      port: listenPort,
      baseUrl: baseUrl2,
      walletAddress: existingProxy.wallet,
      solanaAddress: reuseSolanaAddress,
      balanceMonitor: balanceMonitor2,
      close: async () => {
      }
    };
  }
  const account = privateKeyToAccount(walletKey);
  const evmPublicClient = createPublicClient({ chain: base, transport: http() });
  const evmSigner = toClientEvmSigner(account, evmPublicClient);
  const x402 = new x402Client();
  registerExactEvmScheme(x402, { signer: evmSigner });
  let solanaAddress;
  if (solanaPrivateKeyBytes) {
    const { registerExactSvmScheme: registerExactSvmScheme2 } = await Promise.resolve().then(() => (init_client3(), client_exports));
    const { createKeyPairSignerFromPrivateKeyBytes: createKeyPairSignerFromPrivateKeyBytes2 } = await Promise.resolve().then(() => (init_index_node37(), index_node_exports));
    const solanaSigner = await createKeyPairSignerFromPrivateKeyBytes2(solanaPrivateKeyBytes);
    solanaAddress = solanaSigner.address;
    registerExactSvmScheme2(x402, { signer: solanaSigner });
    console.log(`[ClawRouter] Solana wallet: ${solanaAddress}`);
  }
  x402.onAfterPaymentCreation(async (context) => {
    const network = context.selectedRequirements.network;
    const chain3 = network.startsWith("eip155") ? "Base (EVM)" : network.startsWith("solana") ? "Solana" : network;
    const amountMicros = parseInt(context.selectedRequirements.amount || "0", 10);
    const amountUsd = amountMicros / 1e6;
    const store = paymentStore.getStore();
    if (store) store.amountUsd = amountUsd;
    console.log(`[ClawRouter] Payment signed on ${chain3} (${network}) \u2014 $${amountUsd.toFixed(6)}`);
  });
  const payFetch = createPayFetchWithPreAuth(fetch, x402, void 0, {
    skipPreAuth: paymentChain === "solana"
  });
  let balanceMonitor;
  if (options._balanceMonitorOverride) {
    balanceMonitor = options._balanceMonitorOverride;
  } else if (paymentChain === "solana" && solanaAddress) {
    const { SolanaBalanceMonitor: SolanaBalanceMonitor2 } = await Promise.resolve().then(() => (init_solana_balance(), solana_balance_exports));
    balanceMonitor = new SolanaBalanceMonitor2(solanaAddress);
  } else {
    balanceMonitor = new BalanceMonitor(account.address);
  }
  const routingConfig = mergeRoutingConfig(options.routingConfig);
  const modelPricing = buildModelPricing();
  const routerOpts = {
    config: routingConfig,
    modelPricing
  };
  const deduplicator = new RequestDeduplicator();
  const responseCache2 = new ResponseCache(options.cacheConfig);
  const sessionStore = new SessionStore(options.sessionConfig);
  const sessionJournal = new SessionJournal();
  const connections = /* @__PURE__ */ new Set();
  const server = createServer((req, res) => {
    paymentStore.run({ amountUsd: 0 }, async () => {
      req.on("error", (err) => {
        console.error(`[ClawRouter] Request stream error: ${err.message}`);
      });
      res.on("error", (err) => {
        console.error(`[ClawRouter] Response stream error: ${err.message}`);
      });
      finished(res, (err) => {
        if (err && err.code !== "ERR_STREAM_DESTROYED") {
          console.error(`[ClawRouter] Response finished with error: ${err.message}`);
        }
      });
      finished(req, (err) => {
        if (err && err.code !== "ERR_STREAM_DESTROYED") {
          console.error(`[ClawRouter] Request finished with error: ${err.message}`);
        }
      });
      if (req.url === "/health" || req.url?.startsWith("/health?")) {
        const url = new URL(req.url, "http://localhost");
        const full = url.searchParams.get("full") === "true";
        const response = {
          status: "ok",
          wallet: account.address,
          paymentChain
        };
        if (solanaAddress) {
          response.solana = solanaAddress;
        }
        if (upstreamProxy) {
          response.upstreamProxy = upstreamProxy;
        }
        if (full) {
          try {
            const balanceInfo = await balanceMonitor.checkBalance();
            response.balance = balanceInfo.balanceUSD;
            response.isLow = balanceInfo.isLow;
            response.isEmpty = balanceInfo.isEmpty;
          } catch {
            response.balanceError = "Could not fetch balance";
          }
        }
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end(JSON.stringify(response));
        return;
      }
      if (req.url === "/cache" || req.url?.startsWith("/cache?")) {
        const stats = responseCache2.getStats();
        res.writeHead(200, {
          "Content-Type": "application/json",
          "Cache-Control": "no-cache"
        });
        res.end(JSON.stringify(stats, null, 2));
        return;
      }
      if (req.url === "/stats" && req.method === "DELETE") {
        try {
          const result = await clearStats();
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ cleared: true, deletedFiles: result.deletedFiles }));
        } catch (err) {
          res.writeHead(500, { "Content-Type": "application/json" });
          res.end(
            JSON.stringify({
              error: `Failed to clear stats: ${err instanceof Error ? err.message : String(err)}`
            })
          );
        }
        return;
      }
      if (req.url === "/stats" || req.url?.startsWith("/stats?")) {
        try {
          const url = new URL(req.url, "http://localhost");
          const days = parseInt(url.searchParams.get("days") || "7", 10);
          const stats = await getStats(Math.min(days, 30));
          res.writeHead(200, {
            "Content-Type": "application/json",
            "Cache-Control": "no-cache"
          });
          res.end(
            JSON.stringify(
              {
                ...stats,
                providerErrors: Object.fromEntries(perProviderErrors)
              },
              null,
              2
            )
          );
        } catch (err) {
          res.writeHead(500, { "Content-Type": "application/json" });
          res.end(
            JSON.stringify({
              error: `Failed to get stats: ${err instanceof Error ? err.message : String(err)}`
            })
          );
        }
        return;
      }
      if (req.url === "/v1/models" && req.method === "GET") {
        const models = buildProxyModelList();
        res.writeHead(200, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ object: "list", data: models }));
        return;
      }
      if (req.url?.startsWith("/share") && req.method === "GET") {
        try {
          const url = new URL(req.url, "http://localhost");
          const path2 = url.pathname;
          if (path2 === "/share/list") {
            const limit = Math.min(parseInt(url.searchParams.get("limit") || "20", 10), 100);
            const entries = await listRecent(limit);
            res.writeHead(200, { "Content-Type": "application/json" });
            res.end(
              JSON.stringify(
                entries.map((e7) => ({
                  id: e7.id,
                  timestamp: e7.timestamp,
                  model: e7.model,
                  sessionId: e7.sessionId,
                  requestSummary: e7.requestSummary,
                  responseLength: e7.responseText.length
                }))
              )
            );
            return;
          }
          if (path2 === "/share/last") {
            const sessionId = url.searchParams.get("sessionId") || void 0;
            const entry = await getLast(sessionId);
            if (!entry) {
              res.writeHead(404, { "Content-Type": "application/json" });
              res.end(JSON.stringify({ error: "no responses yet" }));
              return;
            }
            const preset = url.searchParams.get("as");
            if (preset && isSharePreset(preset)) {
              res.writeHead(200, {
                "Content-Type": "application/json",
                "Cache-Control": "no-cache"
              });
              res.end(
                JSON.stringify({
                  id: entry.id,
                  timestamp: entry.timestamp,
                  model: entry.model,
                  preset,
                  rendered: transform(entry.responseText, preset)
                })
              );
              return;
            }
            res.writeHead(200, { "Content-Type": "application/json" });
            res.end(JSON.stringify(entry));
            return;
          }
          const idMatch = path2.match(/^\/share\/(resp_[A-Za-z0-9_]+)(?:\/render)?$/);
          if (idMatch) {
            const id = idMatch[1];
            const entry = await getById(id);
            if (!entry) {
              res.writeHead(404, { "Content-Type": "application/json" });
              res.end(JSON.stringify({ error: `no response with id ${id}` }));
              return;
            }
            const preset = url.searchParams.get("as");
            if (preset && isSharePreset(preset)) {
              res.writeHead(200, { "Content-Type": "application/json" });
              res.end(
                JSON.stringify({
                  id: entry.id,
                  timestamp: entry.timestamp,
                  model: entry.model,
                  preset,
                  rendered: transform(entry.responseText, preset)
                })
              );
              return;
            }
            res.writeHead(200, { "Content-Type": "application/json" });
            res.end(JSON.stringify(entry));
            return;
          }
          res.writeHead(404, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "unknown share endpoint" }));
        } catch (err) {
          res.writeHead(500, { "Content-Type": "application/json" });
          res.end(
            JSON.stringify({
              error: `share failed: ${err instanceof Error ? err.message : String(err)}`
            })
          );
        }
        return;
      }
      if (req.url?.startsWith("/images/") && req.method === "GET") {
        const filename = req.url.slice("/images/".length).split("?")[0].replace(/[^a-zA-Z0-9._-]/g, "");
        if (!filename) {
          res.writeHead(400);
          res.end("Bad request");
          return;
        }
        const filePath = join9(IMAGE_DIR, filename);
        try {
          const s3 = await fsStat(filePath);
          if (!s3.isFile()) throw new Error("not a file");
          const ext = filename.split(".").pop()?.toLowerCase() ?? "png";
          const mime = {
            png: "image/png",
            jpg: "image/jpeg",
            jpeg: "image/jpeg",
            webp: "image/webp",
            gif: "image/gif"
          };
          const data = await readFile2(filePath);
          res.writeHead(200, {
            "Content-Type": mime[ext] ?? "application/octet-stream",
            "Content-Length": data.length
          });
          res.end(data);
        } catch {
          res.writeHead(404, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "Image not found" }));
        }
        return;
      }
      if (req.url?.startsWith("/audio/") && req.method === "GET") {
        const filename = req.url.slice("/audio/".length).split("?")[0].replace(/[^a-zA-Z0-9._-]/g, "");
        if (!filename) {
          res.writeHead(400);
          res.end("Bad request");
          return;
        }
        const filePath = join9(AUDIO_DIR, filename);
        try {
          const s3 = await fsStat(filePath);
          if (!s3.isFile()) throw new Error("not a file");
          const ext = filename.split(".").pop()?.toLowerCase() ?? "mp3";
          const mime = {
            mp3: "audio/mpeg",
            wav: "audio/wav",
            ogg: "audio/ogg",
            m4a: "audio/mp4"
          };
          const data = await readFile2(filePath);
          res.writeHead(200, {
            "Content-Type": mime[ext] ?? "audio/mpeg",
            "Content-Length": data.length
          });
          res.end(data);
        } catch {
          res.writeHead(404, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "Audio not found" }));
        }
        return;
      }
      if (req.url?.startsWith("/videos/") && req.method === "GET") {
        const filename = req.url.slice("/videos/".length).split("?")[0].replace(/[^a-zA-Z0-9._-]/g, "");
        if (!filename) {
          res.writeHead(400);
          res.end("Bad request");
          return;
        }
        const filePath = join9(VIDEO_DIR, filename);
        try {
          const s3 = await fsStat(filePath);
          if (!s3.isFile()) throw new Error("not a file");
          const ext = filename.split(".").pop()?.toLowerCase() ?? "mp4";
          const mime = {
            mp4: "video/mp4",
            webm: "video/webm",
            mov: "video/quicktime"
          };
          const data = await readFile2(filePath);
          res.writeHead(200, {
            "Content-Type": mime[ext] ?? "video/mp4",
            "Content-Length": data.length
          });
          res.end(data);
        } catch {
          res.writeHead(404, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "Video not found" }));
        }
        return;
      }
      if (req.url === "/v1/images/generations" && req.method === "POST") {
        const imgStartTime = Date.now();
        const chunks = [];
        for await (const chunk of req) {
          chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
        }
        const reqBody = Buffer.concat(chunks);
        let imgModel = "unknown";
        let imgCost = 0;
        try {
          const parsed = JSON.parse(reqBody.toString());
          imgModel = parsed.model || "openai/dall-e-3";
          const n = parsed.n || 1;
          imgCost = estimateImageCost(imgModel, parsed.size, n);
        } catch {
        }
        try {
          const upstream = await payFetch(`${apiBase}/v1/images/generations`, {
            method: "POST",
            headers: { "content-type": "application/json", "user-agent": USER_AGENT },
            body: reqBody
          });
          const text = await upstream.text();
          if (!upstream.ok && upstream.status !== 202) {
            res.writeHead(upstream.status, { "Content-Type": "application/json" });
            res.end(text);
            return;
          }
          let result;
          try {
            result = JSON.parse(text);
          } catch {
            res.writeHead(200, { "Content-Type": "application/json" });
            res.end(text);
            return;
          }
          if (result.poll_url && result.id && !result.data?.length) {
            const apiOrigin = new URL(apiBase).origin;
            const pollUrl = result.poll_url.startsWith("http") ? result.poll_url : `${apiOrigin}${result.poll_url}`;
            console.log(
              `[ClawRouter] Image job submitted (id=${result.id}), polling upstream \u2014 typical 30\u2013120s...`
            );
            const pollDeadline = Date.now() + 3e5;
            const pollInterval = 3e3;
            await new Promise((r) => setTimeout(r, 2e3));
            let pollError;
            let completed = false;
            while (Date.now() < pollDeadline) {
              const pollResp = await payFetch(pollUrl, {
                method: "GET",
                headers: { "user-agent": USER_AGENT }
              });
              const pollText = await pollResp.text();
              let pollBody = {};
              try {
                pollBody = JSON.parse(pollText);
              } catch {
                pollError = `Non-JSON poll response (${pollResp.status}): ${pollText.slice(0, 200)}`;
                break;
              }
              if (pollResp.status === 202 || pollBody.status === "queued" || pollBody.status === "in_progress") {
                await new Promise((r) => setTimeout(r, pollInterval));
                continue;
              }
              if (pollBody.status === "failed") {
                pollError = pollBody.error ?? "Upstream image generation failed";
                break;
              }
              if (pollResp.ok && pollBody.status === "completed") {
                result = pollBody;
                completed = true;
                break;
              }
              if (!pollResp.ok) {
                res.writeHead(pollResp.status, { "Content-Type": "application/json" });
                res.end(pollText);
                return;
              }
              result = pollBody;
              completed = true;
              break;
            }
            if (pollError) {
              res.writeHead(502, { "Content-Type": "application/json" });
              res.end(JSON.stringify({ error: "Image generation failed", details: pollError }));
              return;
            }
            if (!completed) {
              res.writeHead(504, { "Content-Type": "application/json" });
              res.end(
                JSON.stringify({
                  error: "Image generation timed out",
                  details: `Upstream did not complete within 5 minutes (job id=${result.id}). No payment has been settled.`
                })
              );
              return;
            }
          }
          if (result.data?.length) {
            await mkdir4(IMAGE_DIR, { recursive: true });
            const port2 = server.address()?.port ?? 8402;
            for (const img of result.data) {
              const dataUriMatch = img.url?.match(/^data:(image\/\w+);base64,(.+)$/);
              if (dataUriMatch) {
                const [, mimeType, b64] = dataUriMatch;
                const ext = mimeType === "image/jpeg" ? "jpg" : mimeType.split("/")[1] ?? "png";
                const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;
                await writeFile2(join9(IMAGE_DIR, filename), Buffer.from(b64, "base64"));
                img.url = `http://localhost:${port2}/images/${filename}`;
                console.log(`[ClawRouter] Image saved \u2192 ${img.url}`);
              } else if (img.url?.startsWith("https://") || img.url?.startsWith("http://")) {
                try {
                  const imgResp = await fetch(img.url);
                  if (imgResp.ok) {
                    const contentType = imgResp.headers.get("content-type") ?? "image/png";
                    const ext = contentType.includes("jpeg") || contentType.includes("jpg") ? "jpg" : contentType.includes("webp") ? "webp" : "png";
                    const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;
                    const buf = Buffer.from(await imgResp.arrayBuffer());
                    await writeFile2(join9(IMAGE_DIR, filename), buf);
                    img.url = `http://localhost:${port2}/images/${filename}`;
                    console.log(`[ClawRouter] Image downloaded & saved \u2192 ${img.url}`);
                  }
                } catch (downloadErr) {
                  console.warn(
                    `[ClawRouter] Failed to download image, using original URL: ${downloadErr instanceof Error ? downloadErr.message : String(downloadErr)}`
                  );
                }
              }
            }
          }
          const imgActualCost = paymentStore.getStore()?.amountUsd ?? imgCost;
          logUsage({
            timestamp: (/* @__PURE__ */ new Date()).toISOString(),
            model: imgModel,
            tier: "IMAGE",
            cost: imgActualCost,
            baselineCost: imgActualCost,
            savings: 0,
            latencyMs: Date.now() - imgStartTime
          }).catch(() => {
          });
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(result));
        } catch (err) {
          const msg = err instanceof Error ? err.message : String(err);
          console.error(`[ClawRouter] Image generation error: ${msg}`);
          if (!res.headersSent) {
            res.writeHead(502, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "Image generation failed", details: msg }));
          }
        }
        return;
      }
      if (req.url === "/v1/images/image2image" && req.method === "POST") {
        const img2imgStartTime = Date.now();
        const chunks = [];
        for await (const chunk of req) {
          chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
        }
        const rawBody = Buffer.concat(chunks);
        let reqBody;
        let img2imgModel = "openai/gpt-image-1";
        let img2imgCost = 0;
        try {
          const parsed = JSON.parse(rawBody.toString());
          for (const field of ["image", "mask"]) {
            const val = parsed[field];
            if (typeof val !== "string" || !val) continue;
            if (val.startsWith("data:")) {
            } else if (val.startsWith("https://") || val.startsWith("http://")) {
              const imgResp = await fetch(val);
              if (!imgResp.ok)
                throw new Error(`Failed to download ${field} from ${val}: HTTP ${imgResp.status}`);
              const contentType = imgResp.headers.get("content-type") ?? "image/png";
              const buf = Buffer.from(await imgResp.arrayBuffer());
              parsed[field] = `data:${contentType};base64,${buf.toString("base64")}`;
              console.log(
                `[ClawRouter] img2img: downloaded ${field} URL \u2192 data URI (${buf.length} bytes)`
              );
            } else {
              parsed[field] = readImageFileAsDataUri(val);
              console.log(`[ClawRouter] img2img: read ${field} file \u2192 data URI`);
            }
          }
          if (!parsed.model) parsed.model = "openai/gpt-image-1";
          img2imgModel = parsed.model;
          img2imgCost = estimateImageCost(img2imgModel, parsed.size, parsed.n || 1);
          reqBody = JSON.stringify(parsed);
        } catch (parseErr) {
          const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "Invalid request", details: msg }));
          return;
        }
        try {
          const upstream = await payFetch(`${apiBase}/v1/images/image2image`, {
            method: "POST",
            headers: { "content-type": "application/json", "user-agent": USER_AGENT },
            body: reqBody
          });
          const text = await upstream.text();
          if (!upstream.ok) {
            res.writeHead(upstream.status, { "Content-Type": "application/json" });
            res.end(text);
            return;
          }
          let result;
          try {
            result = JSON.parse(text);
          } catch {
            res.writeHead(200, { "Content-Type": "application/json" });
            res.end(text);
            return;
          }
          if (result.data?.length) {
            await mkdir4(IMAGE_DIR, { recursive: true });
            const port2 = server.address()?.port ?? 8402;
            for (const img of result.data) {
              const dataUriMatch = img.url?.match(/^data:(image\/\w+);base64,(.+)$/);
              if (dataUriMatch) {
                const [, mimeType, b64] = dataUriMatch;
                const ext = mimeType === "image/jpeg" ? "jpg" : mimeType.split("/")[1] ?? "png";
                const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;
                await writeFile2(join9(IMAGE_DIR, filename), Buffer.from(b64, "base64"));
                img.url = `http://localhost:${port2}/images/${filename}`;
                console.log(`[ClawRouter] Image saved \u2192 ${img.url}`);
              } else if (img.url?.startsWith("https://") || img.url?.startsWith("http://")) {
                try {
                  const imgResp = await fetch(img.url);
                  if (imgResp.ok) {
                    const contentType = imgResp.headers.get("content-type") ?? "image/png";
                    const ext = contentType.includes("jpeg") || contentType.includes("jpg") ? "jpg" : contentType.includes("webp") ? "webp" : "png";
                    const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;
                    const buf = Buffer.from(await imgResp.arrayBuffer());
                    await writeFile2(join9(IMAGE_DIR, filename), buf);
                    img.url = `http://localhost:${port2}/images/${filename}`;
                    console.log(`[ClawRouter] Image downloaded & saved \u2192 ${img.url}`);
                  }
                } catch (downloadErr) {
                  console.warn(
                    `[ClawRouter] Failed to download image, using original URL: ${downloadErr instanceof Error ? downloadErr.message : String(downloadErr)}`
                  );
                }
              }
            }
          }
          const img2imgActualCost = paymentStore.getStore()?.amountUsd ?? img2imgCost;
          logUsage({
            timestamp: (/* @__PURE__ */ new Date()).toISOString(),
            model: img2imgModel,
            tier: "IMAGE",
            cost: img2imgActualCost,
            baselineCost: img2imgActualCost,
            savings: 0,
            latencyMs: Date.now() - img2imgStartTime
          }).catch(() => {
          });
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(result));
        } catch (err) {
          const msg = err instanceof Error ? err.message : String(err);
          console.error(`[ClawRouter] Image editing error: ${msg}`);
          if (!res.headersSent) {
            res.writeHead(502, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "Image editing failed", details: msg }));
          }
        }
        return;
      }
      if (req.url === "/v1/audio/generations" && req.method === "POST") {
        const audioStartTime = Date.now();
        const chunks = [];
        for await (const chunk of req) {
          chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
        }
        const reqBody = Buffer.concat(chunks);
        let audioModel = "minimax/music-2.5+";
        try {
          const parsed = JSON.parse(reqBody.toString());
          audioModel = parsed.model || audioModel;
        } catch {
        }
        try {
          const upstream = await payFetch(`${apiBase}/v1/audio/generations`, {
            method: "POST",
            headers: { "content-type": "application/json", "user-agent": USER_AGENT },
            body: reqBody
          });
          const text = await upstream.text();
          if (!upstream.ok) {
            res.writeHead(upstream.status, { "Content-Type": "application/json" });
            res.end(text);
            return;
          }
          let result;
          try {
            result = JSON.parse(text);
          } catch {
            res.writeHead(200, { "Content-Type": "application/json" });
            res.end(text);
            return;
          }
          if (result.data?.length) {
            await mkdir4(AUDIO_DIR, { recursive: true });
            const port2 = server.address()?.port ?? 8402;
            for (const track of result.data) {
              if (track.url?.startsWith("https://") || track.url?.startsWith("http://")) {
                try {
                  const audioResp = await fetch(track.url);
                  if (audioResp.ok) {
                    const contentType = audioResp.headers.get("content-type") ?? "audio/mpeg";
                    const ext = contentType.includes("wav") ? "wav" : "mp3";
                    const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;
                    const buf = Buffer.from(await audioResp.arrayBuffer());
                    await writeFile2(join9(AUDIO_DIR, filename), buf);
                    track.url = `http://localhost:${port2}/audio/${filename}`;
                    console.log(`[ClawRouter] Audio saved \u2192 ${track.url}`);
                  }
                } catch (downloadErr) {
                  console.warn(
                    `[ClawRouter] Failed to download audio, using original URL: ${downloadErr instanceof Error ? downloadErr.message : String(downloadErr)}`
                  );
                }
              }
            }
          }
          const audioActualCost = paymentStore.getStore()?.amountUsd ?? 0.15;
          logUsage({
            timestamp: (/* @__PURE__ */ new Date()).toISOString(),
            model: audioModel,
            tier: "AUDIO",
            cost: audioActualCost,
            baselineCost: audioActualCost,
            savings: 0,
            latencyMs: Date.now() - audioStartTime
          }).catch(() => {
          });
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(result));
        } catch (err) {
          const msg = err instanceof Error ? err.message : String(err);
          console.error(`[ClawRouter] Audio generation error: ${msg}`);
          if (!res.headersSent) {
            res.writeHead(502, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "Audio generation failed", details: msg }));
          }
        }
        return;
      }
      if (req.url === "/v1/videos/generations" && req.method === "POST") {
        const videoStartTime = Date.now();
        const chunks = [];
        for await (const chunk of req) {
          chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
        }
        const reqBody = Buffer.concat(chunks);
        let videoModel = "xai/grok-imagine-video";
        let videoDuration;
        let videoHasImageInput = false;
        try {
          const parsed = JSON.parse(reqBody.toString());
          videoModel = parsed.model || videoModel;
          videoDuration = typeof parsed.duration_seconds === "number" ? parsed.duration_seconds : void 0;
          videoHasImageInput = typeof parsed.image_url === "string" && parsed.image_url.length > 0;
        } catch {
        }
        try {
          const submitResp = await payFetch(`${apiBase}/v1/videos/generations`, {
            method: "POST",
            headers: { "content-type": "application/json", "user-agent": USER_AGENT },
            body: reqBody
          });
          const submitText = await submitResp.text();
          if (!submitResp.ok && submitResp.status !== 202) {
            res.writeHead(submitResp.status, { "Content-Type": "application/json" });
            res.end(submitText);
            return;
          }
          let submitResult;
          try {
            submitResult = JSON.parse(submitText);
          } catch {
            res.writeHead(200, { "Content-Type": "application/json" });
            res.end(submitText);
            return;
          }
          let finalResult = submitResult;
          if (submitResult.poll_url && submitResult.id) {
            const apiOrigin = new URL(apiBase).origin;
            const pollUrl = submitResult.poll_url.startsWith("http") ? submitResult.poll_url : `${apiOrigin}${submitResult.poll_url}`;
            console.log(
              `[ClawRouter] Video job submitted (id=${submitResult.id}), polling upstream \u2014 typical 60\u2013180s...`
            );
            const pollDeadline = Date.now() + 3e5;
            const pollInterval = 5e3;
            await new Promise((r) => setTimeout(r, 3e3));
            let pollError;
            while (Date.now() < pollDeadline) {
              const pollResp = await payFetch(pollUrl, {
                method: "GET",
                headers: { "user-agent": USER_AGENT }
              });
              const pollText = await pollResp.text();
              let pollBody = {};
              try {
                pollBody = JSON.parse(pollText);
              } catch {
                pollError = `Non-JSON poll response (${pollResp.status}): ${pollText.slice(0, 200)}`;
                break;
              }
              if (pollResp.status === 202 || pollBody.status === "queued" || pollBody.status === "in_progress") {
                await new Promise((r) => setTimeout(r, pollInterval));
                continue;
              }
              if (pollBody.status === "failed") {
                pollError = pollBody.error ?? "Upstream video generation failed";
                break;
              }
              if (pollResp.ok && pollBody.status === "completed") {
                finalResult = pollBody;
                break;
              }
              if (!pollResp.ok) {
                res.writeHead(pollResp.status, { "Content-Type": "application/json" });
                res.end(pollText);
                return;
              }
              finalResult = pollBody;
              break;
            }
            if (pollError) {
              res.writeHead(502, { "Content-Type": "application/json" });
              res.end(JSON.stringify({ error: "Video generation failed", details: pollError }));
              return;
            }
            if (!finalResult.data) {
              res.writeHead(504, { "Content-Type": "application/json" });
              res.end(
                JSON.stringify({
                  error: "Video generation timed out",
                  details: `Upstream did not complete within 5 minutes (job id=${submitResult.id}). No payment has been settled.`
                })
              );
              return;
            }
          }
          if (finalResult.data?.length) {
            await mkdir4(VIDEO_DIR, { recursive: true });
            const port2 = server.address()?.port ?? 8402;
            for (const clip of finalResult.data) {
              if (clip.url?.startsWith("https://") || clip.url?.startsWith("http://")) {
                try {
                  const videoResp = await fetch(clip.url);
                  if (videoResp.ok) {
                    const contentType = videoResp.headers.get("content-type") ?? "video/mp4";
                    const ext = contentType.includes("webm") ? "webm" : contentType.includes("quicktime") ? "mov" : "mp4";
                    const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}.${ext}`;
                    const buf = Buffer.from(await videoResp.arrayBuffer());
                    await writeFile2(join9(VIDEO_DIR, filename), buf);
                    clip.url = `http://localhost:${port2}/videos/${filename}`;
                    console.log(`[ClawRouter] Video saved \u2192 ${clip.url}`);
                  }
                } catch (downloadErr) {
                  console.warn(
                    `[ClawRouter] Failed to download video, using original URL: ${downloadErr instanceof Error ? downloadErr.message : String(downloadErr)}`
                  );
                }
              }
            }
          }
          const videoActualCost = paymentStore.getStore()?.amountUsd ?? estimateVideoCost(videoModel, videoDuration, videoHasImageInput);
          logUsage({
            timestamp: (/* @__PURE__ */ new Date()).toISOString(),
            model: videoModel,
            tier: "VIDEO",
            cost: videoActualCost,
            baselineCost: videoActualCost,
            savings: 0,
            latencyMs: Date.now() - videoStartTime
          }).catch(() => {
          });
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(finalResult));
        } catch (err) {
          const msg = err instanceof Error ? err.message : String(err);
          console.error(`[ClawRouter] Video generation error: ${msg}`);
          if (!res.headersSent) {
            res.writeHead(502, { "Content-Type": "application/json" });
            res.end(JSON.stringify({ error: "Video generation failed", details: msg }));
          }
        }
        return;
      }
      if (req.url?.match(
        /^\/v1\/(?:partner|pm|exa|modal|stocks|usstock|crypto|fx|commodity|phone|voice|surf)\//
      )) {
        try {
          await proxyPaidApiRequest(
            req,
            res,
            apiBase,
            payFetch,
            () => paymentStore.getStore()?.amountUsd ?? 0
          );
        } catch (err) {
          const error = err instanceof Error ? err : new Error(String(err));
          options.onError?.(error);
          if (!res.headersSent) {
            res.writeHead(502, { "Content-Type": "application/json" });
            res.end(
              JSON.stringify({
                error: { message: `Partner proxy error: ${error.message}`, type: "partner_error" }
              })
            );
          }
        }
        return;
      }
      if (!req.url?.startsWith("/v1")) {
        res.writeHead(404, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "Not found" }));
        return;
      }
      try {
        await proxyRequest(
          req,
          res,
          apiBase,
          payFetch,
          options,
          routerOpts,
          deduplicator,
          balanceMonitor,
          sessionStore,
          responseCache2,
          sessionJournal
        );
      } catch (err) {
        const error = err instanceof Error ? err : new Error(String(err));
        options.onError?.(error);
        if (!res.headersSent) {
          res.writeHead(502, { "Content-Type": "application/json" });
          res.end(
            JSON.stringify({
              error: { message: `Proxy error: ${error.message}`, type: "proxy_error" }
            })
          );
        } else if (!res.writableEnded) {
          res.write(
            `data: ${JSON.stringify({ error: { message: error.message, type: "proxy_error" } })}

`
          );
          res.write("data: [DONE]\n\n");
          res.end();
        }
      }
    });
  });
  const tryListen = (attempt) => {
    return new Promise((resolveAttempt, rejectAttempt) => {
      const onError = async (err) => {
        server.removeListener("error", onError);
        if (err.code === "EADDRINUSE") {
          const existingProxy2 = await checkExistingProxy(listenPort);
          if (existingProxy2) {
            console.log(`[ClawRouter] Existing proxy detected on port ${listenPort}, reusing`);
            rejectAttempt({
              code: "REUSE_EXISTING",
              wallet: existingProxy2.wallet,
              existingChain: existingProxy2.paymentChain
            });
            return;
          }
          if (attempt < PORT_RETRY_ATTEMPTS) {
            console.log(
              `[ClawRouter] Port ${listenPort} in TIME_WAIT, retrying in ${PORT_RETRY_DELAY_MS}ms (attempt ${attempt}/${PORT_RETRY_ATTEMPTS})`
            );
            rejectAttempt({ code: "RETRY", attempt });
            return;
          }
          console.error(
            `[ClawRouter] Port ${listenPort} still in use after ${PORT_RETRY_ATTEMPTS} attempts`
          );
          rejectAttempt(err);
          return;
        }
        rejectAttempt(err);
      };
      server.once("error", onError);
      server.listen(listenPort, "127.0.0.1", () => {
        server.removeListener("error", onError);
        resolveAttempt();
      });
    });
  };
  let lastError;
  for (let attempt = 1; attempt <= PORT_RETRY_ATTEMPTS; attempt++) {
    try {
      await tryListen(attempt);
      break;
    } catch (err) {
      const error = err;
      if (error.code === "REUSE_EXISTING" && error.wallet) {
        if (error.existingChain && error.existingChain !== paymentChain) {
          throw new Error(
            `Existing proxy on port ${listenPort} is using ${error.existingChain} but ${paymentChain} was requested. Stop the existing proxy first or use a different port.`,
            { cause: err }
          );
        }
        const baseUrl2 = `http://127.0.0.1:${listenPort}`;
        options.onReady?.(listenPort);
        return {
          port: listenPort,
          baseUrl: baseUrl2,
          walletAddress: error.wallet,
          balanceMonitor,
          close: async () => {
          }
        };
      }
      if (error.code === "RETRY") {
        await new Promise((r) => setTimeout(r, PORT_RETRY_DELAY_MS));
        continue;
      }
      lastError = err;
      break;
    }
  }
  if (lastError) {
    throw lastError;
  }
  const addr = server.address();
  const port = addr.port;
  const baseUrl = `http://127.0.0.1:${port}`;
  options.onReady?.(port);
  checkForUpdates();
  server.on("error", (err) => {
    console.error(`[ClawRouter] Server runtime error: ${err.message}`);
    options.onError?.(err);
  });
  server.on("clientError", (err, socket) => {
    console.error(`[ClawRouter] Client error: ${err.message}`);
    if (socket.writable && !socket.destroyed) {
      socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
    }
  });
  server.on("connection", (socket) => {
    connections.add(socket);
    socket.setTimeout(3e5);
    socket.on("timeout", () => {
      console.error(`[ClawRouter] Socket timeout, destroying connection`);
      socket.destroy();
    });
    socket.on("end", () => {
    });
    socket.on("error", (err) => {
      console.error(`[ClawRouter] Socket error: ${err.message}`);
    });
    socket.on("close", () => {
      connections.delete(socket);
    });
  });
  return {
    port,
    baseUrl,
    walletAddress: account.address,
    solanaAddress,
    balanceMonitor,
    close: () => new Promise((res, rej) => {
      const timeout = setTimeout(() => {
        rej(new Error("[ClawRouter] Close timeout after 4s"));
      }, 4e3);
      sessionStore.close();
      for (const socket of connections) {
        socket.destroy();
      }
      connections.clear();
      server.close((err) => {
        clearTimeout(timeout);
        if (err) {
          rej(err);
        } else {
          res();
        }
      });
    })
  };
}
function isDegenerateCompletion(bodyBuf) {
  try {
    const parsed = JSON.parse(bodyBuf.toString());
    const choice = parsed.choices?.[0];
    const finishReason = choice?.finish_reason;
    if (finishReason !== "length") return false;
    const content = choice?.message?.content ?? "";
    if (content.length < 80) return false;
    const tail = content.slice(-80);
    const tailChars = [...tail];
    const firstChar = tailChars[0];
    if (!/[^\p{L}\p{N}\s]/u.test(firstChar)) return false;
    const sameCount = tailChars.filter((c) => c === firstChar).length;
    return sameCount >= 60;
  } catch {
    return false;
  }
}
async function tryModelRequest(upstreamUrl, method, headers, body, modelId, maxTokens, payFetch, balanceMonitor, signal) {
  let requestBody = body;
  try {
    const parsed = JSON.parse(body.toString());
    parsed.model = toUpstreamModelId(modelId);
    if (Array.isArray(parsed.messages)) {
      parsed.messages = normalizeMessageRoles(parsed.messages);
    }
    if (Array.isArray(parsed.messages)) {
      parsed.messages = debrandSystemMessages(parsed.messages, modelId);
    }
    if (Array.isArray(parsed.messages)) {
      const truncationResult = truncateMessages(parsed.messages);
      parsed.messages = truncationResult.messages;
    }
    if (Array.isArray(parsed.messages)) {
      parsed.messages = sanitizeToolIds(parsed.messages);
    }
    if (isGoogleModel(modelId) && Array.isArray(parsed.messages)) {
      parsed.messages = normalizeMessagesForGoogle(parsed.messages);
    }
    const hasThinkingEnabled = !!(parsed.thinking || parsed.extended_thinking || isReasoningModel(modelId));
    if (hasThinkingEnabled && Array.isArray(parsed.messages)) {
      parsed.messages = normalizeMessagesForThinking(parsed.messages);
    }
    requestBody = Buffer.from(JSON.stringify(parsed));
  } catch {
  }
  try {
    const response = await payFetch(upstreamUrl, {
      method,
      headers,
      body: requestBody.length > 0 ? new Uint8Array(requestBody) : void 0,
      signal
    });
    if (response.status !== 200) {
      const errorBodyChunks = await readBodyWithTimeout(response.body, ERROR_BODY_READ_TIMEOUT_MS);
      const errorBody = Buffer.concat(errorBodyChunks).toString();
      const category = categorizeError(response.status, errorBody);
      return {
        success: false,
        errorBody,
        errorStatus: response.status,
        isProviderError: category !== null,
        errorCategory: category ?? void 0
      };
    }
    const contentType = response.headers.get("content-type") || "";
    if (contentType.includes("json") || contentType.includes("text")) {
      try {
        const clonedChunks = await readBodyWithTimeout(
          response.clone().body,
          ERROR_BODY_READ_TIMEOUT_MS
        );
        const responseBody = Buffer.concat(clonedChunks).toString();
        const degradedReason = detectDegradedSuccessResponse(responseBody);
        if (degradedReason) {
          return {
            success: false,
            errorBody: degradedReason,
            errorStatus: 503,
            isProviderError: true
          };
        }
      } catch {
      }
    }
    return { success: true, response };
  } catch (err) {
    const errorMsg = err instanceof Error ? err.message : String(err);
    return {
      success: false,
      errorBody: errorMsg,
      errorStatus: 500,
      isProviderError: true
      // Network errors are retryable
    };
  }
}
async function proxyRequest(req, res, apiBase, payFetch, options, routerOpts, deduplicator, balanceMonitor, sessionStore, responseCache2, sessionJournal) {
  const startTime = Date.now();
  const upstreamUrl = `${apiBase}${req.url}`;
  const bodyChunks = [];
  for await (const chunk of req) {
    bodyChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
  }
  let body = Buffer.concat(bodyChunks);
  const originalContextSizeKB = Math.ceil(body.length / 1024);
  const debugMode = req.headers["x-clawrouter-debug"] !== "false";
  let routingDecision;
  let hasTools = false;
  let hasVision = false;
  let isStreaming = false;
  let modelId = "";
  let maxTokens = 4096;
  let routingProfile = null;
  let stickyExplicitModel;
  let balanceFallbackNotice;
  let budgetDowngradeNotice;
  let budgetDowngradeHeaderMode;
  let accumulatedContent = "";
  let responseInputTokens;
  let responseOutputTokens;
  let requestHadError = false;
  let requestSummaryForStore = "";
  const isChatCompletion = req.url?.includes("/chat/completions");
  const sessionId = getSessionId(req.headers);
  let effectiveSessionId = sessionId;
  if (isChatCompletion && body.length > 0) {
    try {
      const parsed = JSON.parse(body.toString());
      isStreaming = parsed.stream === true;
      modelId = parsed.model || "";
      maxTokens = parsed.max_tokens || 4096;
      let bodyModified = false;
      const parsedMessages = Array.isArray(parsed.messages) ? parsed.messages : [];
      const lastUserMsg = [...parsedMessages].reverse().find((m) => m.role === "user");
      {
        const c = lastUserMsg?.content;
        let promptText = "";
        if (typeof c === "string") {
          promptText = c;
        } else if (Array.isArray(c)) {
          promptText = c.filter((b) => typeof b === "object" && b !== null && b.type === "text").map((b) => b.text ?? "").join(" ").trim();
        }
        requestSummaryForStore = summarizeRequest(promptText);
      }
      hasTools = Array.isArray(parsed.tools) && parsed.tools.length > 0;
      const rawLastContent = lastUserMsg?.content;
      const lastContent = typeof rawLastContent === "string" ? rawLastContent : Array.isArray(rawLastContent) ? rawLastContent.filter((b) => b.type === "text").map((b) => b.text ?? "").join(" ") : "";
      if (sessionId && parsedMessages.length > 0) {
        const messages = parsedMessages;
        if (sessionJournal.needsContext(lastContent)) {
          const journalText = sessionJournal.format(sessionId);
          if (journalText) {
            const sysIdx = messages.findIndex((m) => m.role === "system");
            if (sysIdx >= 0 && typeof messages[sysIdx].content === "string") {
              messages[sysIdx] = {
                ...messages[sysIdx],
                content: journalText + "\n\n" + messages[sysIdx].content
              };
            } else {
              messages.unshift({ role: "system", content: journalText });
            }
            parsed.messages = messages;
            bodyModified = true;
            console.log(
              `[ClawRouter] Injected session journal (${journalText.length} chars) for session ${sessionId.slice(0, 8)}...`
            );
          }
        }
      }
      if (lastContent.startsWith("/debug")) {
        const debugPrompt = lastContent.slice("/debug".length).trim() || "hello";
        const messages = parsed.messages;
        const systemMsg = messages?.find((m) => m.role === "system");
        const systemPrompt = typeof systemMsg?.content === "string" ? systemMsg.content : void 0;
        const fullText = `${systemPrompt ?? ""} ${debugPrompt}`;
        const estimatedTokens = Math.ceil(fullText.length / 4);
        const normalizedModel2 = typeof parsed.model === "string" ? parsed.model.trim().toLowerCase() : "";
        const profileName = normalizedModel2.replace("blockrun/", "");
        const debugProfile = ["eco", "auto", "premium"].includes(profileName) ? profileName : "auto";
        const scoring = classifyByRules(
          debugPrompt,
          systemPrompt,
          estimatedTokens,
          DEFAULT_ROUTING_CONFIG.scoring
        );
        const debugRouting = route(debugPrompt, systemPrompt, maxTokens, {
          ...routerOpts,
          routingProfile: debugProfile
        });
        const dimLines = (scoring.dimensions ?? []).map((d) => {
          const nameStr = (d.name + ":").padEnd(24);
          const scoreStr = d.score.toFixed(2).padStart(6);
          const sigStr = d.signal ? `  [${d.signal}]` : "";
          return `  ${nameStr}${scoreStr}${sigStr}`;
        }).join("\n");
        const sess = sessionId ? sessionStore.getSession(sessionId) : void 0;
        const sessLine = sess ? `Session: ${sessionId.slice(0, 8)}... \u2192 pinned: ${sess.model} (${sess.requestCount} requests)` : sessionId ? `Session: ${sessionId.slice(0, 8)}... \u2192 no pinned model` : "Session: none";
        const { simpleMedium, mediumComplex, complexReasoning } = DEFAULT_ROUTING_CONFIG.scoring.tierBoundaries;
        const debugText = [
          "ClawRouter Debug",
          "",
          `Profile: ${debugProfile} | Tier: ${debugRouting.tier} | Model: ${debugRouting.model}`,
          `Confidence: ${debugRouting.confidence.toFixed(2)} | Cost: $${debugRouting.costEstimate.toFixed(4)} | Savings: ${(debugRouting.savings * 100).toFixed(0)}%`,
          `Reasoning: ${debugRouting.reasoning}`,
          "",
          `Scoring (weighted: ${scoring.score.toFixed(3)})`,
          dimLines,
          "",
          `Tier Boundaries: SIMPLE <${simpleMedium.toFixed(2)} | MEDIUM <${mediumComplex.toFixed(2)} | COMPLEX <${complexReasoning.toFixed(2)} | REASONING >=${complexReasoning.toFixed(2)}`,
          "",
          sessLine
        ].join("\n");
        const completionId = `chatcmpl-debug-${Date.now()}`;
        const timestamp = Math.floor(Date.now() / 1e3);
        const syntheticResponse = {
          id: completionId,
          object: "chat.completion",
          created: timestamp,
          model: "clawrouter/debug",
          choices: [
            {
              index: 0,
              message: { role: "assistant", content: debugText },
              finish_reason: "stop"
            }
          ],
          usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 }
        };
        if (isStreaming) {
          res.writeHead(200, {
            "Content-Type": "text/event-stream",
            "Cache-Control": "no-cache",
            Connection: "keep-alive"
          });
          const sseChunk = {
            id: completionId,
            object: "chat.completion.chunk",
            created: timestamp,
            model: "clawrouter/debug",
            choices: [
              {
                index: 0,
                delta: { role: "assistant", content: debugText },
                finish_reason: null
              }
            ]
          };
          const sseDone = {
            id: completionId,
            object: "chat.completion.chunk",
            created: timestamp,
            model: "clawrouter/debug",
            choices: [{ index: 0, delta: {}, finish_reason: "stop" }]
          };
          res.write(`data: ${JSON.stringify(sseChunk)}

`);
          res.write(`data: ${JSON.stringify(sseDone)}

`);
          res.write("data: [DONE]\n\n");
          res.end();
        } else {
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(syntheticResponse));
        }
        console.log(`[ClawRouter] /debug command \u2192 ${debugRouting.tier} | ${debugRouting.model}`);
        return;
      }
      const imagegenMatch = lastContent.startsWith("/cr-imagegen") ? "/cr-imagegen" : lastContent.startsWith("/imagegen") ? "/imagegen" : null;
      if (imagegenMatch) {
        const imageArgs = lastContent.slice(imagegenMatch.length).trim();
        let imageModel = "google/nano-banana";
        let imageSize = "1024x1024";
        let imagePrompt = imageArgs;
        const modelMatch = imageArgs.match(/--model\s+(\S+)/);
        if (modelMatch) {
          const raw = modelMatch[1];
          const IMAGE_MODEL_ALIASES = {
            "dall-e-3": "openai/dall-e-3",
            dalle3: "openai/dall-e-3",
            dalle: "openai/dall-e-3",
            "gpt-image": "openai/gpt-image-1",
            "gpt-image-1": "openai/gpt-image-1",
            flux: "black-forest/flux-1.1-pro",
            "flux-pro": "black-forest/flux-1.1-pro",
            banana: "google/nano-banana",
            "nano-banana": "google/nano-banana",
            "banana-pro": "google/nano-banana-pro",
            "nano-banana-pro": "google/nano-banana-pro"
          };
          imageModel = IMAGE_MODEL_ALIASES[raw] ?? raw;
          imagePrompt = imagePrompt.replace(/--model\s+\S+/, "").trim();
        }
        const sizeMatch = imageArgs.match(/--size\s+(\d+x\d+)/);
        if (sizeMatch) {
          imageSize = sizeMatch[1];
          imagePrompt = imagePrompt.replace(/--size\s+\d+x\d+/, "").trim();
        }
        if (!imagePrompt) {
          const errorText = [
            "Usage: /cr-imagegen <prompt>",
            "",
            "Options:",
            "  --model <model>  Model to use (default: nano-banana)",
            "  --size <WxH>     Image size (default: 1024x1024)",
            "",
            "Models:",
            "  nano-banana       Google Gemini Flash \u2014 $0.05/image",
            "  banana-pro        Google Gemini Pro \u2014 $0.10/image (up to 4K)",
            "  dall-e-3          OpenAI DALL-E 3 \u2014 $0.04/image",
            "  gpt-image         OpenAI GPT Image 1 \u2014 $0.02/image",
            "  flux              Black Forest Flux 1.1 Pro \u2014 $0.04/image",
            "",
            "Examples:",
            "  /cr-imagegen a cat wearing sunglasses",
            "  /cr-imagegen --model dall-e-3 a futuristic city at sunset",
            "  /cr-imagegen --model banana-pro --size 2048x2048 mountain landscape",
            "",
            "Note: `/imagegen` is still accepted in chat for backward compatibility."
          ].join("\n");
          const completionId = `chatcmpl-image-${Date.now()}`;
          const timestamp = Math.floor(Date.now() / 1e3);
          if (isStreaming) {
            res.writeHead(200, {
              "Content-Type": "text/event-stream",
              "Cache-Control": "no-cache",
              Connection: "keep-alive"
            });
            res.write(
              `data: ${JSON.stringify({ id: completionId, object: "chat.completion.chunk", created: timestamp, model: "clawrouter/image", choices: [{ index: 0, delta: { role: "assistant", content: errorText }, finish_reason: null }] })}

`
            );
            res.write(
              `data: ${JSON.stringify({ id: completionId, object: "chat.completion.chunk", created: timestamp, model: "clawrouter/image", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] })}

`
            );
            res.write("data: [DONE]\n\n");
            res.end();
          } else {
            res.writeHead(200, { "Content-Type": "application/json" });
            res.end(
              JSON.stringify({
                id: completionId,
                object: "chat.completion",
                created: timestamp,
                model: "clawrouter/image",
                choices: [
                  {
                    index: 0,
                    message: { role: "assistant", content: errorText },
                    finish_reason: "stop"
                  }
                ],
                usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 }
              })
            );
          }
          console.log(`[ClawRouter] /imagegen command \u2192 showing usage help`);
          return;
        }
        console.log(
          `[ClawRouter] /imagegen command \u2192 ${imageModel} (${imageSize}): ${imagePrompt.slice(0, 80)}...`
        );
        try {
          const imageUpstreamUrl = `${apiBase}/v1/images/generations`;
          const imageBody = JSON.stringify({
            model: imageModel,
            prompt: imagePrompt,
            size: imageSize,
            n: 1
          });
          const imageResponse = await payFetch(imageUpstreamUrl, {
            method: "POST",
            headers: { "content-type": "application/json", "user-agent": USER_AGENT },
            body: imageBody
          });
          const imageResult = await imageResponse.json();
          let responseText;
          if (!imageResponse.ok || imageResult.error) {
            const errMsg = typeof imageResult.error === "string" ? imageResult.error : imageResult.error?.message ?? `HTTP ${imageResponse.status}`;
            responseText = `Image generation failed: ${errMsg}`;
            console.log(`[ClawRouter] /imagegen error: ${errMsg}`);
          } else {
            const images = imageResult.data ?? [];
            if (images.length === 0) {
              responseText = "Image generation returned no results.";
            } else {
              const lines = [];
              for (const img of images) {
                if (img.url) {
                  if (img.url.startsWith("data:")) {
                    try {
                      const hostedUrl = await uploadDataUriToHost(img.url);
                      lines.push(hostedUrl);
                    } catch (uploadErr) {
                      console.error(
                        `[ClawRouter] /imagegen: failed to upload data URI: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`
                      );
                      lines.push(
                        "Image generated but upload failed. Try again or use --model dall-e-3."
                      );
                    }
                  } else {
                    lines.push(img.url);
                  }
                }
                if (img.revised_prompt) lines.push(`Revised prompt: ${img.revised_prompt}`);
              }
              lines.push("", `Model: ${imageModel} | Size: ${imageSize}`);
              responseText = lines.join("\n");
            }
            console.log(`[ClawRouter] /imagegen success: ${images.length} image(s) generated`);
            const imagegenActualCost = paymentStore.getStore()?.amountUsd ?? estimateImageCost(imageModel, imageSize, 1);
            logUsage({
              timestamp: (/* @__PURE__ */ new Date()).toISOString(),
              model: imageModel,
              tier: "IMAGE",
              cost: imagegenActualCost,
              baselineCost: imagegenActualCost,
              savings: 0,
              latencyMs: 0
            }).catch(() => {
            });
          }
          const completionId = `chatcmpl-image-${Date.now()}`;
          const timestamp = Math.floor(Date.now() / 1e3);
          if (isStreaming) {
            res.writeHead(200, {
              "Content-Type": "text/event-stream",
              "Cache-Control": "no-cache",
              Connection: "keep-alive"
            });
            res.write(
              `data: ${JSON.stringify({ id: completionId, object: "chat.completion.chunk", created: timestamp, model: "clawrouter/image", choices: [{ index: 0, delta: { role: "assistant", content: responseText }, finish_reason: null }] })}

`
            );
            res.write(
              `data: ${JSON.stringify({ id: completionId, object: "chat.completion.chunk", created: timestamp, model: "clawrouter/image", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] })}

`
            );
            res.write("data: [DONE]\n\n");
            res.end();
          } else {
            res.writeHead(200, { "Content-Type": "application/json" });
            res.end(
              JSON.stringify({
                id: completionId,
                object: "chat.completion",
                created: timestamp,
                model: "clawrouter/image",
                choices: [
                  {
                    index: 0,
                    message: { role: "assistant", content: responseText },
                    finish_reason: "stop"
                  }
                ],
                usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 }
              })
            );
          }
        } catch (err) {
          const errMsg = err instanceof Error ? err.message : String(err);
          console.error(`[ClawRouter] /imagegen error: ${errMsg}`);
          if (!res.headersSent) {
            res.writeHead(500, { "Content-Type": "application/json" });
            res.end(
              JSON.stringify({
                error: { message: `Image generation failed: ${errMsg}`, type: "image_error" }
              })
            );
          }
        }
        return;
      }
      if (lastContent.startsWith("/img2img")) {
        const imgArgs = lastContent.slice("/img2img".length).trim();
        let img2imgModel = "openai/gpt-image-1";
        let img2imgSize = "1024x1024";
        let imagePath = null;
        let maskPath = null;
        let img2imgPrompt = imgArgs;
        const imageMatch = imgArgs.match(/--image\s+(\S+)/);
        if (imageMatch) {
          imagePath = imageMatch[1];
          img2imgPrompt = img2imgPrompt.replace(/--image\s+\S+/, "").trim();
        }
        const maskMatch = imgArgs.match(/--mask\s+(\S+)/);
        if (maskMatch) {
          maskPath = maskMatch[1];
          img2imgPrompt = img2imgPrompt.replace(/--mask\s+\S+/, "").trim();
        }
        const img2imgSizeMatch = imgArgs.match(/--size\s+(\d+x\d+)/);
        if (img2imgSizeMatch) {
          img2imgSize = img2imgSizeMatch[1];
          img2imgPrompt = img2imgPrompt.replace(/--size\s+\d+x\d+/, "").trim();
        }
        const img2imgModelMatch = imgArgs.match(/--model\s+(\S+)/);
        if (img2imgModelMatch) {
          const raw = img2imgModelMatch[1];
          const IMG2IMG_ALIASES = {
            "gpt-image": "openai/gpt-image-1",
            "gpt-image-1": "openai/gpt-image-1"
          };
          img2imgModel = IMG2IMG_ALIASES[raw] ?? raw;
          img2imgPrompt = img2imgPrompt.replace(/--model\s+\S+/, "").trim();
        }
        const usageText = [
          "Usage: /img2img --image <path> <prompt>",
          "",
          "Options:",
          "  --image <path>   Source image path (required)",
          "  --mask <path>    Mask image path (optional, white = area to edit)",
          "  --model <model>  Model (default: gpt-image-1)",
          "  --size <WxH>     Output size (default: 1024x1024)",
          "",
          "Models:",
          "  gpt-image-1      OpenAI GPT Image 1 \u2014 $0.02/image",
          "",
          "Examples:",
          "  /img2img --image ~/photo.png change background to starry sky",
          "  /img2img --image ./cat.jpg --mask ./mask.png remove the background",
          "  /img2img --image /tmp/portrait.png --size 1536x1024 add a hat"
        ].join("\n");
        const sendImg2ImgText = (text) => {
          const completionId = `chatcmpl-img2img-${Date.now()}`;
          const timestamp = Math.floor(Date.now() / 1e3);
          if (isStreaming) {
            res.writeHead(200, {
              "Content-Type": "text/event-stream",
              "Cache-Control": "no-cache",
              Connection: "keep-alive"
            });
            res.write(
              `data: ${JSON.stringify({ id: completionId, object: "chat.completion.chunk", created: timestamp, model: "clawrouter/img2img", choices: [{ index: 0, delta: { role: "assistant", content: text }, finish_reason: null }] })}

`
            );
            res.write(
              `data: ${JSON.stringify({ id: completionId, object: "chat.completion.chunk", created: timestamp, model: "clawrouter/img2img", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] })}

`
            );
            res.write("data: [DONE]\n\n");
            res.end();
          } else {
            res.writeHead(200, { "Content-Type": "application/json" });
            res.end(
              JSON.stringify({
                id: completionId,
                object: "chat.completion",
                created: timestamp,
                model: "clawrouter/img2img",
                choices: [
                  {
                    index: 0,
                    message: { role: "assistant", content: text },
                    finish_reason: "stop"
                  }
                ],
                usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 }
              })
            );
          }
        };
        if (!imagePath || !img2imgPrompt) {
          sendImg2ImgText(usageText);
          return;
        }
        let imageDataUri;
        let maskDataUri;
        try {
          imageDataUri = readImageFileAsDataUri(imagePath);
          if (maskPath) maskDataUri = readImageFileAsDataUri(maskPath);
        } catch (fileErr) {
          const fileErrMsg = fileErr instanceof Error ? fileErr.message : String(fileErr);
          sendImg2ImgText(`Failed to read image file: ${fileErrMsg}`);
          return;
        }
        console.log(
          `[ClawRouter] /img2img \u2192 ${img2imgModel} (${img2imgSize}): ${img2imgPrompt.slice(0, 80)}`
        );
        try {
          const img2imgBody = JSON.stringify({
            model: img2imgModel,
            prompt: img2imgPrompt,
            image: imageDataUri,
            ...maskDataUri ? { mask: maskDataUri } : {},
            size: img2imgSize,
            n: 1
          });
          const img2imgResponse = await payFetch(`${apiBase}/v1/images/image2image`, {
            method: "POST",
            headers: { "content-type": "application/json", "user-agent": USER_AGENT },
            body: img2imgBody
          });
          const img2imgResult = await img2imgResponse.json();
          let responseText;
          if (!img2imgResponse.ok || img2imgResult.error) {
            const errMsg = typeof img2imgResult.error === "string" ? img2imgResult.error : img2imgResult.error?.message ?? `HTTP ${img2imgResponse.status}`;
            responseText = `Image editing failed: ${errMsg}`;
            console.log(`[ClawRouter] /img2img error: ${errMsg}`);
          } else {
            const images = img2imgResult.data ?? [];
            if (images.length === 0) {
              responseText = "Image editing returned no results.";
            } else {
              const lines = [];
              for (const img of images) {
                if (img.url) {
                  if (img.url.startsWith("data:")) {
                    try {
                      const hostedUrl = await uploadDataUriToHost(img.url);
                      lines.push(hostedUrl);
                    } catch (uploadErr) {
                      console.error(
                        `[ClawRouter] /img2img: failed to upload data URI: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`
                      );
                      lines.push("Image edited but upload failed. Try again.");
                    }
                  } else {
                    lines.push(img.url);
                  }
                }
                if (img.revised_prompt) lines.push(`Revised prompt: ${img.revised_prompt}`);
              }
              lines.push("", `Model: ${img2imgModel} | Size: ${img2imgSize}`);
              responseText = lines.join("\n");
            }
            console.log(`[ClawRouter] /img2img success: ${images.length} image(s)`);
            const img2imgActualCost2 = paymentStore.getStore()?.amountUsd ?? estimateImageCost(img2imgModel, img2imgSize, 1);
            logUsage({
              timestamp: (/* @__PURE__ */ new Date()).toISOString(),
              model: img2imgModel,
              tier: "IMAGE",
              cost: img2imgActualCost2,
              baselineCost: img2imgActualCost2,
              savings: 0,
              latencyMs: 0
            }).catch(() => {
            });
          }
          sendImg2ImgText(responseText);
        } catch (err) {
          const errMsg = err instanceof Error ? err.message : String(err);
          console.error(`[ClawRouter] /img2img error: ${errMsg}`);
          if (!res.headersSent) {
            res.writeHead(500, { "Content-Type": "application/json" });
            res.end(
              JSON.stringify({
                error: { message: `Image editing failed: ${errMsg}`, type: "img2img_error" }
              })
            );
          }
        }
        return;
      }
      if (parsed.stream === true) {
        parsed.stream = false;
        bodyModified = true;
      }
      const normalizedModel = typeof parsed.model === "string" ? parsed.model.trim().toLowerCase() : "";
      const resolvedModel = resolveModelAlias(normalizedModel);
      const wasAlias = resolvedModel !== normalizedModel;
      const isRoutingProfile = ROUTING_PROFILES.has(normalizedModel) || ROUTING_PROFILES.has(resolvedModel);
      if (isRoutingProfile) {
        const profileName = resolvedModel.replace("blockrun/", "");
        routingProfile = profileName;
      }
      console.log(
        `[ClawRouter] Received model: "${parsed.model}" -> normalized: "${normalizedModel}"${wasAlias ? ` -> alias: "${resolvedModel}"` : ""}${routingProfile ? `, profile: ${routingProfile}` : ""}`
      );
      if (!isRoutingProfile) {
        if (parsed.model !== resolvedModel) {
          parsed.model = resolvedModel;
          bodyModified = true;
        }
        modelId = resolvedModel;
        const explicitPinSessionId = getSessionId(req.headers) ?? deriveSessionId(parsedMessages);
        if (explicitPinSessionId) {
          sessionStore.setSession(explicitPinSessionId, resolvedModel, "MEDIUM", true);
          console.log(
            `[ClawRouter] Session ${explicitPinSessionId.slice(0, 8)}... user-explicit pin set: ${resolvedModel}`
          );
        }
      }
      if (isRoutingProfile) {
        {
          effectiveSessionId = getSessionId(req.headers) ?? deriveSessionId(parsedMessages);
          const existingSession = effectiveSessionId ? sessionStore.getSession(effectiveSessionId) : void 0;
          const rawPrompt = lastUserMsg?.content;
          const prompt = typeof rawPrompt === "string" ? rawPrompt : Array.isArray(rawPrompt) ? rawPrompt.filter((b) => b.type === "text").map((b) => b.text ?? "").join(" ") : "";
          const systemMsg = parsedMessages.find((m) => m.role === "system");
          const systemPrompt = typeof systemMsg?.content === "string" ? systemMsg.content : void 0;
          const tools = parsed.tools;
          hasTools = Array.isArray(tools) && tools.length > 0;
          if (hasTools && tools) {
            console.log(`[ClawRouter] Tools detected (${tools.length}), forcing agentic tiers`);
          }
          hasVision = parsedMessages.some((m) => {
            if (Array.isArray(m.content)) {
              return m.content.some((p) => p.type === "image_url");
            }
            return false;
          });
          if (hasVision) {
            console.log(`[ClawRouter] Vision content detected, filtering to vision-capable models`);
          }
          routingDecision = route(prompt, systemPrompt, maxTokens, {
            ...routerOpts,
            routingProfile: routingProfile ?? void 0,
            hasTools
          });
          if (hasTools && routingDecision.tier === "SIMPLE") {
            console.log(
              `[ClawRouter] SIMPLE+tools: keeping agentic model ${routingDecision.model} (tools need reliable function-call support)`
            );
          }
          if (existingSession) {
            if (existingSession.userExplicit) {
              stickyExplicitModel = existingSession.model;
              console.log(
                `[ClawRouter] Session ${effectiveSessionId?.slice(0, 8)}... user-explicit pin: ${existingSession.model} (overriding auto-routed ${routingDecision.tier} \u2192 ${routingDecision.model})`
              );
              parsed.model = existingSession.model;
              modelId = existingSession.model;
              bodyModified = true;
              sessionStore.touchSession(effectiveSessionId);
              routingDecision = {
                ...routingDecision,
                model: existingSession.model,
                tier: existingSession.tier
              };
            } else {
              const tierRank = {
                SIMPLE: 0,
                MEDIUM: 1,
                COMPLEX: 2,
                REASONING: 3
              };
              const existingRank = tierRank[existingSession.tier] ?? 0;
              const newRank = tierRank[routingDecision.tier] ?? 0;
              if (newRank > existingRank) {
                console.log(
                  `[ClawRouter] Session ${effectiveSessionId?.slice(0, 8)}... upgrading: ${existingSession.tier} \u2192 ${routingDecision.tier} (${routingDecision.model})`
                );
                parsed.model = routingDecision.model;
                modelId = routingDecision.model;
                bodyModified = true;
                if (effectiveSessionId) {
                  sessionStore.setSession(
                    effectiveSessionId,
                    routingDecision.model,
                    routingDecision.tier
                  );
                }
              } else if (routingDecision.tier === "SIMPLE") {
                console.log(
                  `[ClawRouter] Session ${effectiveSessionId?.slice(0, 8)}... SIMPLE follow-up, using cheap model: ${routingDecision.model} (bypassing pinned ${existingSession.tier})`
                );
                parsed.model = routingDecision.model;
                modelId = routingDecision.model;
                bodyModified = true;
                sessionStore.touchSession(effectiveSessionId);
              } else {
                console.log(
                  `[ClawRouter] Session ${effectiveSessionId?.slice(0, 8)}... keeping pinned model: ${existingSession.model} (${existingSession.tier} >= ${routingDecision.tier})`
                );
                parsed.model = existingSession.model;
                modelId = existingSession.model;
                bodyModified = true;
                sessionStore.touchSession(effectiveSessionId);
                routingDecision = {
                  ...routingDecision,
                  model: existingSession.model,
                  tier: existingSession.tier
                };
              }
              const lastAssistantMsg = [...parsedMessages].reverse().find((m) => m.role === "assistant");
              const assistantToolCalls = lastAssistantMsg?.tool_calls;
              const toolCallNames = Array.isArray(assistantToolCalls) ? assistantToolCalls.map((tc) => tc.function?.name).filter((n) => Boolean(n)) : void 0;
              const contentHash = hashRequestContent(prompt, toolCallNames);
              const shouldEscalate = sessionStore.recordRequestHash(
                effectiveSessionId,
                contentHash
              );
              if (shouldEscalate) {
                const activeTierConfigs = routingDecision.tierConfigs ?? routerOpts.config.tiers;
                const escalation = sessionStore.escalateSession(
                  effectiveSessionId,
                  activeTierConfigs
                );
                if (escalation) {
                  console.log(
                    `[ClawRouter] \u26A1 3-strike escalation: ${existingSession.model} \u2192 ${escalation.model} (${existingSession.tier} \u2192 ${escalation.tier})`
                  );
                  parsed.model = escalation.model;
                  modelId = escalation.model;
                  routingDecision = {
                    ...routingDecision,
                    model: escalation.model,
                    tier: escalation.tier
                  };
                }
              }
            }
          } else {
            parsed.model = routingDecision.model;
            modelId = routingDecision.model;
            bodyModified = true;
            if (effectiveSessionId) {
              sessionStore.setSession(
                effectiveSessionId,
                routingDecision.model,
                routingDecision.tier
              );
              console.log(
                `[ClawRouter] Session ${effectiveSessionId.slice(0, 8)}... pinned to model: ${routingDecision.model}`
              );
            }
          }
          options.onRouted?.(routingDecision);
        }
      }
      if (!effectiveSessionId && parsedMessages.length > 0) {
        effectiveSessionId = deriveSessionId(parsedMessages);
      }
      if (bodyModified) {
        if (parsed.model && typeof parsed.model === "string") {
          parsed.model = toUpstreamModelId(parsed.model);
        }
        body = Buffer.from(JSON.stringify(parsed));
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : String(err);
      console.error(`[ClawRouter] Routing error: ${errorMsg}`);
      console.error(`[ClawRouter] Need help? Run: npx @blockrun/clawrouter doctor`);
      options.onError?.(new Error(`Routing failed: ${errorMsg}`));
    }
  }
  const autoCompress = options.autoCompressRequests ?? true;
  const compressionThreshold = options.compressionThresholdKB ?? 180;
  const requestSizeKB = Math.ceil(body.length / 1024);
  if (autoCompress && requestSizeKB > compressionThreshold) {
    try {
      console.log(
        `[ClawRouter] Request size ${requestSizeKB}KB exceeds threshold ${compressionThreshold}KB, applying compression...`
      );
      const parsed = JSON.parse(body.toString());
      if (parsed.messages && parsed.messages.length > 0 && shouldCompress(parsed.messages)) {
        const compressionResult = await compressContext(parsed.messages, {
          enabled: true,
          preserveRaw: false,
          // Don't need originals in proxy
          layers: {
            deduplication: true,
            // Safe: removes duplicate messages
            whitespace: true,
            // Safe: normalizes whitespace
            dictionary: false,
            // Disabled: requires model to understand codebook
            paths: false,
            // Disabled: requires model to understand path codes
            jsonCompact: true,
            // Safe: just removes JSON whitespace
            observation: false,
            // Disabled: may lose important context
            dynamicCodebook: false
            // Disabled: requires model to understand codes
          },
          dictionary: {
            maxEntries: 50,
            minPhraseLength: 15,
            includeCodebookHeader: false
          }
        });
        const compressedSizeKB = Math.ceil(compressionResult.compressedChars / 1024);
        const savings = ((requestSizeKB - compressedSizeKB) / requestSizeKB * 100).toFixed(1);
        console.log(
          `[ClawRouter] Compressed ${requestSizeKB}KB \u2192 ${compressedSizeKB}KB (${savings}% reduction)`
        );
        parsed.messages = compressionResult.messages;
        body = Buffer.from(JSON.stringify(parsed));
      }
    } catch (err) {
      console.warn(
        `[ClawRouter] Compression failed: ${err instanceof Error ? err.message : String(err)}`
      );
    }
  }
  const cacheKey2 = `${isStreaming ? "sse" : "json"}:${ResponseCache.generateKey(body)}`;
  const reqHeaders = {};
  for (const [key, value] of Object.entries(req.headers)) {
    if (typeof value === "string") reqHeaders[key] = value;
  }
  if (responseCache2.shouldCache(body, reqHeaders)) {
    const cachedResponse = responseCache2.get(cacheKey2);
    if (cachedResponse) {
      console.log(`[ClawRouter] Cache HIT for ${cachedResponse.model} (saved API call)`);
      res.writeHead(cachedResponse.status, cachedResponse.headers);
      res.end(cachedResponse.body);
      return;
    }
  }
  const dedupKey = `${isStreaming ? "sse" : "json"}:${RequestDeduplicator.hash(body)}`;
  const cached = deduplicator.getCached(dedupKey);
  if (cached) {
    res.writeHead(cached.status, cached.headers);
    res.end(cached.body);
    return;
  }
  const inflight = deduplicator.getInflight(dedupKey);
  if (inflight) {
    const result = await inflight;
    res.writeHead(result.status, result.headers);
    res.end(result.body);
    return;
  }
  deduplicator.markInflight(dedupKey);
  let estimatedCostMicros;
  let isFreeModel = FREE_MODELS.has(modelId ?? "");
  if (modelId && !options.skipBalanceCheck && !isFreeModel) {
    const estimated = estimateAmount(modelId, body.length, maxTokens);
    if (estimated) {
      estimatedCostMicros = BigInt(estimated);
      const bufferedCostMicros = estimatedCostMicros * BigInt(Math.ceil(BALANCE_CHECK_BUFFER * 100)) / 100n;
      let sufficiency = null;
      try {
        sufficiency = await balanceMonitor.checkSufficient(bufferedCostMicros);
      } catch (balanceErr) {
        console.warn(
          `[ClawRouter] Balance check failed (${balanceErr instanceof Error ? balanceErr.message : String(balanceErr)}) \u2014 proceeding optimistically`
        );
      }
      if (sufficiency && (sufficiency.info.isEmpty || !sufficiency.sufficient)) {
        const freeFallback = pickFreeModel(loadExcludeList()) ?? FREE_MODEL;
        const originalModel = modelId;
        console.log(
          `[ClawRouter] Wallet ${sufficiency.info.isEmpty ? "empty" : "insufficient"} (${sufficiency.info.balanceUSD}), falling back to free model: ${freeFallback} (requested: ${originalModel})`
        );
        modelId = freeFallback;
        isFreeModel = true;
        const parsed = JSON.parse(body.toString());
        parsed.model = toUpstreamModelId(FREE_MODEL);
        body = Buffer.from(JSON.stringify(parsed));
        const walletAddr = sufficiency.info.walletAddress;
        const fundHint = walletAddr ? ` Send USDC to \`${walletAddr}\`.` : " Run `/wallet` to see your address.";
        balanceFallbackNotice = sufficiency.info.isEmpty ? `> **\u26A0\uFE0F Wallet empty** \u2014 using free model.${fundHint}

` : `> **\u26A0\uFE0F Insufficient balance** (${sufficiency.info.balanceUSD}) \u2014 using free model instead of ${originalModel}.${fundHint}

`;
        options.onLowBalance?.({
          balanceUSD: sufficiency.info.balanceUSD,
          walletAddress: sufficiency.info.walletAddress
        });
      } else if (sufficiency?.info.isLow) {
        options.onLowBalance?.({
          balanceUSD: sufficiency.info.balanceUSD,
          walletAddress: sufficiency.info.walletAddress
        });
      }
    }
  }
  if (options.maxCostPerRunUsd && effectiveSessionId && !isFreeModel && (options.maxCostPerRunMode ?? "graceful") === "strict") {
    const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);
    const thisReqEstStr = estimatedCostMicros !== void 0 ? estimatedCostMicros.toString() : modelId ? estimateAmount(modelId, body.length, maxTokens) : void 0;
    const thisReqEstUsd = thisReqEstStr ? Number(thisReqEstStr) / 1e6 : 0;
    const projectedCostUsd = runCostUsd + thisReqEstUsd;
    if (projectedCostUsd > options.maxCostPerRunUsd) {
      console.log(
        `[ClawRouter] Cost cap exceeded for session ${effectiveSessionId.slice(0, 8)}...: projected $${projectedCostUsd.toFixed(4)} (spent $${runCostUsd.toFixed(4)} + est $${thisReqEstUsd.toFixed(4)}) > $${options.maxCostPerRunUsd} limit`
      );
      res.writeHead(429, {
        "Content-Type": "application/json",
        "X-ClawRouter-Cost-Cap-Exceeded": "1"
      });
      res.end(
        JSON.stringify({
          error: {
            message: `ClawRouter cost cap exceeded: projected spend $${projectedCostUsd.toFixed(4)} (spent $${runCostUsd.toFixed(4)} + est $${thisReqEstUsd.toFixed(4)}) would exceed limit $${options.maxCostPerRunUsd}`,
            type: "cost_cap_exceeded",
            code: "cost_cap_exceeded"
          }
        })
      );
      deduplicator.removeInflight(dedupKey);
      return;
    }
  }
  if (options.maxCostPerRunUsd && effectiveSessionId && !isFreeModel && (options.maxCostPerRunMode ?? "graceful") === "graceful") {
    const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);
    const remainingUsd = options.maxCostPerRunUsd - runCostUsd;
    const isComplexOrAgentic = hasTools || routingDecision?.tier === "COMPLEX" || routingDecision?.tier === "REASONING";
    if (isComplexOrAgentic) {
      const canAffordAnyNonFreeModel = BLOCKRUN_MODELS.some((m) => {
        if (FREE_MODELS.has(m.id)) return false;
        const est = estimateAmount(m.id, body.length, maxTokens);
        return est !== void 0 && Number(est) / 1e6 <= remainingUsd;
      });
      if (!canAffordAnyNonFreeModel) {
        console.log(
          `[ClawRouter] Budget insufficient for agentic/complex session ${effectiveSessionId.slice(0, 8)}...: $${Math.max(0, remainingUsd).toFixed(4)} remaining \u2014 blocking (silent downgrade would corrupt tool/complex responses)`
        );
        res.writeHead(429, {
          "Content-Type": "application/json",
          "X-ClawRouter-Cost-Cap-Exceeded": "1",
          "X-ClawRouter-Budget-Mode": "blocked"
        });
        res.end(
          JSON.stringify({
            error: {
              message: `ClawRouter budget exhausted: $${Math.max(0, remainingUsd).toFixed(4)} remaining (limit: $${options.maxCostPerRunUsd}). Increase maxCostPerRun to continue.`,
              type: "cost_cap_exceeded",
              code: "budget_exhausted"
            }
          })
        );
        deduplicator.removeInflight(dedupKey);
        return;
      }
    } else if (!routingDecision && modelId && !FREE_MODELS.has(modelId)) {
      const est = estimateAmount(modelId, body.length, maxTokens);
      const canAfford = !est || Number(est) / 1e6 <= remainingUsd;
      if (!canAfford) {
        console.log(
          `[ClawRouter] Budget insufficient for explicit model ${modelId} in session ${effectiveSessionId.slice(0, 8)}...: $${Math.max(0, remainingUsd).toFixed(4)} remaining \u2014 blocking (user explicitly chose ${modelId})`
        );
        res.writeHead(429, {
          "Content-Type": "application/json",
          "X-ClawRouter-Cost-Cap-Exceeded": "1",
          "X-ClawRouter-Budget-Mode": "blocked"
        });
        res.end(
          JSON.stringify({
            error: {
              message: `ClawRouter budget exhausted: $${Math.max(0, remainingUsd).toFixed(4)} remaining (limit: $${options.maxCostPerRunUsd}). Increase maxCostPerRun to continue using ${modelId}.`,
              type: "cost_cap_exceeded",
              code: "budget_exhausted"
            }
          })
        );
        deduplicator.removeInflight(dedupKey);
        return;
      }
    }
  }
  let heartbeatInterval;
  let headersSentEarly = false;
  if (isStreaming) {
    res.writeHead(200, {
      "content-type": "text/event-stream",
      "cache-control": "no-cache",
      connection: "keep-alive",
      "x-context-used-kb": String(originalContextSizeKB),
      "x-context-limit-kb": String(CONTEXT_LIMIT_KB)
    });
    headersSentEarly = true;
    safeWrite(res, ": heartbeat\n\n");
    heartbeatInterval = setInterval(() => {
      if (canWrite(res)) {
        safeWrite(res, ": heartbeat\n\n");
      } else {
        clearInterval(heartbeatInterval);
        heartbeatInterval = void 0;
      }
    }, HEARTBEAT_INTERVAL_MS);
  }
  const headers = {};
  for (const [key, value] of Object.entries(req.headers)) {
    if (key === "host" || key === "connection" || key === "transfer-encoding" || key === "content-length")
      continue;
    if (key.startsWith("x-stainless-") || key.startsWith("anthropic-")) continue;
    if (typeof value === "string") {
      headers[key] = value;
    }
  }
  if (!headers["content-type"]) {
    headers["content-type"] = "application/json";
  }
  headers["user-agent"] = USER_AGENT;
  let completed = false;
  res.on("close", () => {
    if (heartbeatInterval) {
      clearInterval(heartbeatInterval);
      heartbeatInterval = void 0;
    }
    if (!completed) {
      deduplicator.removeInflight(dedupKey);
    }
  });
  const timeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
  const globalController = new AbortController();
  const timeoutId = setTimeout(() => globalController.abort(), timeoutMs);
  const onClientClose = () => {
    if (!globalController.signal.aborted) {
      console.log(`[ClawRouter] Client disconnected \u2014 aborting upstream request`);
      globalController.abort();
    }
  };
  req.on("close", onClientClose);
  try {
    let modelsToTry;
    const excludeList = options.excludeModels ?? loadExcludeList();
    if (isFreeModel && routingDecision && !options.skipBalanceCheck) {
      const freeFallback = pickFreeModel(excludeList) ?? FREE_MODEL;
      modelsToTry = [freeFallback];
      console.log(
        `[ClawRouter] Wallet empty \u2014 skipping routing chain, using free model: ${freeFallback}`
      );
    } else if (routingDecision) {
      const prependStickyExplicitModel = (chain3) => {
        if (!stickyExplicitModel) return chain3;
        return [stickyExplicitModel, ...chain3.filter((model) => model !== stickyExplicitModel)];
      };
      const estimatedInputTokens = Math.ceil(body.length / 4);
      const estimatedTotalTokens = estimatedInputTokens + maxTokens;
      const tierConfigs = routingDecision.tierConfigs ?? routerOpts.config.tiers;
      const fullChain = prependStickyExplicitModel(
        getFallbackChain(routingDecision.tier, tierConfigs)
      );
      const contextFiltered = prependStickyExplicitModel(
        getFallbackChainFiltered(
          routingDecision.tier,
          tierConfigs,
          estimatedTotalTokens,
          getModelContextWindow
        )
      );
      const contextExcluded = fullChain.filter((m) => !contextFiltered.includes(m));
      if (contextExcluded.length > 0) {
        console.log(
          `[ClawRouter] Context filter (~${estimatedTotalTokens} tokens): excluded ${contextExcluded.join(", ")}`
        );
      }
      const excludeFiltered = prependStickyExplicitModel(
        filterByExcludeList(contextFiltered, excludeList)
      );
      const excludeExcluded = contextFiltered.filter((m) => !excludeFiltered.includes(m));
      if (excludeExcluded.length > 0) {
        console.log(
          `[ClawRouter] Exclude filter: excluded ${excludeExcluded.join(", ")} (user preference)`
        );
      }
      let toolFiltered = prependStickyExplicitModel(
        filterByToolCalling(excludeFiltered, hasTools, supportsToolCalling)
      );
      const toolExcluded = excludeFiltered.filter((m) => !toolFiltered.includes(m));
      if (toolExcluded.length > 0) {
        console.log(
          `[ClawRouter] Tool-calling filter: excluded ${toolExcluded.join(", ")} (no structured function call support)`
        );
      }
      const TOOL_NONCOMPLIANT_MODELS = [
        "google/gemini-2.5-flash-lite",
        "google/gemini-3-pro-preview",
        "google/gemini-3.1-pro"
      ];
      if (hasTools && toolFiltered.length > 1) {
        const compliant = toolFiltered.filter((m) => !TOOL_NONCOMPLIANT_MODELS.includes(m));
        if (compliant.length > 0 && compliant.length < toolFiltered.length) {
          const dropped = toolFiltered.filter((m) => TOOL_NONCOMPLIANT_MODELS.includes(m));
          console.log(
            `[ClawRouter] Tool-compliance filter: excluded ${dropped.join(", ")} (unreliable tool schema handling)`
          );
          toolFiltered = prependStickyExplicitModel(compliant);
        }
      }
      const visionFiltered = prependStickyExplicitModel(
        filterByVision(toolFiltered, hasVision, supportsVision)
      );
      const visionExcluded = toolFiltered.filter((m) => !visionFiltered.includes(m));
      if (visionExcluded.length > 0) {
        console.log(
          `[ClawRouter] Vision filter: excluded ${visionExcluded.join(", ")} (no vision support)`
        );
      }
      modelsToTry = prependStickyExplicitModel(visionFiltered).slice(0, MAX_FALLBACK_ATTEMPTS);
      modelsToTry = prioritizeNonRateLimited(modelsToTry);
    } else {
      modelsToTry = modelId ? [modelId] : [];
    }
    if (!hasTools && routingDecision) {
      const freeFallback = pickFreeModel(excludeList);
      if (freeFallback && !modelsToTry.includes(freeFallback)) {
        modelsToTry.push(freeFallback);
      }
    }
    if (options.maxCostPerRunUsd && effectiveSessionId && !isFreeModel && (options.maxCostPerRunMode ?? "graceful") === "graceful") {
      const runCostUsd = sessionStore.getSessionCostUsd(effectiveSessionId);
      const remainingUsd = options.maxCostPerRunUsd - runCostUsd;
      const beforeFilter = [...modelsToTry];
      modelsToTry = modelsToTry.filter((m) => {
        if (FREE_MODELS.has(m)) return true;
        const est = estimateAmount(m, body.length, maxTokens);
        if (!est) return true;
        return Number(est) / 1e6 <= remainingUsd;
      });
      const excluded = beforeFilter.filter((m) => !modelsToTry.includes(m));
      const isComplexOrAgenticFilter = hasTools || routingDecision?.tier === "COMPLEX" || routingDecision?.tier === "REASONING" || routingDecision === void 0;
      const filteredToFreeOnly = modelsToTry.length > 0 && modelsToTry.every((m) => FREE_MODELS.has(m));
      if (isComplexOrAgenticFilter && filteredToFreeOnly) {
        const budgetSummary = `$${Math.max(0, remainingUsd).toFixed(4)} remaining (limit: $${options.maxCostPerRunUsd})`;
        console.log(
          `[ClawRouter] Budget filter left only free model for complex/agentic session \u2014 blocking (${budgetSummary})`
        );
        const errPayload = JSON.stringify({
          error: {
            message: `ClawRouter budget exhausted: remaining budget (${budgetSummary}) cannot support a complex/tool request. Increase maxCostPerRun to continue.`,
            type: "cost_cap_exceeded",
            code: "budget_exhausted"
          }
        });
        if (heartbeatInterval) clearInterval(heartbeatInterval);
        if (headersSentEarly) {
          safeWrite(res, `data: ${errPayload}

data: [DONE]

`);
          res.end();
        } else {
          res.writeHead(429, {
            "Content-Type": "application/json",
            "X-ClawRouter-Cost-Cap-Exceeded": "1",
            "X-ClawRouter-Budget-Mode": "blocked"
          });
          res.end(errPayload);
        }
        deduplicator.removeInflight(dedupKey);
        return;
      }
      if (excluded.length > 0) {
        const budgetSummary = remainingUsd > 0 ? `$${remainingUsd.toFixed(4)} remaining` : `budget exhausted ($${runCostUsd.toFixed(4)}/$${options.maxCostPerRunUsd})`;
        console.log(
          `[ClawRouter] Budget downgrade (${budgetSummary}): excluded ${excluded.join(", ")}`
        );
        const fromModel = excluded[0];
        const usingFree = modelsToTry.length === 1 && FREE_MODELS.has(modelsToTry[0]);
        if (usingFree) {
          budgetDowngradeNotice = `> **\u26A0\uFE0F Budget cap reached** ($${runCostUsd.toFixed(4)}/$${options.maxCostPerRunUsd}) \u2014 downgraded to free model. Quality may be reduced. Increase \`maxCostPerRun\` to continue with ${fromModel}.

`;
        } else {
          const toModel = modelsToTry[0] ?? FREE_MODEL;
          budgetDowngradeNotice = `> **\u26A0\uFE0F Budget low** ($${remainingUsd > 0 ? remainingUsd.toFixed(4) : "0.0000"} remaining) \u2014 using ${toModel} instead of ${fromModel}.

`;
        }
        budgetDowngradeHeaderMode = "downgraded";
      }
    }
    let upstream;
    let lastError;
    let actualModelUsed = modelId;
    const failedAttempts = [];
    for (let i = 0; i < modelsToTry.length; i++) {
      const tryModel = modelsToTry[i];
      const isLastAttempt = i === modelsToTry.length - 1;
      if (globalController.signal.aborted) {
        throw new Error(`Request timed out after ${timeoutMs}ms`);
      }
      console.log(`[ClawRouter] Trying model ${i + 1}/${modelsToTry.length}: ${tryModel}`);
      const perAttemptTimeoutMs = timeoutForModel(tryModel);
      const modelController = new AbortController();
      const modelTimeoutId = setTimeout(() => modelController.abort(), perAttemptTimeoutMs);
      const combinedSignal = AbortSignal.any([globalController.signal, modelController.signal]);
      const result = await tryModelRequest(
        upstreamUrl,
        req.method ?? "POST",
        headers,
        body,
        tryModel,
        maxTokens,
        payFetch,
        balanceMonitor,
        combinedSignal
      );
      clearTimeout(modelTimeoutId);
      if (globalController.signal.aborted) {
        throw new Error(`Request timed out after ${timeoutMs}ms`);
      }
      if (!result.success && modelController.signal.aborted && !isLastAttempt) {
        console.log(
          `[ClawRouter] Model ${tryModel} timed out after ${perAttemptTimeoutMs}ms, trying fallback`
        );
        recordProviderError(tryModel, "server_error");
        continue;
      }
      if (result.success && result.response) {
        const bodyChunks2 = await readBodyWithTimeout(result.response.body);
        const bodyBuf = Buffer.concat(bodyChunks2);
        if (isDegenerateCompletion(bodyBuf) && !isLastAttempt) {
          console.warn(
            `[ClawRouter] \u26A0\uFE0F  Degenerate output from ${tryModel} (finish_reason=length + repetition loop) \u2014 retrying with next fallback`
          );
          recordProviderError(tryModel, "server_error");
          failedAttempts.push({
            model: tryModel,
            reason: "degenerate_output",
            status: 200
          });
          continue;
        }
        upstream = new Response(new Uint8Array(bodyBuf), {
          status: result.response.status,
          statusText: result.response.statusText,
          headers: result.response.headers
        });
        actualModelUsed = tryModel;
        console.log(`[ClawRouter] Success with model: ${tryModel}`);
        if (options.maxCostPerRunUsd && effectiveSessionId && !FREE_MODELS.has(tryModel)) {
          const costEst = estimateAmount(tryModel, body.length, maxTokens);
          if (costEst) {
            sessionStore.addSessionCost(effectiveSessionId, BigInt(costEst));
          }
        }
        break;
      }
      lastError = {
        body: result.errorBody || "Unknown error",
        status: result.errorStatus || 500
      };
      failedAttempts.push({
        model: tryModel,
        reason: result.errorCategory || `HTTP ${result.errorStatus || 500}`,
        status: result.errorStatus || 500
      });
      const isPaymentErr = /payment.*verification.*failed|payment.*settlement.*failed|insufficient.*funds|transaction_simulation_failed/i.test(
        result.errorBody || ""
      );
      if (isPaymentErr && !FREE_MODELS.has(tryModel) && !isLastAttempt) {
        failedAttempts.push({
          ...failedAttempts[failedAttempts.length - 1],
          reason: "payment_error"
        });
        const freeInChain = modelsToTry.findIndex((m, idx) => idx > i && FREE_MODELS.has(m));
        if (freeInChain > i + 1) {
          console.log(
            `[ClawRouter] Payment error \u2014 skipping to free model: ${modelsToTry[freeInChain]}`
          );
          i = freeInChain - 1;
          continue;
        }
        if (freeInChain === -1) {
          const freeFallback = pickFreeModel(excludeList);
          if (freeFallback) {
            modelsToTry.push(freeFallback);
            console.log(`[ClawRouter] Payment error \u2014 appending free model: ${freeFallback}`);
            continue;
          }
        }
      }
      const isExplicitPin = !routingDecision;
      const isRetryableServerError = result.errorCategory === "server_error" || result.errorCategory === "overloaded";
      if (isExplicitPin && isLastAttempt && isRetryableServerError && !globalController.signal.aborted) {
        console.log(
          `[ClawRouter] Explicit pin ${tryModel} got ${result.errorCategory} (HTTP ${result.errorStatus ?? "?"}), retrying once in 500ms`
        );
        await new Promise((resolve) => setTimeout(resolve, 500));
        if (!globalController.signal.aborted) {
          const retryController = new AbortController();
          const retryTimeoutId = setTimeout(
            () => retryController.abort(),
            timeoutForModel(tryModel)
          );
          const retrySignal = AbortSignal.any([globalController.signal, retryController.signal]);
          const retryResult = await tryModelRequest(
            upstreamUrl,
            req.method ?? "POST",
            headers,
            body,
            tryModel,
            maxTokens,
            payFetch,
            balanceMonitor,
            retrySignal
          );
          clearTimeout(retryTimeoutId);
          if (retryResult.success && retryResult.response) {
            upstream = retryResult.response;
            actualModelUsed = tryModel;
            console.log(`[ClawRouter] Explicit-pin retry succeeded for: ${tryModel}`);
            if (options.maxCostPerRunUsd && effectiveSessionId && !FREE_MODELS.has(tryModel)) {
              const costEst = estimateAmount(tryModel, body.length, maxTokens);
              if (costEst) {
                sessionStore.addSessionCost(effectiveSessionId, BigInt(costEst));
              }
            }
            break;
          }
          lastError = {
            body: retryResult.errorBody || lastError?.body || "Unknown error",
            status: retryResult.errorStatus || lastError?.status || 500
          };
          failedAttempts.push({
            model: tryModel,
            reason: `${retryResult.errorCategory || `HTTP ${retryResult.errorStatus || 500}`} (retry)`,
            status: retryResult.errorStatus || 500
          });
        }
      }
      if (result.isProviderError && !isLastAttempt) {
        const isExplicitModelError = !routingDecision;
        const isUnknownExplicitModel = isExplicitModelError && /unknown.*model|invalid.*model/i.test(result.errorBody || "");
        if (isUnknownExplicitModel) {
          console.log(
            `[ClawRouter] Explicit model error from ${tryModel}, not falling back: ${result.errorBody?.slice(0, 100)}`
          );
          break;
        }
        const errorCat = result.errorCategory;
        if (errorCat) {
          recordProviderError(tryModel, errorCat);
        }
        if (errorCat === "rate_limited") {
          if (!isLastAttempt && !globalController.signal.aborted) {
            console.log(
              `[ClawRouter] Rate-limited on ${tryModel}, retrying in 200ms before failover`
            );
            await new Promise((resolve) => setTimeout(resolve, 200));
            if (!globalController.signal.aborted) {
              const retryController = new AbortController();
              const retryTimeoutId = setTimeout(
                () => retryController.abort(),
                timeoutForModel(tryModel)
              );
              const retrySignal = AbortSignal.any([
                globalController.signal,
                retryController.signal
              ]);
              const retryResult = await tryModelRequest(
                upstreamUrl,
                req.method ?? "POST",
                headers,
                body,
                tryModel,
                maxTokens,
                payFetch,
                balanceMonitor,
                retrySignal
              );
              clearTimeout(retryTimeoutId);
              if (retryResult.success && retryResult.response) {
                upstream = retryResult.response;
                actualModelUsed = tryModel;
                console.log(`[ClawRouter] Rate-limit retry succeeded for: ${tryModel}`);
                if (options.maxCostPerRunUsd && effectiveSessionId && tryModel !== FREE_MODEL) {
                  const costEst = estimateAmount(tryModel, body.length, maxTokens);
                  if (costEst) {
                    sessionStore.addSessionCost(effectiveSessionId, BigInt(costEst));
                  }
                }
                break;
              }
            }
          }
          markRateLimited(tryModel);
          try {
            const parsed = JSON.parse(result.errorBody || "{}");
            if (parsed.update_available) {
              console.log("");
              console.log(
                `\x1B[33m\u2B06\uFE0F  ClawRouter ${parsed.update_available} available (you have ${VERSION})\x1B[0m`
              );
              console.log(
                `   Run: \x1B[36mcurl -fsSL ${parsed.update_url || "https://blockrun.ai/ClawRouter-update"} | bash\x1B[0m`
              );
              console.log("");
            }
          } catch {
          }
        } else if (errorCat === "overloaded") {
          markOverloaded(tryModel);
        } else if (errorCat === "auth_failure" || errorCat === "quota_exceeded") {
          console.log(
            `[ClawRouter] \u{1F511} ${errorCat === "auth_failure" ? "Auth failure" : "Quota exceeded"} for ${tryModel} \u2014 check provider config`
          );
        }
        console.log(
          `[ClawRouter] Provider error from ${tryModel}, trying fallback: ${result.errorBody?.slice(0, 100)}`
        );
        continue;
      }
      if (!result.isProviderError) {
        console.log(
          `[ClawRouter] Non-provider error from ${tryModel}, not retrying: ${result.errorBody?.slice(0, 100)}`
        );
      }
      break;
    }
    clearTimeout(timeoutId);
    req.removeListener("close", onClientClose);
    if (heartbeatInterval) {
      clearInterval(heartbeatInterval);
      heartbeatInterval = void 0;
    }
    if (debugMode && headersSentEarly && routingDecision) {
      const debugComment = `: x-clawrouter-debug profile=${routingProfile ?? "auto"} tier=${routingDecision.tier} model=${actualModelUsed} agentic=${routingDecision.agenticScore?.toFixed(2) ?? "n/a"} confidence=${routingDecision.confidence.toFixed(2)} reasoning=${routingDecision.reasoning}

`;
      safeWrite(res, debugComment);
    }
    if (routingDecision && actualModelUsed !== routingDecision.model) {
      const estimatedInputTokens = Math.ceil(body.length / 4);
      const newCosts = calculateModelCost(
        actualModelUsed,
        routerOpts.modelPricing,
        estimatedInputTokens,
        maxTokens,
        routingProfile ?? void 0
      );
      routingDecision = {
        ...routingDecision,
        model: actualModelUsed,
        reasoning: `${routingDecision.reasoning} | fallback to ${actualModelUsed}`,
        costEstimate: newCosts.costEstimate,
        baselineCost: newCosts.baselineCost,
        savings: newCosts.savings
      };
      options.onRouted?.(routingDecision);
      if (effectiveSessionId) {
        const pinnedSession = sessionStore.getSession(effectiveSessionId);
        if (pinnedSession?.userExplicit) {
          console.log(
            `[ClawRouter] Session ${effectiveSessionId.slice(0, 8)}... fallback used ${actualModelUsed}, preserving user-explicit pin: ${pinnedSession.model}`
          );
        } else {
          sessionStore.setSession(effectiveSessionId, actualModelUsed, routingDecision.tier);
          console.log(
            `[ClawRouter] Session ${effectiveSessionId.slice(0, 8)}... updated pin to fallback: ${actualModelUsed}`
          );
        }
      }
    }
    if (!upstream) {
      const attemptSummary = failedAttempts.length > 0 ? failedAttempts.map((a) => `${a.model} (${a.reason})`).join(", ") : "unknown";
      const structuredMessage = failedAttempts.length > 0 ? `All ${failedAttempts.length} models failed. Tried: ${attemptSummary}` : "All models in fallback chain failed";
      console.log(`[ClawRouter] ${structuredMessage}`);
      const rawErrBody = lastError?.body || structuredMessage;
      const errStatus = lastError?.status || 502;
      const transformedErr = transformPaymentError(rawErrBody);
      requestHadError = true;
      if (headersSentEarly) {
        let errPayload;
        try {
          const parsed = JSON.parse(transformedErr);
          if (parsed && typeof parsed === "object" && "error" in parsed) {
            errPayload = JSON.stringify(parsed);
          } else {
            errPayload = JSON.stringify({
              error: { message: rawErrBody, type: "provider_error", status: errStatus }
            });
          }
        } catch {
          errPayload = JSON.stringify({
            error: { message: rawErrBody, type: "provider_error", status: errStatus }
          });
        }
        const errEvent = `data: ${errPayload}

`;
        safeWrite(res, errEvent);
        safeWrite(res, "data: [DONE]\n\n");
        res.end();
        const errBuf = Buffer.from(errEvent + "data: [DONE]\n\n");
        deduplicator.complete(dedupKey, {
          status: 200,
          headers: { "content-type": "text/event-stream" },
          body: errBuf,
          completedAt: Date.now()
        });
      } else {
        res.writeHead(errStatus, {
          "Content-Type": "application/json",
          "x-context-used-kb": String(originalContextSizeKB),
          "x-context-limit-kb": String(CONTEXT_LIMIT_KB)
        });
        res.end(transformedErr);
        deduplicator.complete(dedupKey, {
          status: errStatus,
          headers: { "content-type": "application/json" },
          body: Buffer.from(transformedErr),
          completedAt: Date.now()
        });
      }
      const errModel = routingDecision?.model ?? modelId;
      if (errModel) {
        const errPayment = paymentStore.getStore()?.amountUsd ?? 0;
        logUsage({
          timestamp: (/* @__PURE__ */ new Date()).toISOString(),
          model: errModel,
          tier: routingDecision?.tier ?? "DIRECT",
          cost: errPayment,
          baselineCost: errPayment,
          savings: 0,
          latencyMs: Date.now() - startTime,
          status: "error"
        }).catch(() => {
        });
      }
      return;
    }
    const responseChunks = [];
    if (headersSentEarly) {
      if (upstream.body) {
        const chunks = await readBodyWithTimeout(upstream.body);
        const jsonBody = Buffer.concat(chunks);
        const jsonStr = jsonBody.toString();
        try {
          const rsp = JSON.parse(jsonStr);
          if (rsp.usage && typeof rsp.usage === "object") {
            const u = rsp.usage;
            if (typeof u.prompt_tokens === "number") responseInputTokens = u.prompt_tokens;
            if (typeof u.completion_tokens === "number") responseOutputTokens = u.completion_tokens;
          }
          const baseChunk = {
            id: rsp.id ?? `chatcmpl-${Date.now()}`,
            object: "chat.completion.chunk",
            created: rsp.created ?? Math.floor(Date.now() / 1e3),
            model: actualModelUsed || rsp.model || "unknown",
            system_fingerprint: null
          };
          if (rsp.choices && Array.isArray(rsp.choices)) {
            for (const choice of rsp.choices) {
              const endsWithToolCalls = choice.finish_reason === "tool_calls";
              let toolCalls = choice.message?.tool_calls ?? choice.delta?.tool_calls;
              const rawContent = choice.message?.content ?? choice.delta?.content ?? "";
              if (!endsWithToolCalls && (!toolCalls || toolCalls.length === 0) && rawContent) {
                const extracted = extractTextualToolCalls(rawContent);
                if (extracted.toolCalls.length > 0) {
                  toolCalls = extracted.toolCalls;
                }
              }
              const content = endsWithToolCalls || toolCalls && toolCalls.length > 0 ? "" : stripThinkingTokens(rawContent);
              const role = choice.message?.role ?? choice.delta?.role ?? "assistant";
              const index2 = choice.index ?? 0;
              if (content) {
                accumulatedContent += content;
              }
              const roleChunk = {
                ...baseChunk,
                choices: [{ index: index2, delta: { role }, logprobs: null, finish_reason: null }]
              };
              const roleData = `data: ${JSON.stringify(roleChunk)}

`;
              safeWrite(res, roleData);
              responseChunks.push(Buffer.from(roleData));
              if (balanceFallbackNotice) {
                const noticeChunk = {
                  ...baseChunk,
                  choices: [
                    {
                      index: index2,
                      delta: { content: balanceFallbackNotice },
                      logprobs: null,
                      finish_reason: null
                    }
                  ]
                };
                const noticeData = `data: ${JSON.stringify(noticeChunk)}

`;
                safeWrite(res, noticeData);
                responseChunks.push(Buffer.from(noticeData));
                balanceFallbackNotice = void 0;
              }
              if (budgetDowngradeNotice) {
                const noticeChunk = {
                  ...baseChunk,
                  choices: [
                    {
                      index: index2,
                      delta: { content: budgetDowngradeNotice },
                      logprobs: null,
                      finish_reason: null
                    }
                  ]
                };
                const noticeData = `data: ${JSON.stringify(noticeChunk)}

`;
                safeWrite(res, noticeData);
                responseChunks.push(Buffer.from(noticeData));
                budgetDowngradeNotice = void 0;
              }
              if (content) {
                const contentChunk = {
                  ...baseChunk,
                  choices: [{ index: index2, delta: { content }, logprobs: null, finish_reason: null }]
                };
                const contentData = `data: ${JSON.stringify(contentChunk)}

`;
                safeWrite(res, contentData);
                responseChunks.push(Buffer.from(contentData));
              }
              if (toolCalls && toolCalls.length > 0) {
                const toolCallChunk = {
                  ...baseChunk,
                  choices: [
                    {
                      index: index2,
                      delta: { tool_calls: toolCalls },
                      logprobs: null,
                      finish_reason: null
                    }
                  ]
                };
                const toolCallData = `data: ${JSON.stringify(toolCallChunk)}

`;
                safeWrite(res, toolCallData);
                responseChunks.push(Buffer.from(toolCallData));
              }
              const finishChunk = {
                ...baseChunk,
                choices: [
                  {
                    index: index2,
                    delta: {},
                    logprobs: null,
                    finish_reason: endsWithToolCalls || toolCalls && toolCalls.length > 0 ? "tool_calls" : choice.finish_reason ?? "stop"
                  }
                ]
              };
              const finishData = `data: ${JSON.stringify(finishChunk)}

`;
              safeWrite(res, finishData);
              responseChunks.push(Buffer.from(finishData));
            }
          }
        } catch {
          const errPayload = JSON.stringify({
            error: {
              message: `Upstream response could not be parsed: ${jsonStr.slice(0, 200)}`,
              type: "proxy_error"
            }
          });
          const sseData = `data: ${errPayload}

`;
          safeWrite(res, sseData);
          responseChunks.push(Buffer.from(sseData));
        }
      }
      if (typeof responseInputTokens === "number" && typeof responseOutputTokens === "number") {
        const usagePayload = {
          prompt_tokens: responseInputTokens,
          completion_tokens: responseOutputTokens,
          total_tokens: responseInputTokens + responseOutputTokens
        };
        const costBreakdown = buildCostBreakdown({
          actualModelUsed,
          routingProfile: routingProfile ?? void 0,
          routingDecision,
          modelPricing: routerOpts.modelPricing,
          inputTokens: responseInputTokens,
          outputTokens: responseOutputTokens,
          tier: routingDecision?.tier
        });
        if (costBreakdown) {
          usagePayload.cost = costBreakdown;
        }
        const usageChunk = {
          id: `chatcmpl-${Date.now()}`,
          object: "chat.completion.chunk",
          created: Math.floor(Date.now() / 1e3),
          model: actualModelUsed || "unknown",
          system_fingerprint: null,
          choices: [],
          usage: usagePayload
        };
        const usageData = `data: ${JSON.stringify(usageChunk)}

`;
        safeWrite(res, usageData);
        responseChunks.push(Buffer.from(usageData));
      }
      if (routingDecision) {
        const costComment = `: cost=$${routingDecision.costEstimate.toFixed(4)} savings=${(routingDecision.savings * 100).toFixed(0)}% model=${actualModelUsed} tier=${routingDecision.tier}

`;
        safeWrite(res, costComment);
        responseChunks.push(Buffer.from(costComment));
      }
      safeWrite(res, "data: [DONE]\n\n");
      responseChunks.push(Buffer.from("data: [DONE]\n\n"));
      res.end();
      deduplicator.complete(dedupKey, {
        status: 200,
        headers: { "content-type": "text/event-stream" },
        body: Buffer.concat(responseChunks),
        completedAt: Date.now()
      });
    } else {
      const responseHeaders = {};
      upstream.headers.forEach((value, key) => {
        if (key === "transfer-encoding" || key === "connection" || key === "content-encoding")
          return;
        responseHeaders[key] = value;
      });
      responseHeaders["x-context-used-kb"] = String(originalContextSizeKB);
      responseHeaders["x-context-limit-kb"] = String(CONTEXT_LIMIT_KB);
      if (debugMode && routingDecision) {
        responseHeaders["x-clawrouter-profile"] = routingProfile ?? "auto";
        responseHeaders["x-clawrouter-tier"] = routingDecision.tier;
        responseHeaders["x-clawrouter-model"] = actualModelUsed;
        responseHeaders["x-clawrouter-confidence"] = routingDecision.confidence.toFixed(2);
        responseHeaders["x-clawrouter-reasoning"] = routingDecision.reasoning;
        if (routingDecision.agenticScore !== void 0) {
          responseHeaders["x-clawrouter-agentic-score"] = routingDecision.agenticScore.toFixed(2);
        }
      }
      if (routingDecision) {
        responseHeaders["x-clawrouter-cost"] = routingDecision.costEstimate.toFixed(6);
        responseHeaders["x-clawrouter-savings"] = `${(routingDecision.savings * 100).toFixed(0)}%`;
      }
      const bodyParts = [];
      if (upstream.body) {
        const chunks = await readBodyWithTimeout(upstream.body);
        for (const chunk of chunks) {
          bodyParts.push(Buffer.from(chunk));
        }
      }
      let responseBody = Buffer.concat(bodyParts);
      if (responseBody.length > 0) {
        try {
          const parsed = JSON.parse(responseBody.toString());
          let changed = false;
          for (const choice of parsed.choices ?? []) {
            const message = choice.message;
            if (!message || typeof message.content !== "string") continue;
            if (choice.finish_reason === "tool_calls" || Array.isArray(message.tool_calls) && message.tool_calls.length > 0) {
              if (message.content !== "") {
                message.content = "";
                changed = true;
              }
              continue;
            }
            const extracted = extractTextualToolCalls(message.content);
            if (extracted.toolCalls.length > 0) {
              message.tool_calls = extracted.toolCalls;
              message.content = "";
              choice.finish_reason = "tool_calls";
              changed = true;
              continue;
            }
            const stripped = stripThinkingTokens(message.content);
            if (stripped !== message.content) {
              message.content = stripped;
              changed = true;
            }
          }
          if (changed) responseBody = Buffer.from(JSON.stringify(parsed));
        } catch {
        }
      }
      if (balanceFallbackNotice && responseBody.length > 0) {
        try {
          const parsed = JSON.parse(responseBody.toString());
          if (parsed.choices?.[0]?.message?.content !== void 0) {
            parsed.choices[0].message.content = balanceFallbackNotice + parsed.choices[0].message.content;
            responseBody = Buffer.from(JSON.stringify(parsed));
          }
        } catch {
        }
        balanceFallbackNotice = void 0;
      }
      if (budgetDowngradeNotice && responseBody.length > 0) {
        try {
          const parsed = JSON.parse(responseBody.toString());
          if (parsed.choices?.[0]?.message?.content !== void 0) {
            parsed.choices[0].message.content = budgetDowngradeNotice + parsed.choices[0].message.content;
            responseBody = Buffer.from(JSON.stringify(parsed));
          }
        } catch {
        }
        budgetDowngradeNotice = void 0;
      }
      if (actualModelUsed && responseBody.length > 0) {
        try {
          const parsed = JSON.parse(responseBody.toString());
          parsed.model = actualModelUsed;
          const costBreakdown = buildCostBreakdown({
            actualModelUsed,
            routingProfile: routingProfile ?? void 0,
            routingDecision,
            modelPricing: routerOpts.modelPricing,
            inputTokens: responseInputTokens,
            outputTokens: responseOutputTokens,
            tier: routingDecision?.tier
          });
          if (costBreakdown) {
            if (!parsed.usage || typeof parsed.usage !== "object") {
              parsed.usage = {};
            }
            parsed.usage.cost = costBreakdown;
          }
          responseBody = Buffer.from(JSON.stringify(parsed));
        } catch {
        }
      }
      if (budgetDowngradeHeaderMode) {
        responseHeaders["x-clawrouter-budget-downgrade"] = "1";
        responseHeaders["x-clawrouter-budget-mode"] = budgetDowngradeHeaderMode;
        budgetDowngradeHeaderMode = void 0;
      }
      responseHeaders["content-length"] = String(responseBody.length);
      res.writeHead(upstream.status, responseHeaders);
      safeWrite(res, responseBody);
      responseChunks.push(responseBody);
      res.end();
      deduplicator.complete(dedupKey, {
        status: upstream.status,
        headers: responseHeaders,
        body: responseBody,
        completedAt: Date.now()
      });
      if (upstream.status === 200 && responseCache2.shouldCache(body)) {
        responseCache2.set(cacheKey2, {
          body: responseBody,
          status: upstream.status,
          headers: responseHeaders,
          model: actualModelUsed
        });
        console.log(
          `[ClawRouter] Cached response for ${actualModelUsed} (${responseBody.length} bytes)`
        );
      }
      try {
        const rspJson = JSON.parse(responseBody.toString());
        if (rspJson.choices?.[0]?.message?.content) {
          accumulatedContent = rspJson.choices[0].message.content;
        }
        if (rspJson.usage && typeof rspJson.usage === "object") {
          if (typeof rspJson.usage.prompt_tokens === "number")
            responseInputTokens = rspJson.usage.prompt_tokens;
          if (typeof rspJson.usage.completion_tokens === "number")
            responseOutputTokens = rspJson.usage.completion_tokens;
        }
      } catch {
      }
    }
    if (accumulatedContent.length >= 80) {
      const tail = accumulatedContent.slice(-80);
      const tailChars = [...tail];
      const firstChar = tailChars[0];
      const isPunct = /[^\p{L}\p{N}\s]/u.test(firstChar);
      const sameCount = tailChars.filter((c) => c === firstChar).length;
      if (isPunct && sameCount >= 60) {
        console.warn(
          `[ClawRouter] \u26A0\uFE0F  Degenerate output detected \u2014 model=${actualModelUsed || "unknown"} len=${accumulatedContent.length} head=${JSON.stringify(accumulatedContent.slice(0, 40))} tail_repeats_${JSON.stringify(firstChar)}=${sameCount}/80`
        );
      }
    }
    if (sessionId && accumulatedContent) {
      const events = sessionJournal.extractEvents(accumulatedContent);
      if (events.length > 0) {
        sessionJournal.record(sessionId, events, actualModelUsed);
        console.log(
          `[ClawRouter] Recorded ${events.length} events to session journal for session ${sessionId.slice(0, 8)}...`
        );
      }
    }
    if (accumulatedContent && isChatCompletion) {
      void appendResponse({
        sessionId,
        model: actualModelUsed || void 0,
        requestSummary: requestSummaryForStore,
        responseText: accumulatedContent
      });
    }
    if (estimatedCostMicros !== void 0) {
      balanceMonitor.deductEstimated(estimatedCostMicros);
    }
    completed = true;
  } catch (err) {
    clearTimeout(timeoutId);
    req.removeListener("close", onClientClose);
    if (heartbeatInterval) {
      clearInterval(heartbeatInterval);
      heartbeatInterval = void 0;
    }
    deduplicator.removeInflight(dedupKey);
    balanceMonitor.invalidate();
    if (err instanceof Error && err.name === "AbortError") {
      throw new Error(`Request timed out after ${timeoutMs}ms`, { cause: err });
    }
    throw err;
  }
  const logModel = routingDecision?.model ?? modelId;
  if (logModel) {
    const actualPayment = paymentStore.getStore()?.amountUsd ?? 0;
    let logCost;
    let logBaseline;
    let logSavings;
    if (actualPayment > 0) {
      logCost = actualPayment;
      const chargedInputTokens = Math.ceil(body.length / 4);
      const modelDef = BLOCKRUN_MODELS.find((m) => m.id === logModel);
      const chargedOutputTokens = modelDef ? Math.min(maxTokens, modelDef.maxOutput) : maxTokens;
      const baseline = calculateModelCost(
        logModel,
        routerOpts.modelPricing,
        chargedInputTokens,
        chargedOutputTokens,
        routingProfile ?? void 0
      );
      logBaseline = baseline.baselineCost;
      logSavings = logBaseline > 0 ? Math.max(0, (logBaseline - logCost) / logBaseline) : 0;
    } else {
      const chargedInputTokens = Math.ceil(body.length / 4);
      const costs = calculateModelCost(
        logModel,
        routerOpts.modelPricing,
        chargedInputTokens,
        maxTokens,
        routingProfile ?? void 0
      );
      logCost = FREE_MODELS.has(logModel) ? 0 : costs.costEstimate;
      logBaseline = costs.baselineCost;
      logSavings = FREE_MODELS.has(logModel) ? 1 : costs.savings;
    }
    const entry = {
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      model: logModel,
      tier: routingDecision?.tier ?? "DIRECT",
      cost: logCost,
      baselineCost: logBaseline,
      savings: logSavings,
      latencyMs: Date.now() - startTime,
      status: requestHadError ? "error" : "success",
      ...responseInputTokens !== void 0 && { inputTokens: responseInputTokens },
      ...responseOutputTokens !== void 0 && { outputTokens: responseOutputTokens }
    };
    logUsage(entry).catch(() => {
    });
  }
}
var paymentStore, BLOCKRUN_API, BLOCKRUN_SOLANA_API, IMAGE_DIR, AUDIO_DIR, VIDEO_DIR, AUTO_MODEL, ROUTING_PROFILES, FREE_MODELS, FREE_MODEL, MAX_MESSAGES, CONTEXT_LIMIT_KB, HEARTBEAT_INTERVAL_MS, DEFAULT_REQUEST_TIMEOUT_MS, PER_MODEL_TIMEOUT_MS, REASONING_MODEL_TIMEOUT_MS, REASONING_MODEL_IDS, MAX_FALLBACK_ATTEMPTS, HEALTH_CHECK_TIMEOUT_MS, RATE_LIMIT_COOLDOWN_MS, OVERLOAD_COOLDOWN_MS, PORT_RETRY_ATTEMPTS, PORT_RETRY_DELAY_MS, MODEL_BODY_READ_TIMEOUT_MS, ERROR_BODY_READ_TIMEOUT_MS, rateLimitedModels, overloadedModels, perProviderErrors, BALANCE_CHECK_BUFFER, PROVIDER_ERROR_PATTERNS, DEGRADED_RESPONSE_PATTERNS, DEGRADED_LOOP_PATTERNS, VALID_ROLES, ROLE_MAPPINGS, VALID_TOOL_ID_PATTERN, KIMI_BLOCK_RE, KIMI_TOKEN_RE, THINKING_TAG_RE, THINKING_BLOCK_RE, IMAGE_PRICING, VIDEO_PRICING, PHONE_PRICING;
var init_proxy = __esm({
  "src/proxy.ts"() {
    "use strict";
    init_esm();
    init_chains();
    init_accounts();
    init_esm4();
    init_payment_preauth();
    init_client2();
    init_esm5();
    init_router();
    init_rules();
    init_models();
    init_logger();
    init_stats();
    init_dedup();
    init_response_cache();
    init_balance();
    init_auth();
    init_compression();
    init_version4();
    init_session();
    init_updater();
    init_exclude_models();
    init_config2();
    init_journal();
    init_upstream_proxy();
    init_textual_tool_calls();
    init_response_store();
    init_share_formatters();
    paymentStore = new AsyncLocalStorage();
    BLOCKRUN_API = "https://blockrun.ai/api";
    BLOCKRUN_SOLANA_API = "https://sol.blockrun.ai/api";
    IMAGE_DIR = join9(homedir6(), ".openclaw", "blockrun", "images");
    AUDIO_DIR = join9(homedir6(), ".openclaw", "blockrun", "audio");
    VIDEO_DIR = join9(homedir6(), ".openclaw", "blockrun", "videos");
    AUTO_MODEL = "blockrun/auto";
    ROUTING_PROFILES = /* @__PURE__ */ new Set([
      "blockrun/eco",
      "eco",
      "blockrun/auto",
      "auto",
      "blockrun/premium",
      "premium"
    ]);
    FREE_MODELS = /* @__PURE__ */ new Set([
      "free/gpt-oss-120b",
      "free/gpt-oss-20b",
      "free/mistral-small-4-119b",
      // 114 tok/s — fastest free chat
      "free/deepseek-v4-flash",
      // 1M ctx DeepSeek V4 Flash (V4 Pro NVIDIA hung 2026-04-30)
      "free/qwen3-next-80b-a3b-thinking",
      // 116 tok/s reasoning
      "free/qwen3-coder-480b",
      "free/glm-4.7",
      "free/llama-4-maverick",
      "free/nemotron-3-nano-omni-30b-a3b-reasoning"
      // first vision-capable free
    ]);
    FREE_MODEL = "free/gpt-oss-120b";
    MAX_MESSAGES = 200;
    CONTEXT_LIMIT_KB = 5120;
    HEARTBEAT_INTERVAL_MS = 2e3;
    DEFAULT_REQUEST_TIMEOUT_MS = 3e5;
    PER_MODEL_TIMEOUT_MS = 6e4;
    REASONING_MODEL_TIMEOUT_MS = 18e4;
    REASONING_MODEL_IDS = new Set(
      BLOCKRUN_MODELS.filter((m) => m.reasoning).map((m) => m.id)
    );
    MAX_FALLBACK_ATTEMPTS = 5;
    HEALTH_CHECK_TIMEOUT_MS = 2e3;
    RATE_LIMIT_COOLDOWN_MS = 6e4;
    OVERLOAD_COOLDOWN_MS = 15e3;
    PORT_RETRY_ATTEMPTS = 5;
    PORT_RETRY_DELAY_MS = 1e3;
    MODEL_BODY_READ_TIMEOUT_MS = 3e5;
    ERROR_BODY_READ_TIMEOUT_MS = 3e4;
    rateLimitedModels = /* @__PURE__ */ new Map();
    overloadedModels = /* @__PURE__ */ new Map();
    perProviderErrors = /* @__PURE__ */ new Map();
    BALANCE_CHECK_BUFFER = 1.5;
    PROVIDER_ERROR_PATTERNS = [
      /billing/i,
      /insufficient.*balance/i,
      /credits/i,
      /quota.*exceeded/i,
      /rate.*limit/i,
      /model.*unavailable/i,
      /model.*not.*available/i,
      /service.*unavailable/i,
      /capacity/i,
      /overloaded/i,
      /temporarily.*unavailable/i,
      /api.*key.*invalid/i,
      /authentication.*failed/i,
      /request too large/i,
      /request.*size.*exceeds/i,
      /payload too large/i,
      /payment.*verification.*failed/i,
      /model.*not.*allowed/i,
      /unknown.*model/i,
      /reasoning_content.*missing/i,
      // Thinking model multi-turn: missing reasoning_content → fallback
      /thinking.*reasoning_content/i
    ];
    DEGRADED_RESPONSE_PATTERNS = [
      /the ai service is temporarily overloaded/i,
      /service is temporarily overloaded/i,
      /please try again in a moment/i
    ];
    DEGRADED_LOOP_PATTERNS = [
      /the boxed is the response\./i,
      /the response is the text\./i,
      /the final answer is the boxed\./i
    ];
    VALID_ROLES = /* @__PURE__ */ new Set(["system", "user", "assistant", "tool", "function"]);
    ROLE_MAPPINGS = {
      developer: "system",
      // OpenAI's newer API uses "developer" for system messages
      model: "assistant"
      // Some APIs use "model" instead of "assistant"
    };
    VALID_TOOL_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
    KIMI_BLOCK_RE = /<[｜|][^<>]*begin[^<>]*[｜|]>[\s\S]*?<[｜|][^<>]*end[^<>]*[｜|]>/gi;
    KIMI_TOKEN_RE = /<[｜|][^<>]*[｜|]>/g;
    THINKING_TAG_RE = /<\s*\/?\s*(?:think(?:ing)?|thought|antthinking|antml:thinking)\b[^>]*>/gi;
    THINKING_BLOCK_RE = /<\s*(?:think(?:ing)?|thought|antthinking|antml:thinking)\b[^>]*>[\s\S]*?<\s*\/\s*(?:think(?:ing)?|thought|antthinking|antml:thinking)\s*>/gi;
    IMAGE_PRICING = {
      "openai/dall-e-3": {
        default: 0.04,
        sizes: { "1024x1024": 0.04, "1792x1024": 0.08, "1024x1792": 0.08 }
      },
      "openai/gpt-image-1": {
        default: 0.02,
        sizes: { "1024x1024": 0.02, "1536x1024": 0.04, "1024x1536": 0.04 }
      },
      "black-forest/flux-1.1-pro": { default: 0.04 },
      "google/nano-banana": { default: 0.05 },
      "google/nano-banana-pro": {
        default: 0.1,
        sizes: { "1024x1024": 0.1, "2048x2048": 0.1, "4096x4096": 0.15 }
      },
      "xai/grok-imagine-image": { default: 0.02, sizes: { "1024x1024": 0.02 } },
      "xai/grok-imagine-image-pro": { default: 0.07, sizes: { "1024x1024": 0.07 } },
      "zai/cogview-4": {
        default: 0.015,
        sizes: {
          "512x512": 0.015,
          "768x768": 0.015,
          "1024x1024": 0.015,
          "768x1344": 0.015,
          "1344x768": 0.015,
          "1440x1440": 0.02
        }
      }
    };
    VIDEO_PRICING = {
      "xai/grok-imagine-video": { pricePerSecond: 0.05, defaultDurationSeconds: 8 },
      "bytedance/seedance-1.5-pro": { pricePerSecond: 0.0875, defaultDurationSeconds: 5 },
      "bytedance/seedance-2.0-fast": {
        pricePerSecond: 0.22687,
        pricePerSecondImageInput: 0.13369,
        defaultDurationSeconds: 5
      },
      "bytedance/seedance-2.0": {
        pricePerSecond: 0.28358,
        pricePerSecondImageInput: 0.1742,
        defaultDurationSeconds: 5
      }
    };
    PHONE_PRICING = {
      "phone/lookup/fraud": 0.05,
      "phone/lookup": 0.01,
      "phone/numbers/buy": 5,
      "phone/numbers/renew": 5,
      "phone/numbers/list": 1e-3,
      "phone/numbers/release": 0,
      "voice/call": 0.54
    };
  }
});

// src/partners/registry.ts
function getPartnerService(id) {
  return PARTNER_SERVICES.find((s3) => s3.id === id);
}
var PARTNER_SERVICES;
var init_registry = __esm({
  "src/partners/registry.ts"() {
    "use strict";
    PARTNER_SERVICES = [
      // ---------------------------------------------------------------------------
      // Predexon — Prediction Market Data
      // ---------------------------------------------------------------------------
      {
        id: "predexon_events",
        name: "Polymarket Events",
        partner: "Predexon",
        category: "Prediction markets",
        shortDescription: "Live Polymarket events",
        description: "Get live Polymarket prediction market events with current odds, volume, and liquidity. Call this for ANY request about prediction markets, Polymarket markets, current odds, what people are betting on, or market sentiment. Do NOT use browser or web scraping \u2014 this returns structured real-time data directly. Returns: event title, YES/NO prices (implied probability), volume, liquidity, end date.",
        proxyPath: "/pm/polymarket/events",
        method: "GET",
        params: [
          {
            name: "limit",
            type: "number",
            description: "Number of events to return (default: 20, max: 100)",
            required: false
          },
          {
            name: "tag",
            type: "string",
            description: "Filter by category: crypto, politics, sports, science, economics, etc.",
            required: false
          }
        ],
        pricing: { perUnit: "$0.001", unit: "request", minimum: "$0.001", maximum: "$0.001" },
        example: {
          input: { limit: 20 },
          description: "Get top 20 live Polymarket events"
        }
      },
      {
        id: "predexon_leaderboard",
        name: "Polymarket Leaderboard",
        partner: "Predexon",
        category: "Prediction markets",
        shortDescription: "Top traders ranked by profit",
        description: "Get the Polymarket leaderboard of top traders ranked by profit. Call this for ANY request about top Polymarket traders, whale wallets, best performers, richest traders, or who is making the most money on Polymarket. Do NOT use browser or web scraping \u2014 this returns structured data directly. Returns: wallet address/username, total profit, total volume, win rate.",
        proxyPath: "/pm/polymarket/leaderboard",
        method: "GET",
        params: [
          {
            name: "limit",
            type: "number",
            description: "Number of wallets to return (default: 20, max: 100)",
            required: false
          }
        ],
        pricing: { perUnit: "$0.001", unit: "request", minimum: "$0.001", maximum: "$0.001" },
        example: {
          input: { limit: 20 },
          description: "Get top 20 Polymarket whale wallets by profit"
        }
      },
      {
        id: "predexon_markets",
        name: "Polymarket Markets Search",
        partner: "Predexon",
        category: "Prediction markets",
        shortDescription: "Market search by keyword",
        description: "Search and filter Polymarket markets. Use this to find a market by keyword and get its conditionId for follow-up calls (smart money, top holders, etc.). Returns: question, conditionId, YES/NO prices, volume.",
        proxyPath: "/pm/polymarket/markets",
        method: "GET",
        params: [
          {
            name: "search",
            type: "string",
            description: "Keyword to search for (e.g. 'bitcoin', 'election', 'fed rate')",
            required: false
          },
          {
            name: "limit",
            type: "number",
            description: "Number of markets to return (default: 20)",
            required: false
          }
        ],
        pricing: { perUnit: "$0.001", unit: "request", minimum: "$0.001", maximum: "$0.001" },
        example: {
          input: { search: "bitcoin", limit: 10 },
          description: "Search for Bitcoin-related prediction markets"
        }
      },
      {
        id: "predexon_smart_money",
        name: "Polymarket Smart Money",
        partner: "Predexon",
        category: "Prediction markets",
        shortDescription: "Smart-money positions on a market",
        description: "See how high-performing wallets are positioned on a specific Polymarket market. Use this after finding a market's conditionId via predexon_markets or predexon_events. Returns: wallet addresses, their YES/NO positions, size, P&L, win rate.",
        proxyPath: "/pm/polymarket/market/:condition_id/smart-money",
        method: "GET",
        params: [
          {
            name: "condition_id",
            type: "string",
            description: "The market's conditionId (get this from predexon_markets or predexon_events)",
            required: true
          },
          {
            name: "limit",
            type: "number",
            description: "Number of positions to return (default: 20)",
            required: false
          }
        ],
        pricing: { perUnit: "$0.005", unit: "request", minimum: "$0.005", maximum: "$0.005" },
        example: {
          input: { condition_id: "0xabc123...", limit: 10 },
          description: "See smart money positioning on a specific market"
        }
      },
      {
        id: "predexon_smart_activity",
        name: "Polymarket Smart Activity",
        partner: "Predexon",
        category: "Prediction markets",
        shortDescription: "Where smart money is flowing now",
        description: "Discover which Polymarket markets high-performing wallets are currently active in. Use this to find where smart money is flowing right now. Returns: market titles, smart money volume, number of smart wallets active.",
        proxyPath: "/pm/polymarket/markets/smart-activity",
        method: "GET",
        params: [
          {
            name: "limit",
            type: "number",
            description: "Number of markets to return (default: 20)",
            required: false
          }
        ],
        pricing: { perUnit: "$0.005", unit: "request", minimum: "$0.005", maximum: "$0.005" },
        example: {
          input: { limit: 10 },
          description: "Find markets where smart money is most active"
        }
      },
      {
        id: "predexon_wallet",
        name: "Polymarket Wallet Profile",
        partner: "Predexon",
        category: "Prediction markets",
        shortDescription: "Wallet profile (PnL, winrate, positions)",
        description: "Get a complete profile for a Polymarket wallet address: profit, volume, win rate, markets traded, open positions. Use this when the user asks to analyze or look up a specific wallet address.",
        proxyPath: "/pm/polymarket/wallet/:wallet",
        method: "GET",
        params: [
          {
            name: "wallet",
            type: "string",
            description: "Ethereum wallet address (0x...)",
            required: true
          }
        ],
        pricing: { perUnit: "$0.005", unit: "request", minimum: "$0.005", maximum: "$0.005" },
        example: {
          input: { wallet: "0x1234...abcd" },
          description: "Get complete profile for a Polymarket wallet"
        }
      },
      {
        id: "predexon_wallet_pnl",
        name: "Polymarket Wallet P&L",
        partner: "Predexon",
        category: "Prediction markets",
        shortDescription: "Wallet P&L time series",
        description: "Get P&L history and realized profit/loss time series for a Polymarket wallet. Use this when the user wants to see how a wallet has performed over time.",
        proxyPath: "/pm/polymarket/wallet/pnl/:wallet",
        method: "GET",
        params: [
          {
            name: "wallet",
            type: "string",
            description: "Ethereum wallet address (0x...)",
            required: true
          }
        ],
        pricing: { perUnit: "$0.005", unit: "request", minimum: "$0.005", maximum: "$0.005" },
        example: {
          input: { wallet: "0x1234...abcd" },
          description: "Get P&L history for a Polymarket wallet"
        }
      },
      {
        id: "predexon_matching_markets",
        name: "Cross-Market Matching (Polymarket vs Kalshi)",
        partner: "Predexon",
        category: "Prediction markets",
        shortDescription: "Polymarket \u2194 Kalshi market pairs",
        description: "Find equivalent markets across Polymarket and Kalshi to compare odds and spot arbitrage. Use this when the user wants to compare prediction market prices across platforms.",
        proxyPath: "/pm/matching-markets",
        method: "GET",
        params: [
          {
            name: "limit",
            type: "number",
            description: "Number of matched pairs to return (default: 20)",
            required: false
          }
        ],
        pricing: { perUnit: "$0.005", unit: "request", minimum: "$0.005", maximum: "$0.005" },
        example: {
          input: { limit: 10 },
          description: "Compare equivalent markets on Polymarket vs Kalshi"
        }
      },
      {
        id: "predexon_endpoint_call",
        name: "Predexon Endpoint Call (Full Catalog)",
        partner: "Predexon",
        category: "Prediction markets",
        shortDescription: "Direct call to any Predexon endpoint",
        description: "Call ANY Predexon endpoint by path. Use this when the named predexon_* tools don't cover what you need (orderbooks, candlesticks, top-holders, UMA oracle, wallet identity/cluster, Kalshi/Limitless/Opinion/Predict.Fun, dFlow, Binance Futures, cross-venue canonical markets, sports). Default method=GET; pass method=POST with body for the bulk identities endpoint. Responses are raw upstream JSON (no { data: ... } wrapper as of v2 spec).\n\nPOLYMARKET \u2014 Tier 1 ($0.001/call):\n  /pm/polymarket/markets                       (search,limit,offset)\n  /pm/polymarket/markets/keyset                (cursor pagination)\n  /pm/polymarket/events                        (limit,offset,tag)\n  /pm/polymarket/events/keyset                 (cursor pagination)\n  /pm/polymarket/crypto-updown\n  /pm/polymarket/orderbooks                    (tokenId,limit)\n  /pm/polymarket/trades                        (wallet,limit,start_ts,end_ts)\n  /pm/polymarket/activity                      (user)\n  /pm/polymarket/positions                     (wallet,limit)\n  /pm/polymarket/leaderboard                   (limit,offset)\n  /pm/polymarket/leaderboard/market/{conditionId}\n  /pm/polymarket/cohorts/stats\n  /pm/polymarket/market/{conditionId}/top-holders\n  /pm/polymarket/market-price/{tokenId}\n  /pm/polymarket/candlesticks/{conditionId}\n  /pm/polymarket/candlesticks/token/{tokenId}\n  /pm/polymarket/volume-chart/{conditionId}\n  /pm/polymarket/markets/{tokenId}/volume\n  /pm/polymarket/markets/{conditionId}/open_interest\n  /pm/polymarket/uma/markets                   (state,limit,offset)\n  /pm/polymarket/uma/market/{conditionId}\n\nPOLYMARKET \u2014 Tier 2 ($0.005/call) wallet analytics:\n  /pm/polymarket/wallet/{wallet}\n  /pm/polymarket/wallet/{wallet}/markets\n  /pm/polymarket/wallet/{wallet}/similar\n  /pm/polymarket/wallet/pnl/{wallet}\n  /pm/polymarket/wallet/positions/{wallet}\n  /pm/polymarket/wallet/volume-chart/{wallet}\n  /pm/polymarket/wallets/profiles              (wallets=csv)\n  /pm/polymarket/wallets/filter                (conditionId,side)\n  /pm/polymarket/market/{conditionId}/smart-money\n  /pm/polymarket/markets/smart-activity\n\nPOLYMARKET \u2014 Wallet Identity (Tier 2, v2 path shapes):\n  /pm/polymarket/wallet/identity/{wallet}      (single \u2014 v2: path param, NOT ?wallet=)\n  POST /pm/polymarket/wallet/identities        (bulk, body: {addresses:[..]} \u2264200)\n  /pm/polymarket/wallet/{address}/cluster      (cluster \u2014 v2: address path param)\n\nCROSS-VENUE CANONICAL (Tier 1, v2):\n  /pm/markets                                  (canonical containers, cross-venue Predexon IDs)\n  /pm/markets/listings                         (venue-native flattened listings)\n  /pm/outcomes/{predexon_id}                   (resolve canonical outcome \u2192 market + venues)\n\nSPORTS (Tier 1, v2):\n  /pm/sports/categories\n  /pm/sports/markets                           (grouped by game)\n  /pm/sports/markets/{game_id}                 (single game with all venue outcomes)\n  /pm/sports/outcomes/{predexon_id}            (equivalent outcomes across venues)\n\nKALSHI (Tier 1):\n  /pm/kalshi/markets                           (search,limit)\n  /pm/kalshi/trades                            (limit)\n  /pm/kalshi/orderbooks                        (marketId)\n\nLIMITLESS / OPINION / PREDICT.FUN (Tier 1):\n  /pm/limitless/markets   |  /pm/limitless/orderbooks\n  /pm/opinion/markets     |  /pm/opinion/orderbooks\n  /pm/predictfun/markets  |  /pm/predictfun/orderbooks\n\nDFLOW (trades Tier 1, wallet Tier 2):\n  /pm/dflow/trades                             (wallet,limit)\n  /pm/dflow/wallet/positions/{wallet}\n  /pm/dflow/wallet/pnl/{wallet}\n\nBINANCE FUTURES (Tier 2):\n  /pm/binance/candles/{symbol}                 (interval,limit)\n  /pm/binance/ticks/{symbol}                   (limit)\n\nMATCHING (Tier 2):\n  /pm/matching-markets                         (limit,offset)\n  /pm/matching-markets/pairs\n  /pm/markets/search                           (q required, limit, offset, venue)",
        proxyPath: "/pm/__dynamic__",
        method: "GET",
        params: [
          {
            name: "path",
            type: "string",
            description: "Endpoint path under /v1/pm. Either the literal path (e.g. '/pm/polymarket/orderbooks') or with template segments substituted (e.g. '/pm/polymarket/wallet/identity/0xabc...'). Leading /v1 must NOT be included \u2014 proxy adds it.",
            required: true
          },
          {
            name: "method",
            type: "string",
            description: "HTTP method. Default 'GET'. Use 'POST' for /pm/polymarket/wallet/identities (bulk identity body).",
            required: false
          },
          {
            name: "query",
            type: "string",
            description: `JSON object of query parameters as a string, e.g. '{"limit":20,"search":"trump"}'. Encoded into URL query string. Used for GET requests.`,
            required: false
          },
          {
            name: "body",
            type: "string",
            description: `JSON object as a string, used as request body for POST. Example: '{"addresses":["0xabc","0xdef"]}' for bulk identities.`,
            required: false
          }
        ],
        pricing: {
          perUnit: "$0.001 or $0.005",
          unit: "request",
          minimum: "$0.001",
          maximum: "$0.005"
        },
        example: {
          input: { path: "/pm/polymarket/orderbooks", query: '{"tokenId":"0xabc...","limit":20}' },
          description: "Read a Polymarket orderbook by token id"
        }
      },
      // ---------------------------------------------------------------------------
      // BlockRun Markets — Realtime market data (stocks, crypto, FX, commodities)
      // ---------------------------------------------------------------------------
      {
        id: "stock_price",
        name: "Global Stock Realtime Price",
        partner: "BlockRun",
        category: "Market data",
        shortDescription: "Realtime stock quote (12 markets)",
        description: "Get realtime price for a listed equity across 12 global markets. Call this for ANY request about a specific stock price, quote, or current trading value on NYSE/Nasdaq, HKEX, TSE, KRX, LSE, XETRA, Euronext, Shanghai/Shenzhen, or Toronto. Do NOT use browser or web scraping \u2014 this returns structured real-time data directly. Returns: symbol, price, confidence interval, publish time, feed ID.",
        proxyPath: "/stocks/:market/price/:symbol",
        method: "GET",
        params: [
          {
            name: "market",
            type: "string",
            description: "Market code (lowercase): us (NYSE/Nasdaq/AMEX), hk (HKEX), jp (TSE), kr (KRX), gb (LSE), de (XETRA), fr (Euronext Paris), nl (Euronext Amsterdam), ie (Irish SE), lu (Luxembourg SE), cn (Shanghai/Shenzhen ETFs), ca (TSX).",
            required: true
          },
          {
            name: "symbol",
            type: "string",
            description: "Ticker for the given market. Examples: AAPL (us), 0700-HK (hk), 7203 (jp), 005930 (kr), HSBA (gb), SAP (de), MC (fr), AIR (nl), VUSA (ie), MT (lu), 510310 (cn), HODL (ca).",
            required: true
          },
          {
            name: "session",
            type: "string",
            description: "Optional session hint: pre, post, or on (regular hours).",
            required: false
          }
        ],
        pricing: { perUnit: "$0.001", unit: "request", minimum: "$0.001", maximum: "$0.001" },
        example: {
          input: { market: "us", symbol: "AAPL" },
          description: "Get realtime Apple stock price"
        }
      },
      {
        id: "stock_history",
        name: "Global Stock OHLC History",
        partner: "BlockRun",
        category: "Market data",
        shortDescription: "OHLC bars (1m\u2013monthly)",
        description: "Get historical OHLC (candlestick) bars for a listed equity across 12 global markets. Use this for charting, backtesting, or any request about a stock's past price action. Supports resolutions: 1, 5, 15, 60, 240 (minutes) and D, W, M (daily/weekly/monthly). Returns: OHLC arrays (open, high, low, close, volume, timestamps).",
        proxyPath: "/stocks/:market/history/:symbol",
        method: "GET",
        params: [
          {
            name: "market",
            type: "string",
            description: "Market code (lowercase): us, hk, jp, kr, gb, de, fr, nl, ie, lu, cn, ca. See stock_price for full market descriptions.",
            required: true
          },
          {
            name: "symbol",
            type: "string",
            description: "Ticker for the given market (e.g. AAPL for us, 0700-HK for hk).",
            required: true
          },
          {
            name: "resolution",
            type: "string",
            description: "Bar resolution: 1, 5, 15, 60, 240 (minutes) or D, W, M (daily/weekly/monthly). Default: D.",
            required: false
          },
          {
            name: "from",
            type: "number",
            description: "Start time as Unix epoch seconds (required).",
            required: true
          },
          {
            name: "to",
            type: "number",
            description: "End time as Unix epoch seconds. Default: now.",
            required: false
          }
        ],
        pricing: { perUnit: "$0.001", unit: "request", minimum: "$0.001", maximum: "$0.001" },
        example: {
          input: { market: "us", symbol: "AAPL", resolution: "D", from: 1704067200 },
          description: "Get daily OHLC bars for AAPL starting Jan 1 2024"
        }
      },
      {
        id: "stock_list",
        name: "Global Stock Ticker List",
        partner: "BlockRun",
        category: "Market data",
        shortDescription: "Ticker search \u2014 free",
        description: "List and search supported tickers for a given stock market. Use this to resolve a company name to a ticker before calling stock_price or stock_history. FREE \u2014 no x402 payment.",
        proxyPath: "/stocks/:market/list",
        method: "GET",
        params: [
          {
            name: "market",
            type: "string",
            description: "Market code: us, hk, jp, kr, gb, de, fr, nl, ie, lu, cn, ca.",
            required: true
          },
          {
            name: "q",
            type: "string",
            description: "Optional search query to filter tickers by symbol or description.",
            required: false
          },
          {
            name: "limit",
            type: "number",
            description: "Max results to return (default: 100, max: 2000).",
            required: false
          }
        ],
        pricing: { perUnit: "free", unit: "request", minimum: "$0", maximum: "$0" },
        example: {
          input: { market: "us", q: "apple", limit: 5 },
          description: "Search US market for 'apple' tickers"
        }
      },
      {
        id: "crypto_price",
        name: "Crypto Realtime Price",
        partner: "BlockRun",
        category: "Market data",
        shortDescription: "Realtime crypto price \u2014 free",
        description: "Get realtime crypto price. Call this for ANY request about current crypto prices (BTC, ETH, SOL, etc.). FREE \u2014 no x402 payment. Quote is always USD. Do NOT use browser or web scraping \u2014 this returns structured real-time data directly.",
        proxyPath: "/crypto/price/:symbol",
        method: "GET",
        params: [
          {
            name: "symbol",
            type: "string",
            description: "Crypto pair in BASE-QUOTE form. Examples: BTC-USD, ETH-USD, SOL-USD, DOGE-USD. Quote is always USD.",
            required: true
          }
        ],
        pricing: { perUnit: "free", unit: "request", minimum: "$0", maximum: "$0" },
        example: {
          input: { symbol: "BTC-USD" },
          description: "Get realtime Bitcoin price"
        }
      },
      {
        id: "fx_price",
        name: "Foreign Exchange Realtime Price",
        partner: "BlockRun",
        category: "Market data",
        shortDescription: "Realtime FX rate \u2014 free",
        description: "Get realtime FX rate. Call this for ANY request about currency exchange rates. FREE \u2014 no x402 payment. Do NOT use browser or web scraping.",
        proxyPath: "/fx/price/:symbol",
        method: "GET",
        params: [
          {
            name: "symbol",
            type: "string",
            description: "Currency pair in BASE-QUOTE form. Examples: EUR-USD, GBP-USD, JPY-USD, CNY-USD.",
            required: true
          }
        ],
        pricing: { perUnit: "free", unit: "request", minimum: "$0", maximum: "$0" },
        example: {
          input: { symbol: "EUR-USD" },
          description: "Get realtime EUR/USD exchange rate"
        }
      },
      {
        id: "commodity_price",
        name: "Commodity Realtime Price",
        partner: "BlockRun",
        category: "Market data",
        shortDescription: "Realtime commodity spot \u2014 free",
        description: "Get realtime commodity spot price (gold, silver, platinum, etc.). FREE \u2014 no x402 payment. Do NOT use browser or web scraping.",
        proxyPath: "/commodity/price/:symbol",
        method: "GET",
        params: [
          {
            name: "symbol",
            type: "string",
            description: "Commodity code in BASE-USD form. Examples: XAU-USD (gold), XAG-USD (silver), XPT-USD (platinum).",
            required: true
          }
        ],
        pricing: { perUnit: "free", unit: "request", minimum: "$0", maximum: "$0" },
        example: {
          input: { symbol: "XAU-USD" },
          description: "Get realtime gold spot price"
        }
      },
      // ---------------------------------------------------------------------------
      // BlockRun — Image & Video generation
      // ---------------------------------------------------------------------------
      {
        id: "image_generation",
        name: "Image Generation",
        partner: "BlockRun",
        category: "Image & Video",
        shortDescription: "8 image models (DALL-E, Flux, Grok, ...)",
        description: "Generate an image from a text prompt. Models available: google/nano-banana (default), google/nano-banana-pro (up to 4K), openai/gpt-image-1, openai/dall-e-3, black-forest/flux-1.1-pro, xai/grok-imagine-image, xai/grok-imagine-image-pro, zai/cogview-4. Returns a local http://localhost:8402/images/<file>.png URL.",
        proxyPath: "/images/generations",
        method: "POST",
        params: [
          {
            name: "prompt",
            type: "string",
            description: "Text prompt describing the desired image.",
            required: true
          },
          {
            name: "model",
            type: "string",
            description: "Full model ID (e.g. 'google/nano-banana', 'openai/dall-e-3'). Default: google/nano-banana.",
            required: false
          },
          {
            name: "size",
            type: "string",
            description: "Image size, e.g. '1024x1024', '1792x1024', '4096x4096'. Model-dependent \u2014 see image model table.",
            required: false
          },
          {
            name: "n",
            type: "number",
            description: "Number of images to generate (default 1, max 4).",
            required: false
          }
        ],
        pricing: {
          perUnit: "$0.015\u2013$0.15",
          unit: "image",
          minimum: "$0.015 (cogview-4)",
          maximum: "$0.15 (nano-banana-pro 4K)"
        },
        example: {
          input: { model: "google/nano-banana", prompt: "a golden retriever surfing on a wave" },
          description: "Generate an image with Nano Banana"
        }
      },
      {
        id: "image_edit",
        name: "Image Edit / Inpainting",
        partner: "BlockRun",
        category: "Image & Video",
        shortDescription: "Edit existing image (gpt-image-1)",
        description: "Edit or re-style an existing image via openai/gpt-image-1. Supply `image` as a data URI, https URL, or local file path; optional `mask` for inpainting.",
        proxyPath: "/images/image2image",
        method: "POST",
        params: [
          {
            name: "prompt",
            type: "string",
            description: "Text prompt describing how to edit the image.",
            required: true
          },
          {
            name: "image",
            type: "string",
            description: "Source image \u2014 data URI, https URL, or local path (~/... or /abs/path).",
            required: true
          },
          {
            name: "mask",
            type: "string",
            description: "Optional inpainting mask in the same formats as `image`.",
            required: false
          }
        ],
        pricing: {
          perUnit: "$0.02\u2013$0.04",
          unit: "image",
          minimum: "$0.02",
          maximum: "$0.04 (1536x1024)"
        },
        example: {
          input: { prompt: "make the sky sunset orange", image: "~/Pictures/beach.png" },
          description: "Edit a local image with gpt-image-1"
        }
      },
      {
        id: "video_generation",
        name: "Video Generation",
        partner: "BlockRun",
        category: "Image & Video",
        shortDescription: "Grok Imagine + Seedance, 5\u201310s (720p + audio on t2v)",
        description: "Generate a short video (5\u201310s) via xai/grok-imagine-video or bytedance/seedance-1.5-pro (default, cheapest) / seedance-2.0-fast / seedance-2.0. Seedance defaults to 720p with synced audio for text-to-video. Seedance 2.0 variants accept optional `real_face_asset_id` (`ta_xxxxxxxx`) for BytePlus RealFace character consistency \u2014 mutually exclusive with `image_url`. Async \u2014 upstream polling takes 30\u2013120 seconds. Returns a local http://localhost:8402/videos/<file>.mp4 URL.",
        proxyPath: "/videos/generations",
        method: "POST",
        params: [
          {
            name: "prompt",
            type: "string",
            description: "Text prompt describing the video.",
            required: true
          },
          {
            name: "model",
            type: "string",
            description: "Full model ID. Options: bytedance/seedance-1.5-pro (default), bytedance/seedance-2.0-fast, bytedance/seedance-2.0, xai/grok-imagine-video.",
            required: false
          },
          {
            name: "duration_seconds",
            type: "number",
            description: "Clip length in seconds. Supported: 5, 8, 10. Default depends on model.",
            required: false
          },
          {
            name: "image_url",
            type: "string",
            description: "Optional first-frame image URL for image-to-video. Cheaper per-token on 2.0 variants. Cannot be combined with `real_face_asset_id`.",
            required: false
          },
          {
            name: "real_face_asset_id",
            type: "string",
            description: "Optional BytePlus RealFace asset id (format `ta_xxxxxxxx`) for real-person character consistency across frames. Seedance 2.0 Fast / 2.0 Pro only \u2014 rejected on 1.5 Pro. Asset ids come from token360's H5 verification flow.",
            required: false
          }
        ],
        pricing: {
          perUnit: "$0.05\u2013$0.30",
          unit: "second",
          minimum: "$0.42 (grok-imagine-video 8s) / $0.46 (seedance-1.5-pro 5s)",
          maximum: "$2.98 (seedance-2.0 10s text-to-video)"
        },
        example: {
          input: { model: "bytedance/seedance-1.5-pro", prompt: "a cat waving", duration_seconds: 5 },
          description: "Generate a 5-second Seedance video (720p + audio defaults)"
        }
      },
      // ---------------------------------------------------------------------------
      // BlockRun — Phone & Voice (Twilio number intelligence + Bland.ai voice calls)
      // ---------------------------------------------------------------------------
      {
        id: "phone_lookup",
        name: "Phone Number Lookup",
        partner: "BlockRun (Twilio)",
        category: "Communications",
        shortDescription: "Carrier + line type for an E.164 number",
        description: "Look up carrier name, line type (mobile / landline / voip), and country for any phone number. Use to verify a phone number, detect VoIP/spam patterns, or route messages. Does NOT place a call \u2014 purely metadata. Returns: carrier name, line_type, country, mobile_country_code, mobile_network_code.",
        proxyPath: "/phone/lookup",
        method: "POST",
        params: [
          {
            name: "phoneNumber",
            type: "string",
            description: "Phone number in E.164 format, e.g. '+14155552671'.",
            required: true
          }
        ],
        pricing: { perUnit: "$0.01", unit: "lookup", minimum: "$0.01", maximum: "$0.01" },
        example: {
          input: { phoneNumber: "+14155552671" },
          description: "Check carrier and line type for a US number"
        }
      },
      {
        id: "phone_lookup_fraud",
        name: "Phone Fraud Risk Lookup",
        partner: "BlockRun (Twilio)",
        category: "Communications",
        shortDescription: "SIM swap + call-forwarding fraud signals",
        description: "Detect fraud signals on a phone number: SIM swap recency, call forwarding status, line-type-intelligence. Use BEFORE sending sensitive SMS codes or initiating account-recovery flows. Returns: carrier + line type (same as lookup) PLUS sim_swap.last_sim_swap and call_forwarding signals.",
        proxyPath: "/phone/lookup/fraud",
        method: "POST",
        params: [
          {
            name: "phoneNumber",
            type: "string",
            description: "Phone number in E.164 format, e.g. '+14155552671'.",
            required: true
          }
        ],
        pricing: { perUnit: "$0.05", unit: "lookup", minimum: "$0.05", maximum: "$0.05" },
        example: {
          input: { phoneNumber: "+14155552671" },
          description: "Check SIM-swap + forwarding fraud risk for an account-recovery candidate"
        }
      },
      {
        id: "phone_numbers_buy",
        name: "Provision Phone Number",
        partner: "BlockRun (Twilio)",
        category: "Communications",
        shortDescription: "Buy a US/CA number (30-day lease)",
        description: "Purchase a US or Canadian phone number tied to the wallet, leased for 30 days. Use only when the user has explicitly asked to acquire a phone number. Number is bound to the wallet's payer address and can be used as 'from' in voice_call. Returns: phone_number (E.164), expires_at (ISO), chain.",
        proxyPath: "/phone/numbers/buy",
        method: "POST",
        params: [
          {
            name: "country",
            type: "string",
            description: "Country code: 'US' or 'CA'.",
            required: true
          },
          {
            name: "areaCode",
            type: "string",
            description: "Optional 3-digit area code preference (e.g. '415'). Best-effort match.",
            required: false
          }
        ],
        pricing: { perUnit: "$5.00", unit: "number (30 days)", minimum: "$5.00", maximum: "$5.00" },
        example: {
          input: { country: "US", areaCode: "415" },
          description: "Buy a San Francisco area-code number for 30 days"
        }
      },
      {
        id: "phone_numbers_renew",
        name: "Renew Phone Number Lease",
        partner: "BlockRun (Twilio)",
        category: "Communications",
        shortDescription: "Extend a number's lease 30 days",
        description: "Extend an existing wallet-owned number's lease by 30 days. Use before expiry to keep the number; numbers not renewed are released back to the pool. Returns: phone_number, new expires_at (ISO).",
        proxyPath: "/phone/numbers/renew",
        method: "POST",
        params: [
          {
            name: "phoneNumber",
            type: "string",
            description: "E.164 number you currently own (from phone_numbers_list).",
            required: true
          }
        ],
        pricing: { perUnit: "$5.00", unit: "renewal (30 days)", minimum: "$5.00", maximum: "$5.00" },
        example: {
          input: { phoneNumber: "+14155551234" },
          description: "Extend a number's lease another 30 days"
        }
      },
      {
        id: "phone_numbers_list",
        name: "List Wallet's Phone Numbers",
        partner: "BlockRun (Twilio)",
        category: "Communications",
        shortDescription: "Wallet's active numbers + expiry",
        description: "List phone numbers currently owned by the calling wallet, with lease expiry timestamps. Use to see what numbers are available as 'from' in voice_call, or to decide which to renew/release. Returns: array of { phone_number, expires_at, country, chain }.",
        proxyPath: "/phone/numbers/list",
        method: "POST",
        params: [],
        pricing: { perUnit: "$0.001", unit: "request", minimum: "$0.001", maximum: "$0.001" },
        example: {
          input: {},
          description: "List all numbers owned by this wallet"
        }
      },
      {
        id: "phone_numbers_release",
        name: "Release Phone Number",
        partner: "BlockRun (Twilio)",
        category: "Communications",
        shortDescription: "Release a number (free)",
        description: "Release a wallet-owned phone number back to the pool before its lease expires. Use when the user explicitly asks to give up a number; no refund. Returns: { released: true, phone_number }.",
        proxyPath: "/phone/numbers/release",
        method: "POST",
        params: [
          {
            name: "phoneNumber",
            type: "string",
            description: "E.164 number you own (from phone_numbers_list).",
            required: true
          }
        ],
        pricing: { perUnit: "free", unit: "release", minimum: "$0", maximum: "$0" },
        example: {
          input: { phoneNumber: "+14155551234" },
          description: "Release a number"
        }
      },
      {
        id: "voice_call",
        name: "AI Voice Call (Outbound)",
        partner: "BlockRun (Bland.ai)",
        category: "Communications",
        shortDescription: "Bland.ai outbound call, up to 30 min",
        description: "Place a REAL outbound phone call via Bland.ai's AI agent. The agent speaks the supplied task, listens to the recipient, and produces a transcript + optional recording. \u26A0\uFE0F SAFETY: This places a real call to a real phone number \u2014 only invoke when the user has explicitly asked to place a call. Server enforces an emergency-number blocklist. Initiation is synchronous: returns { call_id, poll_url, status } immediately; the call itself runs in the cloud for up to 30 minutes. Poll via voice_status to retrieve transcript/recording.",
        proxyPath: "/voice/call",
        method: "POST",
        params: [
          {
            name: "to",
            type: "string",
            description: "Destination phone number in E.164 format (e.g. '+14155552671').",
            required: true
          },
          {
            name: "task",
            type: "string",
            description: "What the AI should say or accomplish during the call (free-form natural language).",
            required: true
          },
          {
            name: "from",
            type: "string",
            description: "Optional caller ID \u2014 must be a wallet-owned number from phone_numbers_list. If omitted, Bland.ai picks a default outbound number.",
            required: false
          },
          {
            name: "voice",
            type: "string",
            description: "Voice preset: nat (default), josh, maya, june, paige, derek, florian, or a custom Bland.ai voice ID.",
            required: false
          },
          {
            name: "max_duration",
            type: "number",
            description: "Maximum call length in minutes (1\u201330, default 5).",
            required: false
          },
          {
            name: "language",
            type: "string",
            description: "Spoken language ISO code, e.g. 'en-US' (default), 'es-ES', 'zh-CN'.",
            required: false
          }
        ],
        pricing: {
          perUnit: "$0.54",
          unit: "call (\u226430 min)",
          minimum: "$0.54",
          maximum: "$0.54"
        },
        example: {
          input: {
            to: "+14155552671",
            task: "Call and confirm the 3pm Thursday meeting; reschedule if they can't make it.",
            max_duration: 5
          },
          description: "Call to confirm an appointment"
        }
      },
      {
        id: "voice_status",
        name: "Voice Call Status",
        partner: "BlockRun (Bland.ai)",
        category: "Communications",
        shortDescription: "Poll status, transcript, recording",
        description: "Poll the status of a voice call placed via voice_call. Free \u2014 no x402 payment. Returns: status (queued|in_progress|completed|failed), transcript array, duration_seconds, recording_url (when completed), error (when failed). Poll every 10\u201330s while in_progress.",
        proxyPath: "/voice/call/:callId",
        method: "GET",
        params: [
          {
            name: "callId",
            type: "string",
            description: "Call ID returned by voice_call.",
            required: true
          }
        ],
        pricing: { perUnit: "free", unit: "poll", minimum: "$0", maximum: "$0" },
        example: {
          input: { callId: "call_abc123" },
          description: "Check on a placed call"
        }
      }
    ];
  }
});

// src/partners/tools.ts
function buildTool(service, proxyBaseUrl) {
  const properties = {};
  const required = [];
  for (const param of service.params) {
    const prop = {
      description: param.description
    };
    if (param.type === "string[]") {
      prop.type = "array";
      prop.items = { type: "string" };
    } else {
      prop.type = param.type;
    }
    properties[param.name] = prop;
    if (param.required) {
      required.push(param.name);
    }
  }
  return {
    name: `blockrun_${service.id}`,
    description: [
      service.description,
      "",
      `Partner: ${service.partner}`,
      `Pricing: ${service.pricing.perUnit} per ${service.pricing.unit} (min: ${service.pricing.minimum}, max: ${service.pricing.maximum})`
    ].join("\n"),
    parameters: {
      type: "object",
      properties,
      required
    },
    execute: async (_toolCallId, params) => {
      let path2;
      const leftoverParams = {};
      let dynamicMethod = "GET";
      let dynamicBody = void 0;
      if (service.proxyPath === "/pm/__dynamic__") {
        const rawPath = typeof params.path === "string" ? params.path : "";
        const normalized = rawPath.startsWith("/") ? rawPath : `/${rawPath}`;
        if (!normalized.startsWith("/pm/") || normalized.includes("..")) {
          throw new Error(
            `predexon_endpoint_call: invalid path '${rawPath}' \u2014 must begin with '/pm/' and contain no '..'`
          );
        }
        path2 = `/v1${normalized}`;
        if (typeof params.method === "string") {
          const upper = params.method.toUpperCase();
          if (upper !== "GET" && upper !== "POST") {
            throw new Error(
              `predexon_endpoint_call: method must be 'GET' or 'POST', got '${params.method}'`
            );
          }
          dynamicMethod = upper;
        }
        if (typeof params.query === "string" && params.query.trim().length > 0) {
          let parsed;
          try {
            parsed = JSON.parse(params.query);
          } catch (err) {
            throw new Error(
              `predexon_endpoint_call: query must be a JSON object string \u2014 ${err instanceof Error ? err.message : String(err)}`,
              { cause: err }
            );
          }
          if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
            for (const [key, value] of Object.entries(parsed)) {
              if (value === void 0 || value === null) continue;
              leftoverParams[key] = value;
            }
          }
        } else if (params.query && typeof params.query === "object" && !Array.isArray(params.query)) {
          for (const [key, value] of Object.entries(params.query)) {
            if (value === void 0 || value === null) continue;
            leftoverParams[key] = value;
          }
        }
        if (dynamicMethod === "POST") {
          if (typeof params.body === "string" && params.body.trim().length > 0) {
            try {
              dynamicBody = JSON.parse(params.body);
            } catch (err) {
              throw new Error(
                `predexon_endpoint_call: body must be a JSON object string \u2014 ${err instanceof Error ? err.message : String(err)}`,
                { cause: err }
              );
            }
          } else if (params.body && typeof params.body === "object") {
            dynamicBody = params.body;
          } else {
            dynamicBody = {};
          }
        }
      } else {
        path2 = `/v1${service.proxyPath}`;
        for (const [key, value] of Object.entries(params)) {
          if (value === void 0 || value === null) continue;
          const placeholder = `:${key}`;
          if (path2.includes(placeholder)) {
            path2 = path2.replace(placeholder, encodeURIComponent(String(value)));
          } else {
            leftoverParams[key] = value;
          }
        }
      }
      const effectiveMethod = service.proxyPath === "/pm/__dynamic__" ? dynamicMethod : service.method;
      let url = `${proxyBaseUrl}${path2}`;
      if (effectiveMethod === "GET" && Object.keys(leftoverParams).length > 0) {
        const qs = new URLSearchParams();
        for (const [key, value] of Object.entries(leftoverParams)) {
          qs.set(key, Array.isArray(value) ? value.join(",") : String(value));
        }
        url += `?${qs.toString()}`;
      }
      let requestBody;
      if (effectiveMethod === "POST") {
        if (service.proxyPath === "/pm/__dynamic__") {
          requestBody = JSON.stringify(dynamicBody ?? {});
        } else {
          requestBody = JSON.stringify(params);
        }
      }
      const response = await fetch(url, {
        method: effectiveMethod,
        headers: { "Content-Type": "application/json" },
        body: requestBody
      });
      if (!response.ok) {
        const errText = await response.text().catch(() => "");
        throw new Error(
          `Partner API error (${response.status}): ${errText || response.statusText}`
        );
      }
      const data = await response.json();
      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(data, null, 2)
          }
        ],
        details: data
      };
    }
  };
}
function buildPartnerTools(proxyBaseUrl) {
  return PARTNER_SERVICES.map((service) => buildTool(service, proxyBaseUrl));
}
var init_tools = __esm({
  "src/partners/tools.ts"() {
    "use strict";
    init_registry();
  }
});

// src/partners/index.ts
var init_partners = __esm({
  "src/partners/index.ts"() {
    "use strict";
    init_registry();
    init_tools();
  }
});

// src/provider.ts
function setActiveProxy(proxy) {
  activeProxy = proxy;
}
function getActiveProxy() {
  return activeProxy;
}
var activeProxy, blockrunProvider;
var init_provider = __esm({
  "src/provider.ts"() {
    "use strict";
    init_models();
    init_proxy();
    activeProxy = null;
    blockrunProvider = {
      id: "blockrun",
      label: "BlockRun",
      docsPath: "https://blockrun.ai/docs",
      aliases: ["br"],
      envVars: ["BLOCKRUN_WALLET_KEY"],
      // Model definitions — always point to local proxy URL.
      // Even before the proxy starts, we return the local URL so that OpenClaw's
      // async config persistence writes the correct baseUrl to openclaw.json.
      get models() {
        if (activeProxy) {
          return buildProviderModels(activeProxy.baseUrl);
        }
        const port = getProxyPort();
        return buildProviderModels(`http://127.0.0.1:${port}/v1`);
      },
      // No auth required — the x402 proxy handles wallet-based payments internally.
      // The proxy auto-generates a wallet on first run and stores it at
      // ~/.openclaw/blockrun/wallet.key. Users just fund that wallet with USDC.
      auth: []
    };
  }
});

// src/web-search-provider.ts
function getProxyBaseUrl() {
  return getActiveProxy()?.baseUrl ?? `http://127.0.0.1:${getProxyPort()}`;
}
function asObject(value) {
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
}
function readString(value) {
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
}
function readStringList(value) {
  if (Array.isArray(value)) {
    const items2 = value.map(readString).filter((item) => Boolean(item));
    return items2.length > 0 ? items2 : void 0;
  }
  const single = readString(value);
  if (!single) return void 0;
  const items = single.split(",").map((item) => item.trim()).filter(Boolean);
  return items.length > 0 ? items : void 0;
}
function readPositiveInteger(value) {
  if (typeof value === "number" && Number.isInteger(value) && value > 0) return value;
  if (typeof value === "string") {
    const parsed = Number.parseInt(value, 10);
    if (Number.isInteger(parsed) && parsed > 0) return parsed;
  }
  return void 0;
}
function errorPayload(error, message) {
  return {
    error,
    message,
    docs: BLOCKRUN_EXA_DOCS_URL
  };
}
function resolveSiteName(url) {
  try {
    return new URL(url).hostname.replace(/^www\./, "") || void 0;
  } catch {
    return void 0;
  }
}
function readResultString(entry, keys) {
  for (const key of keys) {
    const value = readString(entry[key]);
    if (value) return value;
  }
  return void 0;
}
function resolveDescription(entry) {
  const summary = readResultString(entry, ["summary", "description", "snippet", "excerpt"]);
  if (summary) return summary;
  const highlights = entry.highlights;
  if (Array.isArray(highlights)) {
    const text = highlights.map(readString).filter((item) => Boolean(item)).join("\n");
    if (text) return text;
  }
  return readResultString(entry, ["text", "content"]) ?? "";
}
function extractResults(payload) {
  if (Array.isArray(payload)) {
    return payload.map(asObject).filter((entry) => Boolean(entry));
  }
  const direct = asObject(payload);
  if (!direct) return [];
  const candidates = [
    direct.results,
    asObject(direct.data)?.results,
    asObject(direct.response)?.results
  ];
  for (const candidate of candidates) {
    if (!Array.isArray(candidate)) continue;
    return candidate.map(asObject).filter((entry) => Boolean(entry));
  }
  return [];
}
function normalizeBlockRunExaPayload(query, payload) {
  const results = extractResults(payload);
  return {
    query,
    provider: BLOCKRUN_EXA_PROVIDER_ID,
    count: results.length,
    externalContent: {
      untrusted: true,
      source: "web_search",
      provider: BLOCKRUN_EXA_PROVIDER_ID
    },
    results: results.map((entry) => {
      const title = readResultString(entry, ["title", "name"]) ?? "";
      const url = readResultString(entry, ["url", "uri", "link"]) ?? "";
      const summary = readResultString(entry, ["summary"]);
      const published = readResultString(entry, [
        "publishedDate",
        "published",
        "published_at",
        "date"
      ]);
      return {
        title,
        url,
        description: resolveDescription(entry),
        ...published ? { published } : {},
        ...summary ? { summary } : {},
        ...url ? { siteName: resolveSiteName(url) } : {}
      };
    })
  };
}
function ensureBlockrunExaSelection(config) {
  if (!config.tools || typeof config.tools !== "object" || Array.isArray(config.tools)) {
    config.tools = {};
  }
  const tools = config.tools;
  if (!tools.web || typeof tools.web !== "object" || Array.isArray(tools.web)) {
    tools.web = {};
  }
  const web = tools.web;
  if (!web.search || typeof web.search !== "object" || Array.isArray(web.search)) {
    web.search = {};
  }
  const search = web.search;
  search.provider = BLOCKRUN_EXA_PROVIDER_ID;
  search.enabled = true;
  return config;
}
async function runBlockrunExaSearch(args) {
  const query = readString(args.query);
  if (!query) {
    return errorPayload("missing_query", "web_search (blockrun-exa) requires a non-empty query.");
  }
  const count = Math.min(readPositiveInteger(args.count) ?? DEFAULT_RESULT_COUNT, MAX_RESULT_COUNT);
  const category = readString(args.category);
  const includeDomains = readStringList(args.include_domains) ?? readStringList(args.includeDomains) ?? readStringList(args.domains);
  const excludeDomains = readStringList(args.exclude_domains) ?? readStringList(args.excludeDomains);
  const requestBody = {
    query,
    numResults: count
  };
  if (category) requestBody.category = category;
  if (includeDomains) requestBody.includeDomains = includeDomains;
  if (excludeDomains) requestBody.excludeDomains = excludeDomains;
  try {
    const response = await fetch(`${getProxyBaseUrl()}${BLOCKRUN_EXA_SEARCH_PATH}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(requestBody)
    });
    if (!response.ok) {
      const details = await response.text().catch(() => "");
      return errorPayload(
        "blockrun_exa_error",
        `BlockRun Exa search failed (${response.status}): ${details || response.statusText}`
      );
    }
    const payload = await response.json();
    return normalizeBlockRunExaPayload(query, payload);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    return errorPayload("blockrun_exa_unavailable", `BlockRun Exa search failed: ${message}`);
  }
}
var BLOCKRUN_EXA_PROVIDER_ID, BLOCKRUN_EXA_SEARCH_PATH, BLOCKRUN_EXA_DOCS_URL, DEFAULT_RESULT_COUNT, MAX_RESULT_COUNT, blockrunExaWebSearchProvider;
var init_web_search_provider = __esm({
  "src/web-search-provider.ts"() {
    "use strict";
    init_provider();
    init_proxy();
    BLOCKRUN_EXA_PROVIDER_ID = "blockrun-exa";
    BLOCKRUN_EXA_SEARCH_PATH = "/v1/exa/search";
    BLOCKRUN_EXA_DOCS_URL = "https://blockrun.ai";
    DEFAULT_RESULT_COUNT = 5;
    MAX_RESULT_COUNT = 20;
    blockrunExaWebSearchProvider = {
      id: BLOCKRUN_EXA_PROVIDER_ID,
      label: "BlockRun Exa Search",
      hint: "Neural web search paid through your ClawRouter wallet",
      onboardingScopes: ["text-inference"],
      requiresCredential: false,
      envVars: [],
      placeholder: "(uses ClawRouter wallet)",
      signupUrl: "https://blockrun.ai",
      docsUrl: BLOCKRUN_EXA_DOCS_URL,
      autoDetectOrder: 5,
      credentialPath: "",
      inactiveSecretPaths: [],
      getCredentialValue: () => void 0,
      setCredentialValue: () => {
      },
      applySelectionConfig: ensureBlockrunExaSelection,
      createTool: () => ({
        description: "Search the web through BlockRun's Exa backend. Uses your ClawRouter wallet for x402 micropayments, so no Exa API key is required.",
        parameters: {
          type: "object",
          additionalProperties: false,
          properties: {
            query: {
              type: "string",
              description: "Natural-language search query."
            },
            count: {
              type: "integer",
              minimum: 1,
              maximum: MAX_RESULT_COUNT,
              description: `Number of results to return (1-${MAX_RESULT_COUNT}).`
            },
            category: {
              type: "string",
              description: "Optional Exa category filter such as news, company, github, pdf, or research paper."
            },
            domains: {
              type: "array",
              items: { type: "string" },
              description: "Only search within these domains."
            },
            include_domains: {
              type: "array",
              items: { type: "string" },
              description: "Alias for domains."
            },
            exclude_domains: {
              type: "array",
              items: { type: "string" },
              description: "Exclude these domains from results."
            }
          },
          required: ["query"]
        },
        execute: runBlockrunExaSearch
      })
    };
  }
});

// src/commands/stats.ts
function createStatsCommand() {
  return {
    name: "stats",
    description: "Show ClawRouter usage statistics and cost savings",
    acceptsArgs: true,
    requireAuth: false,
    handler: async (ctx) => {
      const arg = ctx.args?.trim().toLowerCase() || "7";
      if (arg === "clear" || arg === "reset") {
        try {
          const { deletedFiles } = await clearStats();
          return {
            text: `Stats cleared \u2014 ${deletedFiles} log file(s) deleted. Fresh start!`
          };
        } catch (err) {
          return {
            text: `Failed to clear stats: ${err instanceof Error ? err.message : String(err)}`,
            isError: true
          };
        }
      }
      const days = parseInt(arg, 10) || 7;
      try {
        const stats = await getStats(Math.min(days, 30));
        const ascii = formatStatsAscii(stats);
        return {
          text: ["```", ascii, "```"].join("\n")
        };
      } catch (err) {
        return {
          text: `Failed to load stats: ${err instanceof Error ? err.message : String(err)}`,
          isError: true
        };
      }
    }
  };
}
var init_stats2 = __esm({
  "src/commands/stats.ts"() {
    "use strict";
    init_stats();
  }
});

// src/commands/exclude.ts
function createExcludeCommand() {
  return {
    name: "exclude",
    description: "Manage excluded models \u2014 /exclude add|remove|clear <model>",
    acceptsArgs: true,
    requireAuth: true,
    handler: async (ctx) => {
      const args = ctx.args?.trim() || "";
      const parts = args.split(/\s+/);
      const subcommand = parts[0]?.toLowerCase() || "";
      const modelArg = parts.slice(1).join(" ").trim();
      if (!subcommand) {
        const list = loadExcludeList();
        if (list.size === 0) {
          return {
            text: "No models excluded.\n\nUsage:\n  /exclude add <model>  \u2014 block a model\n  /exclude remove <model> \u2014 unblock\n  /exclude clear \u2014 remove all"
          };
        }
        const models = [...list].sort().map((m) => `  \u2022 ${m}`).join("\n");
        return {
          text: `Excluded models (${list.size}):
${models}

Use /exclude remove <model> to unblock.`
        };
      }
      if (subcommand === "add") {
        if (!modelArg) {
          return {
            text: "Usage: /exclude add <model>\nExample: /exclude add nvidia/gpt-oss-120b",
            isError: true
          };
        }
        const resolved = addExclusion(modelArg);
        const list = loadExcludeList();
        return {
          text: `Excluded: ${resolved}

Active exclusions (${list.size}):
${[...list].sort().map((m) => `  \u2022 ${m}`).join("\n")}`
        };
      }
      if (subcommand === "remove") {
        if (!modelArg) {
          return { text: "Usage: /exclude remove <model>", isError: true };
        }
        const removed = removeExclusion(modelArg);
        if (!removed) {
          return { text: `Model "${modelArg}" was not in the exclude list.` };
        }
        const list = loadExcludeList();
        return {
          text: `Unblocked: ${modelArg}

Active exclusions (${list.size}):
${list.size > 0 ? [...list].sort().map((m) => `  \u2022 ${m}`).join("\n") : "  (none)"}`
        };
      }
      if (subcommand === "clear") {
        clearExclusions();
        return { text: "All model exclusions cleared." };
      }
      return {
        text: `Unknown subcommand: ${subcommand}

Usage:
  /exclude \u2014 show list
  /exclude add <model>
  /exclude remove <model>
  /exclude clear`,
        isError: true
      };
    }
  };
}
var init_exclude = __esm({
  "src/commands/exclude.ts"() {
    "use strict";
    init_exclude_models();
  }
});

// src/mcp-config.ts
function isRecord(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isStringArray(value) {
  return Array.isArray(value) && value.every((entry) => typeof entry === "string");
}
function looksLikeBlockrunPackageArgs(args) {
  return args.some((arg) => arg.startsWith("@blockrun/mcp"));
}
function looksLikeLocalBlockrunDistArgs(args) {
  return args.some((arg) => arg.replaceAll("\\", "/").endsWith("/blockrun-mcp/dist/index.js"));
}
function isManagedBlockrunMcpServerDefinition(value) {
  if (!isRecord(value)) return false;
  const args = isStringArray(value.args) ? value.args : [];
  if (typeof value.command === "string" && value.command === "npx") {
    return looksLikeBlockrunPackageArgs(args);
  }
  return looksLikeLocalBlockrunDistArgs(args);
}
function removeManagedBlockrunMcpServerConfig(config) {
  if (!config.mcp || typeof config.mcp !== "object" || Array.isArray(config.mcp)) {
    return false;
  }
  const mcp = config.mcp;
  if (!mcp.servers || typeof mcp.servers !== "object" || Array.isArray(mcp.servers)) {
    return false;
  }
  const servers = mcp.servers;
  if (!isManagedBlockrunMcpServerDefinition(servers[BLOCKRUN_MCP_SERVER_NAME])) {
    return false;
  }
  delete servers[BLOCKRUN_MCP_SERVER_NAME];
  if (Object.keys(servers).length === 0) {
    delete mcp.servers;
  }
  if (Object.keys(mcp).length === 0) {
    delete config.mcp;
  }
  return true;
}
var BLOCKRUN_MCP_SERVER_NAME;
var init_mcp_config = __esm({
  "src/mcp-config.ts"() {
    "use strict";
    BLOCKRUN_MCP_SERVER_NAME = "blockrun";
  }
});

// src/spend-control.ts
import * as fs from "fs";
import * as path from "path";
import { homedir as homedir7 } from "os";
function formatDuration(seconds) {
  if (seconds < 60) {
    return `${seconds}s`;
  } else if (seconds < 3600) {
    const mins = Math.ceil(seconds / 60);
    return `${mins} min`;
  } else {
    const hours = Math.floor(seconds / 3600);
    const mins = Math.ceil(seconds % 3600 / 60);
    return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
  }
}
var WALLET_DIR2, HOUR_MS, DAY_MS, FileSpendControlStorage, InMemorySpendControlStorage, SpendControl;
var init_spend_control = __esm({
  "src/spend-control.ts"() {
    "use strict";
    init_fs_read();
    WALLET_DIR2 = path.join(homedir7(), ".openclaw", "blockrun");
    HOUR_MS = 60 * 60 * 1e3;
    DAY_MS = 24 * HOUR_MS;
    FileSpendControlStorage = class {
      spendingFile;
      constructor() {
        this.spendingFile = path.join(WALLET_DIR2, "spending.json");
      }
      load() {
        try {
          if (fs.existsSync(this.spendingFile)) {
            const data = JSON.parse(readTextFileSync(this.spendingFile));
            const rawLimits = data.limits ?? {};
            const rawHistory = data.history ?? [];
            const limits = {};
            for (const key of ["perRequest", "hourly", "daily", "session"]) {
              const val = rawLimits[key];
              if (typeof val === "number" && val > 0 && Number.isFinite(val)) {
                limits[key] = val;
              }
            }
            const history = [];
            if (Array.isArray(rawHistory)) {
              for (const r of rawHistory) {
                if (typeof r?.timestamp === "number" && typeof r?.amount === "number" && Number.isFinite(r.timestamp) && Number.isFinite(r.amount) && r.amount >= 0) {
                  history.push({
                    timestamp: r.timestamp,
                    amount: r.amount,
                    model: typeof r.model === "string" ? r.model : void 0,
                    action: typeof r.action === "string" ? r.action : void 0
                  });
                }
              }
            }
            return { limits, history };
          }
        } catch (err) {
          console.error(`[ClawRouter] Failed to load spending data, starting fresh: ${err}`);
        }
        return null;
      }
      save(data) {
        try {
          if (!fs.existsSync(WALLET_DIR2)) {
            fs.mkdirSync(WALLET_DIR2, { recursive: true, mode: 448 });
          }
          fs.writeFileSync(this.spendingFile, JSON.stringify(data, null, 2), {
            mode: 384
          });
        } catch (err) {
          console.error(`[ClawRouter] Failed to save spending data: ${err}`);
        }
      }
    };
    InMemorySpendControlStorage = class {
      data = null;
      load() {
        return this.data ? {
          limits: { ...this.data.limits },
          history: this.data.history.map((r) => ({ ...r }))
        } : null;
      }
      save(data) {
        this.data = {
          limits: { ...data.limits },
          history: data.history.map((r) => ({ ...r }))
        };
      }
    };
    SpendControl = class {
      limits = {};
      history = [];
      sessionSpent = 0;
      sessionCalls = 0;
      storage;
      now;
      constructor(options) {
        this.storage = options?.storage ?? new FileSpendControlStorage();
        this.now = options?.now ?? (() => Date.now());
        this.load();
      }
      setLimit(window, amount) {
        if (!Number.isFinite(amount) || amount <= 0) {
          throw new Error("Limit must be a finite positive number");
        }
        this.limits[window] = amount;
        this.save();
      }
      clearLimit(window) {
        delete this.limits[window];
        this.save();
      }
      getLimits() {
        return { ...this.limits };
      }
      check(estimatedCost) {
        const now = this.now();
        if (this.limits.perRequest !== void 0) {
          if (estimatedCost > this.limits.perRequest) {
            return {
              allowed: false,
              blockedBy: "perRequest",
              remaining: this.limits.perRequest,
              reason: `Per-request limit exceeded: $${estimatedCost.toFixed(4)} > $${this.limits.perRequest.toFixed(2)} max`
            };
          }
        }
        if (this.limits.hourly !== void 0) {
          const hourlySpent = this.getSpendingInWindow(now - HOUR_MS, now);
          const remaining = this.limits.hourly - hourlySpent;
          if (estimatedCost > remaining) {
            const oldestInWindow = this.history.find((r) => r.timestamp >= now - HOUR_MS);
            const resetIn = oldestInWindow ? Math.ceil((oldestInWindow.timestamp + HOUR_MS - now) / 1e3) : 0;
            return {
              allowed: false,
              blockedBy: "hourly",
              remaining,
              reason: `Hourly limit exceeded: $${(hourlySpent + estimatedCost).toFixed(2)} > $${this.limits.hourly.toFixed(2)} max`,
              resetIn
            };
          }
        }
        if (this.limits.daily !== void 0) {
          const dailySpent = this.getSpendingInWindow(now - DAY_MS, now);
          const remaining = this.limits.daily - dailySpent;
          if (estimatedCost > remaining) {
            const oldestInWindow = this.history.find((r) => r.timestamp >= now - DAY_MS);
            const resetIn = oldestInWindow ? Math.ceil((oldestInWindow.timestamp + DAY_MS - now) / 1e3) : 0;
            return {
              allowed: false,
              blockedBy: "daily",
              remaining,
              reason: `Daily limit exceeded: $${(dailySpent + estimatedCost).toFixed(2)} > $${this.limits.daily.toFixed(2)} max`,
              resetIn
            };
          }
        }
        if (this.limits.session !== void 0) {
          const remaining = this.limits.session - this.sessionSpent;
          if (estimatedCost > remaining) {
            return {
              allowed: false,
              blockedBy: "session",
              remaining,
              reason: `Session limit exceeded: $${(this.sessionSpent + estimatedCost).toFixed(2)} > $${this.limits.session.toFixed(2)} max`
            };
          }
        }
        return { allowed: true };
      }
      record(amount, metadata) {
        if (!Number.isFinite(amount) || amount < 0) {
          throw new Error("Record amount must be a non-negative finite number");
        }
        const record = {
          timestamp: this.now(),
          amount,
          model: metadata?.model,
          action: metadata?.action
        };
        this.history.push(record);
        this.sessionSpent += amount;
        this.sessionCalls += 1;
        this.cleanup();
        this.save();
      }
      getSpendingInWindow(from14, to) {
        return this.history.filter((r) => r.timestamp >= from14 && r.timestamp <= to).reduce((sum, r) => sum + r.amount, 0);
      }
      getSpending(window) {
        const now = this.now();
        switch (window) {
          case "hourly":
            return this.getSpendingInWindow(now - HOUR_MS, now);
          case "daily":
            return this.getSpendingInWindow(now - DAY_MS, now);
          case "session":
            return this.sessionSpent;
        }
      }
      getRemaining(window) {
        const limit = this.limits[window];
        if (limit === void 0) return null;
        return Math.max(0, limit - this.getSpending(window));
      }
      getStatus() {
        const now = this.now();
        const hourlySpent = this.getSpendingInWindow(now - HOUR_MS, now);
        const dailySpent = this.getSpendingInWindow(now - DAY_MS, now);
        return {
          limits: { ...this.limits },
          spending: {
            hourly: hourlySpent,
            daily: dailySpent,
            session: this.sessionSpent
          },
          remaining: {
            hourly: this.limits.hourly !== void 0 ? this.limits.hourly - hourlySpent : null,
            daily: this.limits.daily !== void 0 ? this.limits.daily - dailySpent : null,
            session: this.limits.session !== void 0 ? this.limits.session - this.sessionSpent : null
          },
          calls: this.sessionCalls
        };
      }
      getHistory(limit) {
        const records = [...this.history].reverse();
        return limit ? records.slice(0, limit) : records;
      }
      resetSession() {
        this.sessionSpent = 0;
        this.sessionCalls = 0;
      }
      cleanup() {
        const cutoff = this.now() - DAY_MS;
        this.history = this.history.filter((r) => r.timestamp >= cutoff);
      }
      save() {
        this.storage.save({
          limits: { ...this.limits },
          history: [...this.history]
        });
      }
      load() {
        const data = this.storage.load();
        if (data) {
          this.limits = data.limits;
          this.history = data.history;
          this.cleanup();
        }
      }
    };
  }
});

// src/retry.ts
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
async function fetchWithRetry(fetchFn, url, init, config) {
  const cfg = {
    ...DEFAULT_RETRY_CONFIG,
    ...config
  };
  let lastError;
  let lastResponse;
  for (let attempt = 0; attempt <= cfg.maxRetries; attempt++) {
    try {
      const response = await fetchFn(url, init);
      if (!cfg.retryableCodes.includes(response.status)) {
        return response;
      }
      lastResponse = response;
      const retryAfter = response.headers.get("retry-after");
      let delay;
      if (retryAfter) {
        const seconds = parseInt(retryAfter, 10);
        delay = isNaN(seconds) ? cfg.baseDelayMs * Math.pow(2, attempt) : seconds * 1e3;
      } else {
        delay = cfg.baseDelayMs * Math.pow(2, attempt);
      }
      if (attempt < cfg.maxRetries) {
        await sleep(delay);
      }
    } catch (err) {
      lastError = err instanceof Error ? err : new Error(String(err));
      if (attempt < cfg.maxRetries) {
        const delay = cfg.baseDelayMs * Math.pow(2, attempt);
        await sleep(delay);
      }
    }
  }
  if (lastResponse) {
    return lastResponse;
  }
  throw lastError ?? new Error("Max retries exceeded");
}
function isRetryable(errorOrResponse, config) {
  const retryableCodes = config?.retryableCodes ?? DEFAULT_RETRY_CONFIG.retryableCodes;
  if (errorOrResponse instanceof Response) {
    return retryableCodes.includes(errorOrResponse.status);
  }
  const message = errorOrResponse.message.toLowerCase();
  return message.includes("network") || message.includes("timeout") || message.includes("econnreset") || message.includes("econnrefused") || message.includes("socket hang up");
}
var DEFAULT_RETRY_CONFIG;
var init_retry = __esm({
  "src/retry.ts"() {
    "use strict";
    DEFAULT_RETRY_CONFIG = {
      maxRetries: 2,
      baseDelayMs: 500,
      retryableCodes: [429, 502, 503, 504]
    };
  }
});

// src/index.ts
var index_exports = {};
__export(index_exports, {
  BALANCE_THRESHOLDS: () => BALANCE_THRESHOLDS,
  BLOCKRUN_MODELS: () => BLOCKRUN_MODELS,
  BalanceMonitor: () => BalanceMonitor,
  DEFAULT_RETRY_CONFIG: () => DEFAULT_RETRY_CONFIG,
  DEFAULT_ROUTING_CONFIG: () => DEFAULT_ROUTING_CONFIG,
  DEFAULT_SESSION_CONFIG: () => DEFAULT_SESSION_CONFIG,
  EmptyWalletError: () => EmptyWalletError,
  FileSpendControlStorage: () => FileSpendControlStorage,
  InMemorySpendControlStorage: () => InMemorySpendControlStorage,
  InsufficientFundsError: () => InsufficientFundsError2,
  MODEL_ALIASES: () => MODEL_ALIASES,
  OPENCLAW_MODELS: () => OPENCLAW_MODELS,
  PARTNER_SERVICES: () => PARTNER_SERVICES,
  RequestDeduplicator: () => RequestDeduplicator,
  ResponseCache: () => ResponseCache,
  RpcError: () => RpcError2,
  SessionStore: () => SessionStore,
  SolanaBalanceMonitor: () => SolanaBalanceMonitor,
  SpendControl: () => SpendControl,
  blockrunProvider: () => blockrunProvider,
  buildPartnerTools: () => buildPartnerTools,
  buildProviderModels: () => buildProviderModels,
  calculateModelCost: () => calculateModelCost,
  clearStats: () => clearStats,
  default: () => index_default2,
  deriveAllKeys: () => deriveAllKeys,
  deriveEvmKey: () => deriveEvmKey,
  deriveSolanaKeyBytes: () => deriveSolanaKeyBytes,
  fetchWithRetry: () => fetchWithRetry,
  formatDuration: () => formatDuration,
  formatStatsAscii: () => formatStatsAscii,
  generateWalletMnemonic: () => generateWalletMnemonic,
  getAgenticModels: () => getAgenticModels,
  getFallbackChain: () => getFallbackChain,
  getFallbackChainFiltered: () => getFallbackChainFiltered,
  getModelContextWindow: () => getModelContextWindow,
  getPartnerService: () => getPartnerService,
  getProxyPort: () => getProxyPort,
  getSessionId: () => getSessionId,
  getStats: () => getStats,
  hashRequestContent: () => hashRequestContent,
  injectAuthProfile: () => injectAuthProfile,
  injectModelsConfig: () => injectModelsConfig,
  isAgenticModel: () => isAgenticModel,
  isBalanceError: () => isBalanceError,
  isBlockrunWebSearchDisabled: () => isBlockrunWebSearchDisabled,
  isEmptyWalletError: () => isEmptyWalletError,
  isInsufficientFundsError: () => isInsufficientFundsError,
  isRetryable: () => isRetryable,
  isRpcError: () => isRpcError,
  isValidMnemonic: () => isValidMnemonic,
  loadPaymentChain: () => loadPaymentChain,
  logUsage: () => logUsage,
  parseCallArgs: () => parseCallArgs,
  resolveModelAlias: () => resolveModelAlias,
  resolvePaymentChain: () => resolvePaymentChain,
  route: () => route,
  savePaymentChain: () => savePaymentChain,
  setupSolana: () => setupSolana,
  startProxy: () => startProxy
});
import {
  writeFileSync as writeFileSync3,
  existsSync as existsSync4,
  readdirSync,
  mkdirSync as mkdirSync3,
  copyFileSync,
  renameSync
} from "fs";
import { readFile as readFileAsync } from "fs/promises";
import { homedir as homedir8 } from "os";
import { join as join11, dirname as dirname3 } from "path";
import { fileURLToPath as fileURLToPath2 } from "url";
async function waitForProxyHealth(port, timeoutMs = 3e3) {
  const start = Date.now();
  while (Date.now() - start < timeoutMs) {
    try {
      const res = await fetch(`http://127.0.0.1:${port}/health`);
      if (res.ok) return true;
    } catch {
    }
    await new Promise((r) => setTimeout(r, 100));
  }
  return false;
}
function getPackageRoot() {
  return join11(dirname3(fileURLToPath2(import.meta.url)), "..");
}
function installSkillsToWorkspace(logger) {
  try {
    const packageRoot = getPackageRoot();
    const bundledSkillsDir = join11(packageRoot, "skills");
    if (!existsSync4(bundledSkillsDir)) {
      return;
    }
    const profile = (process["env"].OPENCLAW_PROFILE ?? "").trim().toLowerCase();
    const workspaceDirName = profile && profile !== "default" ? `workspace-${profile}` : "workspace";
    const workspaceSkillsDir = join11(homedir8(), ".openclaw", workspaceDirName, "skills");
    mkdirSync3(workspaceSkillsDir, { recursive: true });
    const INTERNAL_SKILLS = /* @__PURE__ */ new Set(["release"]);
    const entries = readdirSync(bundledSkillsDir, { withFileTypes: true });
    let installed = 0;
    for (const entry of entries) {
      if (!entry.isDirectory()) continue;
      const skillName = entry.name;
      if (INTERNAL_SKILLS.has(skillName)) continue;
      const srcSkillFile = join11(bundledSkillsDir, skillName, "SKILL.md");
      if (!existsSync4(srcSkillFile)) continue;
      const destDir = join11(workspaceSkillsDir, skillName);
      const destSkillFile = join11(destDir, "SKILL.md");
      let needsUpdate = true;
      if (existsSync4(destSkillFile)) {
        try {
          const srcContent = readTextFileSync(srcSkillFile);
          const destContent = readTextFileSync(destSkillFile);
          if (srcContent === destContent) needsUpdate = false;
        } catch {
        }
      }
      if (needsUpdate) {
        mkdirSync3(destDir, { recursive: true });
        copyFileSync(srcSkillFile, destSkillFile);
        installed++;
      }
    }
    if (installed > 0) {
      logger.info(`Installed ${installed} skill(s) to ${workspaceSkillsDir}`);
    }
  } catch (err) {
    logger.warn(`Failed to install skills: ${err instanceof Error ? err.message : String(err)}`);
  }
}
function isCompletionMode() {
  const args = process.argv;
  return args.some((arg, i) => arg === "completion" && i >= 1 && i <= 3);
}
function isGatewayMode() {
  const args = process.argv;
  return args.includes("gateway");
}
function isBlockrunWebSearchDisabled(config) {
  if (process.env.BLOCKRUN_WEB_SEARCH?.toLowerCase() === "off") return true;
  const cfg = config ?? {};
  return cfg.tools?.web?.search?.enabled === false;
}
function injectModelsConfig(logger, options = {}) {
  const configDir = join11(homedir8(), ".openclaw");
  const configPath = join11(configDir, "openclaw.json");
  let config = {};
  let needsWrite = false;
  if (!existsSync4(configDir)) {
    try {
      mkdirSync3(configDir, { recursive: true });
      logger.info("Created OpenClaw config directory");
    } catch (err) {
      logger.info(
        `Failed to create config dir: ${err instanceof Error ? err.message : String(err)}`
      );
      return;
    }
  }
  if (existsSync4(configPath)) {
    try {
      const content = readTextFileSync(configPath).trim();
      if (content) {
        config = JSON.parse(content);
      } else {
        logger.info("OpenClaw config is empty, initializing");
        needsWrite = true;
      }
    } catch (err) {
      const backupPath = `${configPath}.backup.${Date.now()}`;
      try {
        copyFileSync(configPath, backupPath);
        logger.info(`Config parse failed, backed up to ${backupPath}`);
      } catch {
        logger.info("Config parse failed, could not create backup");
      }
      logger.info(
        `Skipping config injection (corrupt file): ${err instanceof Error ? err.message : String(err)}`
      );
      return;
    }
  } else {
    logger.info("OpenClaw config not found, creating");
    needsWrite = true;
  }
  if (!config.models) {
    config.models = {};
    needsWrite = true;
  }
  const models = config.models;
  if (!models.providers) {
    models.providers = {};
    needsWrite = true;
  }
  const proxyPort = getProxyPort();
  const expectedBaseUrl = `http://127.0.0.1:${proxyPort}/v1`;
  const providers = models.providers;
  if (!providers.blockrun) {
    providers.blockrun = {
      baseUrl: expectedBaseUrl,
      api: "openai-completions",
      // apiKey is required by pi-coding-agent's ModelRegistry for providers with models.
      // We use a placeholder since the proxy handles real x402 auth internally.
      apiKey: "x402-proxy-handles-auth",
      models: VISIBLE_OPENCLAW_MODELS
    };
    logger.info("Injected BlockRun provider config");
    needsWrite = true;
  } else {
    const blockrun = providers.blockrun;
    let fixed = false;
    if (!blockrun.baseUrl || blockrun.baseUrl !== expectedBaseUrl) {
      blockrun.baseUrl = expectedBaseUrl;
      fixed = true;
    }
    if (!blockrun.api) {
      blockrun.api = "openai-completions";
      fixed = true;
    }
    if (!blockrun.apiKey) {
      blockrun.apiKey = "x402-proxy-handles-auth";
      fixed = true;
    }
    const currentModels = blockrun.models;
    const currentModelIds = new Set(
      Array.isArray(currentModels) ? currentModels.map((m) => m?.id).filter((id) => typeof id === "string") : []
    );
    const expectedModelIds = VISIBLE_OPENCLAW_MODELS.map((m) => m.id);
    const expectedSet = new Set(expectedModelIds);
    const needsModelUpdate = !currentModels || !Array.isArray(currentModels) || currentModels.length !== VISIBLE_OPENCLAW_MODELS.length || expectedModelIds.some((id) => !currentModelIds.has(id)) || Array.from(currentModelIds).some((id) => !expectedSet.has(id));
    if (needsModelUpdate) {
      blockrun.models = VISIBLE_OPENCLAW_MODELS;
      fixed = true;
      logger.info(`Updated models list (${VISIBLE_OPENCLAW_MODELS.length} visible models)`);
    }
    if (fixed) {
      logger.info("Fixed incomplete BlockRun provider config");
      needsWrite = true;
    }
  }
  if (!config.agents) {
    config.agents = {};
    needsWrite = true;
  }
  const agents = config.agents;
  if (!agents.defaults) {
    agents.defaults = {};
    needsWrite = true;
  }
  const defaults = agents.defaults;
  if (!defaults.model || typeof defaults.model !== "object" || Array.isArray(defaults.model)) {
    const prev = typeof defaults.model === "string" ? defaults.model : void 0;
    defaults.model = prev ? { primary: prev } : {};
    needsWrite = true;
  }
  const model = defaults.model;
  if (!model.primary) {
    model.primary = "blockrun/auto";
    logger.info("Set default model to blockrun/auto (first install)");
    needsWrite = true;
  }
  if (!defaults.models || typeof defaults.models !== "object" || Array.isArray(defaults.models)) {
    defaults.models = {};
    needsWrite = true;
  }
  const allowlist = defaults.models;
  const DEPRECATED_BLOCKRUN_MODELS = ["blockrun/xai/grok-code-fast-1"];
  let removedDeprecatedCount = 0;
  for (const key of DEPRECATED_BLOCKRUN_MODELS) {
    if (allowlist[key]) {
      delete allowlist[key];
      removedDeprecatedCount++;
    }
  }
  if (removedDeprecatedCount > 0) {
    needsWrite = true;
    logger.info(`Removed ${removedDeprecatedCount} deprecated model entries from allowlist`);
  }
  const expectedBlockrunKeys = new Set(TOP_MODELS.map((id) => `blockrun/${id}`));
  let addedCount = 0;
  let prunedCount = 0;
  for (const key of Object.keys(allowlist)) {
    if (key.startsWith("blockrun/") && !expectedBlockrunKeys.has(key)) {
      delete allowlist[key];
      prunedCount++;
    }
  }
  for (const id of TOP_MODELS) {
    const key = `blockrun/${id}`;
    if (!allowlist[key]) {
      allowlist[key] = {};
      addedCount++;
    }
  }
  if (addedCount > 0 || prunedCount > 0) {
    needsWrite = true;
    if (prunedCount > 0) {
      logger.info(`Pruned ${prunedCount} stale blockrun/* entries from allowlist`);
    }
    if (addedCount > 0) {
      logger.info(`Added ${addedCount} models to allowlist (${TOP_MODELS.length} total)`);
    }
  }
  if (!config.tools || typeof config.tools !== "object" || Array.isArray(config.tools)) {
    config.tools = {};
    needsWrite = true;
  }
  const toolsCfg = config.tools;
  if (!toolsCfg.web || typeof toolsCfg.web !== "object" || Array.isArray(toolsCfg.web)) {
    toolsCfg.web = {};
    needsWrite = true;
  }
  const webCfg = toolsCfg.web;
  if (!webCfg.search || typeof webCfg.search !== "object" || Array.isArray(webCfg.search)) {
    webCfg.search = {};
    needsWrite = true;
  }
  const searchCfg = webCfg.search;
  if (searchCfg.provider === BLOCKRUN_EXA_PROVIDER_ID) {
    delete searchCfg.provider;
    needsWrite = true;
    logger.info(
      `Removed legacy tools.web.search.provider=${BLOCKRUN_EXA_PROVIDER_ID} (auto-detected at runtime now)`
    );
  }
  if (!isBlockrunWebSearchDisabled(config) && searchCfg.enabled !== true) {
    searchCfg.enabled = true;
    needsWrite = true;
  }
  if (removeManagedBlockrunMcpServerConfig(config)) {
    needsWrite = true;
    logger.info(
      `Removed bundled BlockRun MCP server config (${BLOCKRUN_MCP_SERVER_NAME}) \u2014 restart the gateway to free any leaked processes`
    );
  }
  if (needsWrite) {
    if (!isGatewayMode() && !options.forceWrite) {
      logger.info("Deferring config write to first gateway start (outside gateway mode)");
      return;
    }
    try {
      const tmpPath = `${configPath}.tmp.${process.pid}`;
      writeFileSync3(tmpPath, JSON.stringify(config, null, 2));
      renameSync(tmpPath, configPath);
      logger.info("Smart routing enabled (blockrun/auto)");
    } catch (err) {
      logger.info(`Failed to write config: ${err instanceof Error ? err.message : String(err)}`);
    }
  }
}
function injectAuthProfile(logger) {
  const agentsDir = join11(homedir8(), ".openclaw", "agents");
  if (!existsSync4(agentsDir)) {
    try {
      mkdirSync3(agentsDir, { recursive: true });
    } catch (err) {
      logger.info(
        `Could not create agents dir: ${err instanceof Error ? err.message : String(err)}`
      );
      return;
    }
  }
  try {
    let agents = readdirSync(agentsDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
    if (!agents.includes("main")) {
      agents = ["main", ...agents];
    }
    for (const agentId of agents) {
      const authDir = join11(agentsDir, agentId, "agent");
      const authPath = join11(authDir, "auth-profiles.json");
      if (!existsSync4(authDir)) {
        try {
          mkdirSync3(authDir, { recursive: true });
        } catch {
          continue;
        }
      }
      let store = {
        version: 1,
        profiles: {}
      };
      if (existsSync4(authPath)) {
        try {
          const existing = JSON.parse(readTextFileSync(authPath));
          if (existing.version && existing.profiles) {
            store = existing;
          }
        } catch {
        }
      }
      const profileKey = "blockrun:default";
      if (store.profiles[profileKey]) {
        continue;
      }
      store.profiles[profileKey] = {
        type: "api_key",
        provider: "blockrun",
        key: "x402-proxy-handles-auth"
      };
      try {
        writeFileSync3(authPath, JSON.stringify(store, null, 2));
        logger.info(`Injected BlockRun auth profile for agent: ${agentId}`);
      } catch (err) {
        logger.info(
          `Could not inject auth for ${agentId}: ${err instanceof Error ? err.message : String(err)}`
        );
      }
    }
  } catch (err) {
    logger.info(`Auth injection failed: ${err instanceof Error ? err.message : String(err)}`);
  }
}
function clearDeferredProxyStartTimer(proc = process) {
  if (!proc.__clawrouterDeferredStartTimer) return false;
  clearTimeout(proc.__clawrouterDeferredStartTimer);
  proc.__clawrouterDeferredStartTimer = void 0;
  return true;
}
function beginProxyStartupAttempt(proc = process, startedWithEmptyConfig = false) {
  const generation = (proc.__clawrouterStartupGeneration ?? 0) + 1;
  proc.__clawrouterStartupGeneration = generation;
  proc.__clawrouterProxyStarted = true;
  proc.__clawrouterStartedWithEmptyConfig = startedWithEmptyConfig;
  proc.__clawrouterStartupPhase = "probing";
  return generation;
}
function isProxyStartupCurrent(generation, proc = process) {
  return proc.__clawrouterStartupGeneration === generation && proc.__clawrouterProxyStarted === true;
}
function resetProxyStartupState() {
  const proc = process;
  clearDeferredProxyStartTimer(proc);
  pendingConfiguredStartupApi = null;
  proc.__clawrouterStartupGeneration = (proc.__clawrouterStartupGeneration ?? 0) + 1;
  proc.__clawrouterProxyStarted = false;
  proc.__clawrouterStartedWithEmptyConfig = false;
  proc.__clawrouterStartupPhase = "idle";
  setActiveProxy(null);
}
function startPendingConfiguredProxyIfQueued(proc = process) {
  if (!pendingConfiguredStartupApi) return false;
  if (proc.__clawrouterProxyStarted || activeProxyHandle) {
    pendingConfiguredStartupApi = null;
    return false;
  }
  const api = pendingConfiguredStartupApi;
  pendingConfiguredStartupApi = null;
  const generation = beginProxyStartupAttempt(proc, false);
  api.logger.info("Starting proxy with populated pluginConfig");
  startProxyAfterPortProbe(api, generation);
  return true;
}
function resumePendingConfiguredProxyAfterStaleFailure(proc = process) {
  if (!pendingConfiguredStartupApi) return false;
  if (proc.__clawrouterProxyStarted || activeProxyHandle) return false;
  proc.__clawrouterStartupPhase = "idle";
  return startPendingConfiguredProxyIfQueued(proc);
}
function supersedeEmptyConfigStartup(api) {
  const proc = process;
  pendingConfiguredStartupApi = api;
  proc.__clawrouterStartupGeneration = (proc.__clawrouterStartupGeneration ?? 0) + 1;
  proc.__clawrouterProxyStarted = false;
  proc.__clawrouterStartedWithEmptyConfig = false;
  if (activeProxyHandle) {
    const oldHandle = activeProxyHandle;
    activeProxyHandle = null;
    setActiveProxy(null);
    proc.__clawrouterStartupPhase = "idle";
    void oldHandle.close().catch(() => {
    }).finally(() => {
      startPendingConfiguredProxyIfQueued(proc);
    });
    return;
  }
  if (proc.__clawrouterStartupPhase === "starting") {
    api.logger.info(
      "Populated pluginConfig arrived during provisional startup \u2014 queued restart with current config"
    );
    return;
  }
  proc.__clawrouterStartupPhase = "idle";
  startPendingConfiguredProxyIfQueued(proc);
}
async function startProxyInBackground(api, startupGeneration) {
  const proc = process;
  if (startupGeneration !== void 0 && isProxyStartupCurrent(startupGeneration, proc)) {
    proc.__clawrouterStartupPhase = "starting";
  }
  const configKey = api.pluginConfig?.walletKey;
  let wallet;
  if (typeof configKey === "string" && /^0x[0-9a-fA-F]{64}$/.test(configKey)) {
    const account = privateKeyToAccount(configKey);
    wallet = { key: configKey, address: account.address, source: "config" };
  } else {
    if (configKey !== void 0) {
      api.logger.warn(
        `pluginConfig.walletKey is set but invalid (expected 0x + 64 hex chars) \u2014 falling back to saved wallet`
      );
    }
    wallet = await resolveOrGenerateWalletKey();
  }
  if (wallet.source === "generated") {
    api.logger.warn(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`);
    api.logger.warn(`  NEW WALLET GENERATED \u2014 BACK UP YOUR KEY NOW!`);
    api.logger.warn(`  Address : ${wallet.address}`);
    api.logger.warn(`  Run /wallet export to get your private key`);
    api.logger.warn(`  Losing this key = losing your USDC funds`);
    api.logger.warn(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`);
  } else if (wallet.source === "saved") {
    api.logger.info(`Using saved wallet: ${wallet.address}`);
  } else if (wallet.source === "config") {
    api.logger.info(`Using wallet from plugin config: ${wallet.address}`);
  } else {
    api.logger.info(`Using wallet from BLOCKRUN_WALLET_KEY: ${wallet.address}`);
  }
  const routingConfig = api.pluginConfig?.routing;
  const maxCostPerRunUsd = typeof api.pluginConfig?.maxCostPerRun === "number" ? api.pluginConfig.maxCostPerRun : void 0;
  const maxCostPerRunMode = api.pluginConfig?.maxCostPerRunMode === "strict" ? "strict" : "graceful";
  if (maxCostPerRunUsd !== void 0) {
    api.logger.info(
      `Cost cap: $${maxCostPerRunUsd.toFixed(2)} per session (mode: ${maxCostPerRunMode})`
    );
  }
  const proxy = await startProxy({
    wallet,
    routingConfig,
    maxCostPerRunUsd,
    maxCostPerRunMode,
    onReady: (port) => {
      api.logger.info(`BlockRun x402 proxy listening on port ${port}`);
    },
    onError: (error) => {
      api.logger.error(`BlockRun proxy error: ${error.message}`);
    },
    onRouted: (decision) => {
      const cost = decision.costEstimate.toFixed(4);
      const saved = (decision.savings * 100).toFixed(0);
      api.logger.info(
        `[${decision.tier}] ${decision.model} $${cost} (saved ${saved}%) | ${decision.reasoning}`
      );
    },
    onLowBalance: (info) => {
      api.logger.warn(`[!] Low balance: ${info.balanceUSD}. Fund wallet: ${info.walletAddress}`);
    },
    onInsufficientFunds: (info) => {
      api.logger.error(
        `[!] Insufficient funds. Balance: ${info.balanceUSD}, Needed: ${info.requiredUSD}. Fund wallet: ${info.walletAddress}`
      );
    }
  });
  if (startupGeneration !== void 0 && !isProxyStartupCurrent(startupGeneration)) {
    try {
      await proxy.close();
    } catch {
    }
    proc.__clawrouterStartupPhase = "idle";
    startPendingConfiguredProxyIfQueued(proc);
    return false;
  }
  setActiveProxy(proxy);
  activeProxyHandle = proxy;
  proc.__clawrouterStartupPhase = "running";
  const startupExclusions = loadExcludeList();
  if (startupExclusions.size > 0) {
    api.logger.info(
      `Model exclusions active (${startupExclusions.size}): ${[...startupExclusions].join(", ")}`
    );
  }
  api.logger.info(`ClawRouter ready \u2014 smart routing enabled`);
  api.logger.info(`Pricing: Simple ~$0.001 | Code ~$0.01 | Complex ~$0.05 | Free: $0`);
  const currentChain = await resolvePaymentChain();
  const displayAddress = currentChain === "solana" && proxy.solanaAddress ? proxy.solanaAddress : wallet.address;
  const network = currentChain === "solana" ? "Solana" : "Base";
  proxy.balanceMonitor.checkBalance().then(async (balance) => {
    if (balance.isEmpty) {
      api.logger.info(`Wallet (${network}): ${displayAddress}`);
      api.logger.info(
        `Balance: $0.00 \u2014 send USDC on ${network} to the address above to unlock paid models.`
      );
    } else if (balance.isLow) {
      api.logger.info(
        `Wallet (${network}): ${displayAddress} | Balance: ${balance.balanceUSD} (low \u2014 top up soon)`
      );
    } else {
      api.logger.info(`Wallet (${network}): ${displayAddress} | Balance: ${balance.balanceUSD}`);
    }
    if (currentChain === "solana" && (balance.isEmpty || balance.isLow)) {
      try {
        const solLamports = await proxy.balanceMonitor.checkSolBalance();
        if (solLamports > 10000000n) {
          const sol = Number(solLamports) / 1e9;
          api.logger.info(
            `You have ${sol.toFixed(2)} SOL \u2014 swap to USDC: https://jup.ag/swap/SOL-USDC`
          );
        }
      } catch {
      }
    }
  }).catch(() => {
    api.logger.info(`Wallet (${network}): ${displayAddress} | Balance: (checking...)`);
  });
  return true;
}
function startProxyAfterPortProbe(api, startupGeneration) {
  const proxyPort = getProxyPort();
  const portProbe = import("net").then(
    (net) => new Promise((resolve) => {
      const sock = net.connect({ host: "127.0.0.1", port: proxyPort }, () => {
        sock.destroy();
        resolve(true);
      });
      sock.on("error", () => resolve(false));
      sock.setTimeout(500, () => {
        sock.destroy();
        resolve(false);
      });
    })
  );
  portProbe.then((portInUse) => {
    if (!isProxyStartupCurrent(startupGeneration)) {
      return;
    }
    if (portInUse) {
      resetProxyStartupState();
      api.logger.info(
        `Port ${proxyPort} already in use \u2014 skipping proxy startup (another instance running)`
      );
      return;
    }
    return startProxyInBackground(api, startupGeneration).then(async (started) => {
      if (!started || !isProxyStartupCurrent(startupGeneration)) {
        return;
      }
      const port = getProxyPort();
      const healthy = await waitForProxyHealth(port, 15e3);
      if (!healthy && isProxyStartupCurrent(startupGeneration)) {
        api.logger.warn(`Proxy health check timed out, commands may not work immediately`);
      }
    });
  }).catch((err) => {
    if (isProxyStartupCurrent(startupGeneration)) {
      resetProxyStartupState();
    } else {
      resumePendingConfiguredProxyAfterStaleFailure();
    }
    api.logger.error(
      `Failed to start BlockRun proxy: ${err instanceof Error ? err.message : String(err)}`
    );
  });
}
function parseCallArgs(raw) {
  let to;
  let voice;
  let from14;
  let language;
  let max_duration;
  const taskParts = [];
  const tokens = raw.trim().match(/"[^"]*"|\S+/g) ?? [];
  for (let i = 0; i < tokens.length; i++) {
    const raw2 = tokens[i];
    const tok = raw2.startsWith('"') && raw2.endsWith('"') ? raw2.slice(1, -1) : raw2;
    const eqMatch = tok.match(/^--(voice|max-duration|max_duration|from|language|lang)=(.+)$/);
    if (eqMatch) {
      const [, key, value] = eqMatch;
      if (key === "voice") voice = value;
      else if (key === "max-duration" || key === "max_duration") max_duration = Number(value);
      else if (key === "from") from14 = value;
      else if (key === "language" || key === "lang") language = value;
      continue;
    }
    const spaceMatch = tok.match(/^--(voice|max-duration|max_duration|from|language|lang)$/);
    if (spaceMatch) {
      const next = tokens[i + 1];
      if (next !== void 0) {
        const value = next.startsWith('"') && next.endsWith('"') ? next.slice(1, -1) : next;
        const key = spaceMatch[1];
        if (key === "voice") voice = value;
        else if (key === "max-duration" || key === "max_duration") max_duration = Number(value);
        else if (key === "from") from14 = value;
        else if (key === "language" || key === "lang") language = value;
        i++;
      }
      continue;
    }
    if (!to && /^\+\d{6,15}$/.test(tok)) {
      to = tok;
      continue;
    }
    taskParts.push(tok);
  }
  return {
    to,
    task: taskParts.join(" ").trim(),
    voice,
    from: from14,
    language,
    ...Number.isFinite(max_duration) ? { max_duration } : {}
  };
}
function parseGenArgs(raw) {
  const promptParts = [];
  let model;
  let size5;
  let n;
  let duration;
  const tokens = raw.trim().match(/(?:[^\s"]+|"[^"]*")+/g) ?? [];
  for (const tok of tokens) {
    const t = tok.startsWith('"') && tok.endsWith('"') ? tok.slice(1, -1) : tok;
    const flagMatch = t.match(/^--(model|size|n|count|duration|duration_seconds)=(.+)$/);
    if (flagMatch) {
      const [, key, value] = flagMatch;
      if (key === "model") model = value;
      else if (key === "size") size5 = value;
      else if (key === "n" || key === "count") n = Number(value);
      else if (key === "duration" || key === "duration_seconds") duration = Number(value);
      continue;
    }
    promptParts.push(t);
  }
  return {
    prompt: promptParts.join(" ").trim(),
    model,
    size: size5,
    ...Number.isFinite(n) ? { n } : {},
    ...Number.isFinite(duration) ? { duration } : {}
  };
}
function buildImageGenerationProvider() {
  return {
    id: "blockrun",
    label: "BlockRun",
    defaultModel: "google/nano-banana",
    models: [
      "google/nano-banana",
      "google/nano-banana-pro",
      "openai/gpt-image-1",
      "openai/dall-e-3",
      "black-forest/flux-1.1-pro",
      "xai/grok-imagine-image",
      "xai/grok-imagine-image-pro",
      "zai/cogview-4"
    ],
    capabilities: {
      generate: {
        maxCount: 1,
        supportsSize: true,
        supportsAspectRatio: false,
        supportsResolution: false
      },
      // Only openai/gpt-image-1 supports edit server-side; OpenClaw's UI picks a
      // compatible model at edit time via /v1/images/image2image.
      edit: { enabled: true },
      geometry: {
        sizes: [
          "512x512",
          "768x768",
          "768x1344",
          "1024x1024",
          "1216x832",
          "1344x768",
          "1440x1440",
          "1536x1024",
          "1024x1536",
          "1792x1024",
          "1024x1792",
          "2048x2048",
          "4096x4096"
        ]
      }
    },
    isConfigured: () => existsSync4(WALLET_FILE),
    generateImage: async (req) => {
      const port = getProxyPort();
      const body = JSON.stringify({
        model: req.model,
        prompt: req.prompt,
        size: req.size ?? "1024x1024",
        n: req.count ?? 1
      });
      const resp = await fetch(`http://127.0.0.1:${port}/v1/images/generations`, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body,
        signal: req.timeoutMs ? AbortSignal.timeout(req.timeoutMs) : void 0
      });
      if (!resp.ok) {
        const errText = await resp.text().catch(() => "");
        throw new Error(`BlockRun image generation failed (${resp.status}): ${errText}`);
      }
      const result = await resp.json();
      const images = await Promise.all(
        (result.data ?? []).map(async (img) => {
          const filename = img.url?.split("/images/").pop();
          if (!filename) throw new Error(`Unexpected image URL format: ${img.url}`);
          const filePath = join11(IMAGE_DIR2, filename);
          const buffer2 = await readFileAsync(filePath);
          const ext = filename.split(".").pop()?.toLowerCase() ?? "png";
          const mimeType = ext === "jpg" || ext === "jpeg" ? "image/jpeg" : ext === "webp" ? "image/webp" : "image/png";
          return { buffer: buffer2, mimeType, fileName: filename, revisedPrompt: img.revised_prompt };
        })
      );
      return { images, model: result.model ?? req.model };
    }
  };
}
function buildMusicGenerationProvider() {
  return {
    id: "blockrun",
    label: "BlockRun",
    defaultModel: "minimax/music-2.5+",
    models: ["minimax/music-2.5+", "minimax/music-2.5"],
    capabilities: {
      maxTracks: 1,
      maxDurationSeconds: 240,
      supportsLyrics: true,
      supportsInstrumental: true,
      supportsDuration: true,
      supportsFormat: true,
      supportedFormats: ["mp3"]
    },
    isConfigured: () => existsSync4(WALLET_FILE),
    generateMusic: async (req) => {
      const port = getProxyPort();
      const body = JSON.stringify({
        model: req.model,
        prompt: req.prompt,
        ...req.lyrics ? { lyrics: req.lyrics } : {},
        ...req.instrumental !== void 0 ? { instrumental: req.instrumental } : {},
        ...req.durationSeconds ? { duration_seconds: req.durationSeconds } : {}
      });
      const timeoutMs = req.timeoutMs ?? 2e5;
      const resp = await fetch(`http://127.0.0.1:${port}/v1/audio/generations`, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body,
        signal: AbortSignal.timeout(timeoutMs)
      });
      if (!resp.ok) {
        const errText = await resp.text().catch(() => "");
        throw new Error(`BlockRun music generation failed (${resp.status}): ${errText}`);
      }
      const result = await resp.json();
      const tracks = await Promise.all(
        (result.data ?? []).map(async (track) => {
          const filename = track.url?.split("/audio/").pop();
          if (!filename) throw new Error(`Unexpected audio URL format: ${track.url}`);
          const filePath = join11(AUDIO_DIR2, filename);
          const buffer2 = await readFileAsync(filePath);
          const ext = filename.split(".").pop()?.toLowerCase() ?? "mp3";
          const mimeType = ext === "wav" ? "audio/wav" : "audio/mpeg";
          return {
            buffer: buffer2,
            mimeType,
            fileName: filename,
            metadata: {
              ...track.duration_seconds ? { duration_seconds: track.duration_seconds } : {},
              ...track.lyrics ? { lyrics: track.lyrics } : {}
            }
          };
        })
      );
      const allLyrics = (result.data ?? []).map((t) => t.lyrics).filter((l2) => Boolean(l2));
      return {
        tracks,
        model: result.model ?? req.model,
        lyrics: allLyrics.length ? allLyrics : void 0
      };
    }
  };
}
function buildVideoGenerationProvider() {
  return {
    id: "blockrun",
    label: "BlockRun",
    defaultModel: "xai/grok-imagine-video",
    models: [
      "xai/grok-imagine-video",
      "bytedance/seedance-1.5-pro",
      "bytedance/seedance-2.0-fast",
      "bytedance/seedance-2.0"
    ],
    capabilities: {
      maxVideos: 1,
      maxInputImages: 1,
      maxDurationSeconds: 10,
      supportedDurationSeconds: [5, 8, 10],
      supportsAudio: false,
      imageToVideo: {
        enabled: true,
        maxInputImages: 1,
        maxDurationSeconds: 10,
        supportedDurationSeconds: [5, 8, 10]
      }
    },
    isConfigured: () => existsSync4(WALLET_FILE),
    generateVideo: async (req) => {
      const port = getProxyPort();
      const imageUrl = req.inputImages?.[0]?.url;
      const body = JSON.stringify({
        model: req.model,
        prompt: req.prompt,
        ...imageUrl ? { image_url: imageUrl } : {},
        ...req.durationSeconds ? { duration_seconds: req.durationSeconds } : {}
      });
      const timeoutMs = req.timeoutMs ?? 33e4;
      const resp = await fetch(`http://127.0.0.1:${port}/v1/videos/generations`, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body,
        signal: AbortSignal.timeout(timeoutMs)
      });
      if (!resp.ok) {
        const errText = await resp.text().catch(() => "");
        throw new Error(`BlockRun video generation failed (${resp.status}): ${errText}`);
      }
      const result = await resp.json();
      const videos = await Promise.all(
        (result.data ?? []).map(async (clip) => {
          const filename = clip.url?.split("/videos/").pop();
          if (!filename) throw new Error(`Unexpected video URL format: ${clip.url}`);
          const filePath = join11(VIDEO_DIR2, filename);
          const buffer2 = await readFileAsync(filePath);
          const ext = filename.split(".").pop()?.toLowerCase() ?? "mp4";
          const mimeType = ext === "webm" ? "video/webm" : ext === "mov" ? "video/quicktime" : "video/mp4";
          return {
            buffer: buffer2,
            mimeType,
            fileName: filename,
            metadata: {
              ...clip.duration_seconds ? { duration_seconds: clip.duration_seconds } : {}
            }
          };
        })
      );
      return {
        videos,
        model: result.model ?? req.model
      };
    }
  };
}
function restartProxyForChainSwitch(api) {
  const oldHandle = activeProxyHandle;
  activeProxyHandle = null;
  const restartGeneration = beginProxyStartupAttempt();
  const doRestart = async () => {
    if (oldHandle) {
      try {
        await oldHandle.close();
      } catch {
      }
    }
    await new Promise((r) => setTimeout(r, 300));
    if (!isProxyStartupCurrent(restartGeneration)) return;
    await startProxyInBackground(api, restartGeneration);
  };
  doRestart().catch((err) => {
    if (isProxyStartupCurrent(restartGeneration)) {
      resetProxyStartupState();
    }
    api.logger.error(
      `Failed to restart proxy after chain switch: ${err instanceof Error ? err.message : String(err)}`
    );
  });
}
function createWalletCommand(api) {
  return {
    name: "wallet",
    description: "Show BlockRun wallet info, balance, chain, or export key",
    acceptsArgs: true,
    requireAuth: true,
    handler: async (ctx) => {
      const subcommand = ctx.args?.trim().toLowerCase() || "status";
      let walletKey;
      let address2;
      try {
        if (existsSync4(WALLET_FILE)) {
          walletKey = readTextFileSync(WALLET_FILE).trim();
          if (walletKey.startsWith("0x") && walletKey.length === 66) {
            const account = privateKeyToAccount(walletKey);
            address2 = account.address;
          }
        }
      } catch {
      }
      if (!walletKey || !address2) {
        return {
          text: `No ClawRouter wallet found.

Run \`openclaw plugins install @blockrun/clawrouter\` to generate a wallet.`,
          isError: true
        };
      }
      if (subcommand === "export") {
        const lines = [
          "**ClawRouter Wallet Export**",
          "",
          "**SECURITY WARNING**: Your private key and mnemonic control your wallet funds.",
          "Never share these. Anyone with them can spend your USDC.",
          "",
          "**EVM (Base):**",
          `  Address: \`${address2}\``,
          `  Private Key: \`${walletKey}\``
        ];
        let hasMnemonic = false;
        try {
          if (existsSync4(MNEMONIC_FILE)) {
            const mnemonic = readTextFileSync(MNEMONIC_FILE).trim();
            if (mnemonic) {
              hasMnemonic = true;
              const { deriveSolanaKeyBytes: deriveSolanaKeyBytes2 } = await Promise.resolve().then(() => (init_wallet(), wallet_exports));
              const solKeyBytes = deriveSolanaKeyBytes2(mnemonic);
              const { createKeyPairSignerFromPrivateKeyBytes: createKeyPairSignerFromPrivateKeyBytes2 } = await Promise.resolve().then(() => (init_index_node37(), index_node_exports));
              const signer = await createKeyPairSignerFromPrivateKeyBytes2(solKeyBytes);
              lines.push(
                "",
                "**Solana:**",
                `  Address: \`${signer.address}\``,
                `  (Derived from mnemonic below)`,
                "",
                "**Mnemonic (24 words):**",
                `\`${mnemonic}\``,
                "",
                "CRITICAL: Back up this mnemonic. It is the ONLY way to recover your Solana wallet."
              );
            }
          }
        } catch {
        }
        lines.push(
          "",
          "**To restore on a new machine:**",
          "1. Set the environment variable before running OpenClaw:",
          `   \`export BLOCKRUN_WALLET_KEY=${walletKey}\``,
          "2. Or save to file:",
          `   \`mkdir -p ~/.openclaw/blockrun && echo "${walletKey}" > ~/.openclaw/blockrun/wallet.key && chmod 600 ~/.openclaw/blockrun/wallet.key\``
        );
        if (hasMnemonic) {
          lines.push(
            "3. Restore the mnemonic for Solana:",
            `   \`echo "<your mnemonic>" > ~/.openclaw/blockrun/mnemonic && chmod 600 ~/.openclaw/blockrun/mnemonic\``
          );
        }
        return { text: lines.join("\n") };
      }
      if (subcommand === "solana") {
        try {
          let solanaAddr;
          if (existsSync4(MNEMONIC_FILE)) {
            const existingMnemonic = readTextFileSync(MNEMONIC_FILE).trim();
            if (existingMnemonic) {
              await savePaymentChain("solana");
              const { deriveSolanaKeyBytes: deriveSolanaKeyBytes2 } = await Promise.resolve().then(() => (init_wallet(), wallet_exports));
              const solKeyBytes = deriveSolanaKeyBytes2(existingMnemonic);
              const { createKeyPairSignerFromPrivateKeyBytes: createKeyPairSignerFromPrivateKeyBytes3 } = await Promise.resolve().then(() => (init_index_node37(), index_node_exports));
              const signer2 = await createKeyPairSignerFromPrivateKeyBytes3(solKeyBytes);
              solanaAddr = signer2.address;
              if (api) restartProxyForChainSwitch(api);
              return {
                text: [
                  "\u2713 Payment chain switched to **Solana**.",
                  api ? "Proxy restarting in background (~2s)." : "Restart the gateway to apply.",
                  "",
                  `**Solana Address:** \`${solanaAddr}\``,
                  `**Fund with USDC on Solana:** https://solscan.io/account/${solanaAddr}`
                ].join("\n")
              };
            }
          }
          const { solanaPrivateKeyBytes } = await setupSolana();
          await savePaymentChain("solana");
          const { createKeyPairSignerFromPrivateKeyBytes: createKeyPairSignerFromPrivateKeyBytes2 } = await Promise.resolve().then(() => (init_index_node37(), index_node_exports));
          const signer = await createKeyPairSignerFromPrivateKeyBytes2(solanaPrivateKeyBytes);
          if (api) restartProxyForChainSwitch(api);
          return {
            text: [
              "**Solana Wallet Set Up**",
              "",
              `**Solana Address:** \`${signer.address}\``,
              `**Mnemonic File:** \`${MNEMONIC_FILE}\``,
              "",
              "Your existing EVM wallet is unchanged.",
              api ? "\u2713 Payment chain switched to Solana. Proxy restarting in background (~2s)." : "Payment chain set to Solana. Restart the gateway to apply.",
              "",
              `**Fund with USDC on Solana:** https://solscan.io/account/${signer.address}`
            ].join("\n")
          };
        } catch (err) {
          return {
            text: `Failed to set up Solana: ${err instanceof Error ? err.message : String(err)}`,
            isError: true
          };
        }
      }
      if (subcommand === "base") {
        try {
          await savePaymentChain("base");
          if (api) restartProxyForChainSwitch(api);
          return {
            text: api ? "\u2713 Payment chain switched to **Base (EVM)**. Proxy restarting in background (~2s)." : "Payment chain set to Base (EVM). Restart the gateway to apply."
          };
        } catch (err) {
          return {
            text: `Failed to set payment chain: ${err instanceof Error ? err.message : String(err)}`,
            isError: true
          };
        }
      }
      const evmBalancePromise = (async () => {
        try {
          const monitor = new BalanceMonitor(address2);
          const balance = await monitor.checkBalance();
          return `Balance: ${balance.balanceUSD}`;
        } catch {
          return "Balance: (could not check)";
        }
      })();
      const solanaPromise = (async () => {
        try {
          if (!existsSync4(MNEMONIC_FILE)) return "";
          const { deriveSolanaKeyBytes: deriveSolanaKeyBytes2 } = await Promise.resolve().then(() => (init_wallet(), wallet_exports));
          const mnemonic = readTextFileSync(MNEMONIC_FILE).trim();
          if (!mnemonic) return "";
          const solKeyBytes = deriveSolanaKeyBytes2(mnemonic);
          const { createKeyPairSignerFromPrivateKeyBytes: createKeyPairSignerFromPrivateKeyBytes2 } = await Promise.resolve().then(() => (init_index_node37(), index_node_exports));
          const signer = await createKeyPairSignerFromPrivateKeyBytes2(solKeyBytes);
          const solAddr = signer.address;
          let solBalanceText = "Balance: (could not check)";
          try {
            const { SolanaBalanceMonitor: SolanaBalanceMonitor2 } = await Promise.resolve().then(() => (init_solana_balance(), solana_balance_exports));
            const solMonitor = new SolanaBalanceMonitor2(solAddr);
            const solBalance = await solMonitor.checkBalance();
            solBalanceText = `Balance: ${solBalance.balanceUSD}`;
          } catch {
          }
          return [
            "",
            "**Solana:**",
            `  Address: \`${solAddr}\``,
            `  ${solBalanceText}`,
            `  Fund (USDC only): https://solscan.io/account/${solAddr}`
          ].join("\n");
        } catch {
          return "";
        }
      })();
      const chainPromise = resolvePaymentChain();
      const usagePromise = (async () => {
        try {
          const stats = await getStats(7);
          if (stats.totalRequests === 0) return "";
          const modelLines = Object.entries(stats.byModel).sort((a, b) => b[1].count - a[1].count).slice(0, 8).map(
            ([model, data]) => `  ${model.length > 30 ? model.slice(0, 27) + "..." : model}  ${data.count} reqs  $${data.cost.toFixed(4)}`
          );
          return [
            "",
            `**Usage (${stats.period}):**`,
            `  Total: ${stats.totalRequests} requests, $${stats.totalCost.toFixed(4)} spent`,
            stats.totalSavings > 0 ? `  Saved: $${stats.totalSavings.toFixed(4)} (${stats.savingsPercentage.toFixed(0)}% vs Opus baseline)` : "",
            "",
            "**Top Models:**",
            ...modelLines
          ].filter(Boolean).join("\n");
        } catch {
          return "";
        }
      })();
      const [evmBalanceText, solanaSection, currentChain, usageSection] = await Promise.all([
        evmBalancePromise,
        solanaPromise,
        chainPromise,
        usagePromise
      ]);
      return {
        text: [
          "**ClawRouter Wallet**",
          "",
          `**Payment Chain:** ${currentChain === "solana" ? "Solana" : "Base (EVM)"}`,
          "",
          "**Base (EVM):**",
          `  Address: \`${address2}\``,
          `  ${evmBalanceText}`,
          `  Fund (USDC only): https://basescan.org/address/${address2}`,
          solanaSection,
          usageSection,
          "",
          `**Key File:** \`${WALLET_FILE}\``,
          "",
          "**Commands:**",
          "\u2022 `/wallet` - Show this status",
          "\u2022 `/wallet export` - Export private key for backup",
          "\u2022 `/stats` - Detailed usage breakdown",
          !solanaSection ? "\u2022 `/wallet solana` - Enable Solana payments" : "",
          solanaSection ? "\u2022 `/wallet base` - Switch to Base (EVM)" : "",
          solanaSection ? "\u2022 `/wallet solana` - Switch to Solana" : ""
        ].filter(Boolean).join("\n")
      };
    }
  };
}
var activeProxyHandle, pendingConfiguredStartupApi, IMAGE_DIR2, AUDIO_DIR2, VIDEO_DIR2, plugin, index_default2;
var init_index = __esm({
  "src/index.ts"() {
    "use strict";
    init_provider();
    init_proxy();
    init_web_search_provider();
    init_auth();
    init_balance();
    init_exclude_models();
    init_models();
    init_fs_read();
    init_top_models2();
    init_version4();
    init_accounts();
    init_stats();
    init_partners();
    init_stats2();
    init_exclude();
    init_mcp_config();
    init_proxy();
    init_provider();
    init_models();
    init_router();
    init_logger();
    init_dedup();
    init_balance();
    init_solana_balance();
    init_spend_control();
    init_wallet();
    init_auth();
    init_errors5();
    init_retry();
    init_stats();
    init_session();
    init_response_cache();
    init_partners();
    activeProxyHandle = null;
    pendingConfiguredStartupApi = null;
    IMAGE_DIR2 = join11(homedir8(), ".openclaw", "blockrun", "images");
    AUDIO_DIR2 = join11(homedir8(), ".openclaw", "blockrun", "audio");
    VIDEO_DIR2 = join11(homedir8(), ".openclaw", "blockrun", "videos");
    plugin = {
      id: "clawrouter",
      name: "ClawRouter",
      description: "Smart LLM router \u2014 55+ models, x402 micropayments, 78% cost savings",
      version: VERSION,
      register(api) {
        const isDisabled = process["env"].CLAWROUTER_DISABLED === "true" || process["env"].CLAWROUTER_DISABLED === "1";
        if (isDisabled) {
          api.logger.info("ClawRouter disabled (CLAWROUTER_DISABLED=true). Using default routing.");
          return;
        }
        installSkillsToWorkspace(api.logger);
        const proc = process;
        const proxyAlreadyStarted = !!proc.__clawrouterProxyStarted;
        if (isCompletionMode()) {
          api.registerProvider(blockrunProvider);
          return;
        }
        api.registerProvider(blockrunProvider);
        api.registerImageGenerationProvider(buildImageGenerationProvider());
        api.registerMusicGenerationProvider(buildMusicGenerationProvider());
        if (typeof api.registerVideoGenerationProvider === "function") {
          api.registerVideoGenerationProvider(buildVideoGenerationProvider());
        } else {
          api.logger.warn(
            "OpenClaw runtime does not expose registerVideoGenerationProvider(); BlockRun video models unavailable on this version."
          );
        }
        const webSearchDisabled = isBlockrunWebSearchDisabled(api.config);
        if (typeof api.registerWebSearchProvider === "function") {
          if (!webSearchDisabled) {
            api.registerWebSearchProvider(blockrunExaWebSearchProvider);
          }
        } else {
          api.logger.warn(
            "OpenClaw runtime does not expose registerWebSearchProvider(); blockrun-exa search is unavailable on this version."
          );
        }
        injectModelsConfig(api.logger);
        injectAuthProfile(api.logger);
        const runtimePort = getProxyPort();
        if (!api.config.models) {
          api.config.models = { providers: {} };
        }
        if (!api.config.models.providers) {
          api.config.models.providers = {};
        }
        api.config.models.providers.blockrun = {
          baseUrl: `http://127.0.0.1:${runtimePort}/v1`,
          api: "openai-completions",
          // apiKey is required by pi-coding-agent's ModelRegistry for providers with models.
          apiKey: "x402-proxy-handles-auth",
          models: VISIBLE_OPENCLAW_MODELS
        };
        const runtimeMcpRemoved = removeManagedBlockrunMcpServerConfig(api.config);
        const shouldLogRegistration = !proc.__clawrouterRegistrationLogged;
        proc.__clawrouterRegistrationLogged = true;
        if (shouldLogRegistration) {
          api.logger.info("BlockRun provider registered (55+ models via x402)");
          if (typeof api.registerWebSearchProvider === "function") {
            if (webSearchDisabled) {
              api.logger.info(
                "BlockRun web search disabled (BLOCKRUN_WEB_SEARCH=off or tools.web.search.enabled=false)"
              );
            } else {
              api.logger.info(`Registered BlockRun web_search provider (${BLOCKRUN_EXA_PROVIDER_ID})`);
            }
          }
          if (runtimeMcpRemoved) {
            api.logger.info(
              `Removed bundled BlockRun MCP server config (${BLOCKRUN_MCP_SERVER_NAME}) \u2014 restart the gateway to free any leaked processes`
            );
          }
        }
        try {
          const proxyBaseUrl = `http://127.0.0.1:${runtimePort}`;
          const partnerTools = buildPartnerTools(proxyBaseUrl);
          for (const tool of partnerTools) {
            api.registerTool(tool);
          }
          if (partnerTools.length > 0 && shouldLogRegistration) {
            api.logger.info(
              `Registered ${partnerTools.length} partner tool(s): ${partnerTools.map((t) => t.name).join(", ")}`
            );
          }
        } catch (err) {
          api.logger.warn(
            `Failed to register partner tools: ${err instanceof Error ? err.message : String(err)}`
          );
        }
        api.registerCommand({
          name: "partners",
          description: "List available partner APIs and pricing",
          acceptsArgs: false,
          requireAuth: false,
          handler: async () => {
            if (PARTNER_SERVICES.length === 0) {
              return { text: "No partner APIs available." };
            }
            const byCategory = /* @__PURE__ */ new Map();
            for (const svc of PARTNER_SERVICES) {
              const bucket = byCategory.get(svc.category) ?? [];
              bucket.push(svc);
              byCategory.set(svc.category, bucket);
            }
            const toolWidth = Math.max(...PARTNER_SERVICES.map((s3) => `blockrun_${s3.id}`.length), 28);
            const priceWidth = Math.max(
              ...PARTNER_SERVICES.map(
                (s3) => s3.pricing.perUnit === "free" ? 4 : `${s3.pricing.perUnit}/${s3.pricing.unit}`.length
              ),
              12
            );
            const lines = ["**Partner APIs** (paid via your ClawRouter wallet)", ""];
            for (const [category, services] of byCategory) {
              lines.push(`**${category}**`);
              for (const svc of services) {
                const tool = `blockrun_${svc.id}`.padEnd(toolWidth);
                const price = (svc.pricing.perUnit === "free" ? "free" : `${svc.pricing.perUnit}/${svc.pricing.unit}`).padEnd(priceWidth);
                lines.push(`  \`${tool}\` ${price}  ${svc.shortDescription}`);
              }
              lines.push("");
            }
            lines.push("Tool-call any of these in chat, or use `/cr-imagegen` / `/videogen` directly.");
            return { text: lines.join("\n") };
          }
        });
        api.registerCommand({
          name: "cr-imagegen",
          description: "Generate an image (BlockRun image models, paid via wallet)",
          acceptsArgs: true,
          requireAuth: false,
          handler: async (ctx) => {
            const parsed = parseGenArgs(ctx.args ?? "");
            if (!parsed.prompt) {
              return {
                text: "Usage: `/cr-imagegen <prompt> [--model=<alias>] [--size=1024x1024] [--n=1]`\n\nAliases: `nano-banana` (default), `banana-pro`, `dalle`, `gpt-image`, `flux`, `grok-imagine`, `grok-imagine-pro`, `cogview`."
              };
            }
            const model = resolveModelAlias(parsed.model ?? "nano-banana");
            const port = getProxyPort();
            try {
              const resp = await fetch(`http://127.0.0.1:${port}/v1/images/generations`, {
                method: "POST",
                headers: { "content-type": "application/json" },
                body: JSON.stringify({
                  model,
                  prompt: parsed.prompt,
                  size: parsed.size ?? "1024x1024",
                  n: parsed.n ?? 1
                }),
                signal: AbortSignal.timeout(18e4)
              });
              if (!resp.ok) {
                const errText = await resp.text().catch(() => "");
                if (resp.status === 402) {
                  return {
                    text: `Insufficient wallet balance for image generation. Top up with \`/wallet\`.

${errText}`
                  };
                }
                return { text: `Image generation failed (${resp.status}): ${errText}` };
              }
              const result = await resp.json();
              const urls = (result.data ?? []).map((d) => d.url).filter(Boolean);
              if (urls.length === 0) {
                return { text: "Image generation returned no results." };
              }
              return {
                text: urls.map((u, i) => `![image ${i + 1}](${u})`).join("\n\n")
              };
            } catch (err) {
              return {
                text: `Image generation error: ${err instanceof Error ? err.message : String(err)}`
              };
            }
          }
        });
        api.registerCommand({
          name: "videogen",
          description: "Generate a short video (Grok Imagine / Seedance, paid via wallet)",
          acceptsArgs: true,
          requireAuth: false,
          handler: async (ctx) => {
            const parsed = parseGenArgs(ctx.args ?? "");
            if (!parsed.prompt) {
              return {
                text: "Usage: `/videogen <prompt> [--model=<alias>] [--duration=5|8|10]`\n\nAliases: `seedance` (1.5-pro, default \u2014 cheapest), `seedance-2-fast`, `seedance-2`, `grok-video`.\n\n\u23F1\uFE0F  Generation takes 60\u2013180 seconds. Payment settles only on success."
              };
            }
            const model = resolveModelAlias(parsed.model ?? "seedance");
            const port = getProxyPort();
            try {
              const resp = await fetch(`http://127.0.0.1:${port}/v1/videos/generations`, {
                method: "POST",
                headers: { "content-type": "application/json" },
                body: JSON.stringify({
                  model,
                  prompt: parsed.prompt,
                  ...parsed.duration ? { duration_seconds: parsed.duration } : {}
                }),
                signal: AbortSignal.timeout(33e4)
              });
              if (!resp.ok) {
                const errText = await resp.text().catch(() => "");
                if (resp.status === 402) {
                  return {
                    text: `Insufficient wallet balance for video generation. Top up with \`/wallet\`.

${errText}`
                  };
                }
                return { text: `Video generation failed (${resp.status}): ${errText}` };
              }
              const result = await resp.json();
              const urls = (result.data ?? []).map((d) => d.url).filter(Boolean);
              if (urls.length === 0) {
                return { text: "Video generation returned no results." };
              }
              return { text: urls.map((u, i) => `Video ${i + 1}: ${u}`).join("\n") };
            } catch (err) {
              return {
                text: `Video generation error: ${err instanceof Error ? err.message : String(err)}`
              };
            }
          }
        });
        api.registerCommand({
          name: "cr-call",
          description: "Place an AI voice call via BlockRun + Bland.ai (paid from wallet, $0.54/call)",
          acceptsArgs: true,
          requireAuth: false,
          handler: async (ctx) => {
            const parsed = parseCallArgs(ctx.args ?? "");
            if (!parsed.to || !parsed.task) {
              return {
                text: 'Usage: `/cr-call +1<E.164-number> "<what the AI should say>" [--voice nat] [--max-duration 5] [--from +1<owned-number>] [--language en-US]`\n\nVoices: `nat` (default), `josh`, `maya`, `june`, `paige`, `derek`, `florian`.\n\n\u26A0\uFE0F Places a REAL phone call. $0.54 per call (covers up to 30 minutes). Use `clawrouter phone numbers list` to see wallet-owned numbers usable as `--from`.'
              };
            }
            const port = getProxyPort();
            try {
              const resp = await fetch(`http://127.0.0.1:${port}/v1/voice/call`, {
                method: "POST",
                headers: { "content-type": "application/json" },
                body: JSON.stringify({
                  to: parsed.to,
                  task: parsed.task,
                  ...parsed.voice ? { voice: parsed.voice } : {},
                  ...parsed.from ? { from: parsed.from } : {},
                  ...parsed.language ? { language: parsed.language } : {},
                  ...parsed.max_duration !== void 0 ? { max_duration: parsed.max_duration } : {}
                }),
                signal: AbortSignal.timeout(6e4)
              });
              if (!resp.ok) {
                const errText = await resp.text().catch(() => "");
                if (resp.status === 402) {
                  return {
                    text: `Insufficient wallet balance for voice call ($0.54). Top up with \`/wallet\`.

${errText}`
                  };
                }
                return { text: `Voice call failed (${resp.status}): ${errText}` };
              }
              const result = await resp.json();
              if (!result.call_id) {
                return {
                  text: `Voice call accepted but no call_id returned: ${JSON.stringify(result)}`
                };
              }
              const lines = [
                `\u{1F4DE} Calling **${parsed.to}** (call_id: \`${result.call_id}\`)`,
                "",
                `Status: ${result.status ?? "queued"}`
              ];
              if (result.poll_url) {
                lines.push(`Poll: \`GET ${result.poll_url}\``);
              } else {
                lines.push(`Poll: \`GET http://localhost:${port}/v1/voice/call/${result.call_id}\``);
              }
              lines.push(
                "",
                "Call runs in the cloud for up to 30 min. Transcript + recording appear once status is `completed`."
              );
              return { text: lines.join("\n") };
            } catch (err) {
              return {
                text: `Voice call error: ${err instanceof Error ? err.message : String(err)}`
              };
            }
          }
        });
        api.registerCommand(createWalletCommand(api));
        try {
          const blockrunAlias = createWalletCommand(api);
          blockrunAlias.name = "blockrun";
          api.registerCommand(blockrunAlias);
        } catch {
        }
        api.registerCommand(createStatsCommand());
        api.registerCommand(createExcludeCommand());
        if (shouldLogRegistration) {
          api.logger.info(
            "Commands registered: /wallet, /blockrun, /stats, /exclude, /partners, /cr-imagegen, /videogen, /cr-call"
          );
        }
        api.registerService({
          id: "clawrouter-proxy",
          start: () => {
          },
          stop: async () => {
            if (activeProxyHandle) {
              try {
                await activeProxyHandle.close();
                api.logger.info("BlockRun proxy closed");
              } catch (err) {
                api.logger.warn(
                  `Failed to close proxy: ${err instanceof Error ? err.message : String(err)}`
                );
              }
              activeProxyHandle = null;
            }
            resetProxyStartupState();
          }
        });
        if (!isGatewayMode()) {
          if (shouldLogRegistration) {
            resolveOrGenerateWalletKey().then(({ address: address2, source }) => {
              if (source === "generated") {
                api.logger.warn(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`);
                api.logger.warn(`  NEW WALLET GENERATED \u2014 BACK UP YOUR KEY NOW!`);
                api.logger.warn(`  Address : ${address2}`);
                api.logger.warn(`  Run /wallet export to get your private key`);
                api.logger.warn(`  Losing this key = losing your USDC funds`);
                api.logger.warn(`\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550`);
              } else if (source === "saved") {
                api.logger.info(`Using saved wallet: ${address2}`);
              } else if (source === "config") {
                api.logger.info(`Using wallet from plugin config: ${address2}`);
              } else {
                api.logger.info(`Using wallet from BLOCKRUN_WALLET_KEY: ${address2}`);
              }
            }).catch((err) => {
              api.logger.warn(
                `Failed to initialize wallet: ${err instanceof Error ? err.message : String(err)}`
              );
            });
            api.logger.info("Not in gateway mode \u2014 proxy will start when gateway runs");
          }
          return;
        }
        const pluginConfigEmpty = !api.pluginConfig || typeof api.pluginConfig !== "object" || Object.keys(api.pluginConfig).length === 0;
        if (clearDeferredProxyStartTimer(proc)) {
          api.logger.info("Superseding earlier deferred proxy start \u2014 using current pluginConfig");
        }
        if (proxyAlreadyStarted) {
          if (!pluginConfigEmpty && proc.__clawrouterStartedWithEmptyConfig) {
            api.logger.info(
              "Populated pluginConfig arrived after provisional default startup \u2014 switching proxy to current config"
            );
            supersedeEmptyConfigStartup(api);
          } else if (shouldLogRegistration) {
            api.logger.info("Proxy already started by earlier register() call \u2014 skipping");
          }
          return;
        }
        if (pluginConfigEmpty) {
          if (shouldLogRegistration) {
            api.logger.info(
              "pluginConfig empty \u2014 deferring proxy startup 250ms in case a populated config arrives"
            );
          }
          proc.__clawrouterDeferredStartTimer = setTimeout(() => {
            proc.__clawrouterDeferredStartTimer = void 0;
            if (proc.__clawrouterProxyStarted) return;
            const startupGeneration2 = beginProxyStartupAttempt(proc, true);
            api.logger.info("Deferred timer fired \u2014 starting proxy with default config");
            startProxyAfterPortProbe(api, startupGeneration2);
          }, 250);
          return;
        }
        if (pendingConfiguredStartupApi) {
          pendingConfiguredStartupApi = null;
          api.logger.info("Discarding older queued populated pluginConfig \u2014 using newest config");
        }
        const startupGeneration = beginProxyStartupAttempt(proc, false);
        startProxyAfterPortProbe(api, startupGeneration);
      },
      /**
       * Cleanup hook called when plugin is uninstalled via `openclaw plugins uninstall`.
       * Removes blockrun provider config, plugin entries, model allowlist entries,
       * and auth profiles from openclaw.json so no residual config causes errors.
       */
      deactivate(api) {
        if (activeProxyHandle) {
          activeProxyHandle.close().catch(() => {
          });
          activeProxyHandle = null;
        }
        resetProxyStartupState();
        try {
          const configPath = join11(homedir8(), ".openclaw", "openclaw.json");
          if (existsSync4(configPath)) {
            const config = JSON.parse(readTextFileSync(configPath));
            if (config.models?.providers?.blockrun) {
              delete config.models.providers.blockrun;
            }
            removeManagedBlockrunMcpServerConfig(config);
            for (const key of ["clawrouter", "ClawRouter", "@blockrun/clawrouter"]) {
              if (config.plugins?.entries?.[key]) delete config.plugins.entries[key];
              if (config.plugins?.installs?.[key]) delete config.plugins.installs[key];
            }
            if (Array.isArray(config.plugins?.allow)) {
              config.plugins.allow = config.plugins.allow.filter(
                (p) => p !== "clawrouter" && p !== "ClawRouter" && p !== "@blockrun/clawrouter"
              );
            }
            if (config.agents?.defaults?.models) {
              for (const key of Object.keys(config.agents.defaults.models)) {
                if (key.startsWith("blockrun/")) delete config.agents.defaults.models[key];
              }
            }
            if (config.agents?.defaults?.model?.primary?.startsWith("blockrun/")) {
              delete config.agents.defaults.model.primary;
            }
            if (config.tools?.web?.search?.provider === BLOCKRUN_EXA_PROVIDER_ID) {
              delete config.tools.web.search.provider;
            }
            const tmpPath = `${configPath}.tmp.${process.pid}`;
            writeFileSync3(tmpPath, JSON.stringify(config, null, 2));
            renameSync(tmpPath, configPath);
            api.logger.info("ClawRouter config cleaned up");
          }
        } catch (err) {
          api.logger.warn(`Config cleanup failed: ${err instanceof Error ? err.message : String(err)}`);
        }
        try {
          const agentsDir = join11(homedir8(), ".openclaw", "agents");
          if (existsSync4(agentsDir)) {
            for (const entry of readdirSync(agentsDir, { withFileTypes: true })) {
              if (!entry.isDirectory()) continue;
              const authPath = join11(agentsDir, entry.name, "agent", "auth-profiles.json");
              if (!existsSync4(authPath)) continue;
              try {
                const store = JSON.parse(readTextFileSync(authPath));
                if (store.profiles?.["blockrun:default"]) {
                  delete store.profiles["blockrun:default"];
                  writeFileSync3(authPath, JSON.stringify(store, null, 2));
                }
              } catch {
              }
            }
          }
        } catch {
        }
        api.logger.info("ClawRouter deactivated \u2014 restart gateway to complete uninstall");
      }
    };
    index_default2 = plugin;
  }
});

// src/cli.ts
init_proxy();
init_version4();
init_auth();
init_wallet();

// src/report.ts
init_stats();
async function generateReport(period, json = false) {
  const days = period === "daily" ? 1 : period === "weekly" ? 7 : 30;
  const stats = await getStats(days);
  if (json) {
    return JSON.stringify(stats, null, 2);
  }
  return formatMarkdownReport(period, days, stats);
}
function formatMarkdownReport(period, days, stats) {
  const lines = [];
  lines.push(`# ClawRouter ${capitalize(period)} Report`);
  lines.push(`**Period:** Last ${days} day${days > 1 ? "s" : ""}`);
  lines.push(`**Generated:** ${(/* @__PURE__ */ new Date()).toISOString()}`);
  lines.push("");
  lines.push("## \u{1F4CA} Usage Summary");
  lines.push("");
  lines.push(`| Metric | Value |`);
  lines.push(`|--------|-------|`);
  lines.push(`| Total Requests | ${stats.totalRequests} |`);
  lines.push(`| Total Cost | $${stats.totalCost.toFixed(4)} |`);
  lines.push(`| Baseline Cost | $${stats.totalBaselineCost.toFixed(4)} |`);
  lines.push(`| **Savings** | **$${stats.totalSavings.toFixed(4)}** |`);
  lines.push(`| Savings % | ${stats.savingsPercentage.toFixed(1)}% |`);
  lines.push(`| Avg Latency | ${stats.avgLatencyMs.toFixed(0)}ms |`);
  lines.push("");
  lines.push("## \u{1F916} Model Distribution");
  lines.push("");
  const sortedModels = Object.entries(stats.byModel).sort((a, b) => b[1].count - a[1].count).slice(0, 10);
  for (const [model, data] of sortedModels) {
    lines.push(`- ${model}: ${data.count} reqs, $${data.cost.toFixed(4)}`);
  }
  lines.push("");
  return lines.join("\n");
}
function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

// src/cli.ts
init_stats();

// src/doctor.ts
init_esm();
init_chains();
init_accounts();
init_esm4();
init_client2();
init_esm5();
init_auth();
init_balance();
init_wallet();
init_stats();
init_proxy();
init_version4();
import { platform, arch, freemem, totalmem } from "os";
import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
function formatBytes(bytes) {
  const gb = bytes / (1024 * 1024 * 1024);
  return `${gb.toFixed(1)}GB`;
}
function green(text) {
  return `\x1B[32m\u2713\x1B[0m ${text}`;
}
function red(text) {
  return `\x1B[31m\u2717\x1B[0m ${text}`;
}
function yellow(text) {
  return `\x1B[33m\u26A0\x1B[0m ${text}`;
}
async function fetchLatestVersion() {
  try {
    const res = await fetch("https://registry.npmjs.org/@blockrun/clawrouter/latest", {
      signal: AbortSignal.timeout(5e3)
    });
    if (!res.ok) return null;
    const data = await res.json();
    return data.version ?? null;
  } catch {
    return null;
  }
}
function collectSystemInfo() {
  return {
    os: `${platform()} ${arch()}`,
    arch: arch(),
    nodeVersion: process.version,
    memoryFree: formatBytes(freemem()),
    memoryTotal: formatBytes(totalmem())
  };
}
async function collectWalletInfo() {
  try {
    const { key, address: address2, source, solanaPrivateKeyBytes } = await resolveOrGenerateWalletKey();
    if (!key || !address2) {
      return {
        exists: false,
        valid: false,
        address: null,
        solanaAddress: null,
        balance: null,
        isLow: false,
        isEmpty: true,
        source: null,
        paymentChain: "base"
      };
    }
    let solanaAddress = null;
    if (solanaPrivateKeyBytes) {
      try {
        solanaAddress = await getSolanaAddress(solanaPrivateKeyBytes);
      } catch {
      }
    }
    const paymentChain = await resolvePaymentChain();
    try {
      let balanceInfo;
      if (paymentChain === "solana" && solanaAddress) {
        const { SolanaBalanceMonitor: SolanaBalanceMonitor2 } = await Promise.resolve().then(() => (init_solana_balance(), solana_balance_exports));
        const monitor = new SolanaBalanceMonitor2(solanaAddress);
        balanceInfo = await monitor.checkBalance();
      } else {
        const monitor = new BalanceMonitor(address2);
        balanceInfo = await monitor.checkBalance();
      }
      return {
        exists: true,
        valid: true,
        address: address2,
        solanaAddress,
        balance: balanceInfo.balanceUSD,
        isLow: balanceInfo.isLow,
        isEmpty: balanceInfo.isEmpty,
        source,
        paymentChain
      };
    } catch {
      return {
        exists: true,
        valid: true,
        address: address2,
        solanaAddress,
        balance: null,
        isLow: false,
        isEmpty: false,
        source,
        paymentChain
      };
    }
  } catch {
    return {
      exists: false,
      valid: false,
      address: null,
      solanaAddress: null,
      balance: null,
      isLow: false,
      isEmpty: true,
      source: null,
      paymentChain: "base"
    };
  }
}
async function collectNetworkInfo() {
  const port = getProxyPort();
  let blockrunReachable = false;
  let blockrunLatency = null;
  try {
    const start = Date.now();
    const response = await fetch("https://blockrun.ai/api/v1/models", {
      method: "GET",
      signal: AbortSignal.timeout(1e4)
    });
    blockrunLatency = Date.now() - start;
    blockrunReachable = response.ok || response.status === 402;
  } catch {
  }
  let proxyRunning = false;
  try {
    const response = await fetch(`http://127.0.0.1:${port}/health`, {
      method: "GET",
      signal: AbortSignal.timeout(3e3)
    });
    proxyRunning = response.ok;
  } catch {
  }
  return {
    blockrunApi: { reachable: blockrunReachable, latencyMs: blockrunLatency },
    localProxy: { running: proxyRunning, port }
  };
}
async function collectLogInfo() {
  try {
    const stats = await getStats(1);
    return {
      requestsLast24h: stats.totalRequests,
      costLast24h: `$${stats.totalCost.toFixed(4)}`,
      errorsFound: 0
      // TODO: parse error logs
    };
  } catch {
    return {
      requestsLast24h: 0,
      costLast24h: "$0.00",
      errorsFound: 0
    };
  }
}
function identifyIssues(result) {
  const issues = [];
  if (!result.wallet.exists) {
    issues.push("No wallet found");
  }
  if (result.wallet.isEmpty) {
    const chain3 = result.wallet.paymentChain === "solana" ? "Solana" : "Base";
    issues.push(`Wallet is empty - need to fund with USDC on ${chain3}`);
    if (result.wallet.paymentChain === "base" && result.wallet.solanaAddress) {
      issues.push("Tip: if you funded Solana, run /wallet solana to switch chains");
    }
  } else if (result.wallet.isLow) {
    issues.push("Wallet balance is low (< $1.00)");
  }
  if (!result.network.blockrunApi.reachable) {
    issues.push("Cannot reach BlockRun API - check internet connection");
  }
  if (!result.network.localProxy.running) {
    issues.push(`Local proxy not running on port ${result.network.localProxy.port}`);
  }
  if (result.latestVersion && result.latestVersion !== result.version) {
    issues.push(
      `Outdated version: running v${result.version}, latest is v${result.latestVersion}. Run: curl -fsSL https://blockrun.ai/ClawRouter-update | bash`
    );
  }
  return issues;
}
function printDiagnostics(result) {
  console.log("\n\u{1F50D} Collecting diagnostics...\n");
  console.log("Version");
  if (result.latestVersion && result.latestVersion !== result.version) {
    console.log(`  ${red(`Installed: v${result.version} (outdated!)`)}`);
    console.log(`  ${yellow(`Latest:    v${result.latestVersion}`)}`);
    console.log(
      `  ${yellow(`Update:    curl -fsSL https://blockrun.ai/ClawRouter-update | bash`)}`
    );
  } else if (result.latestVersion) {
    console.log(`  ${green(`v${result.version} (up to date)`)}`);
  } else {
    console.log(`  ${green(`v${result.version}`)}`);
  }
  console.log("\nSystem");
  console.log(`  ${green(`OS: ${result.system.os}`)}`);
  console.log(`  ${green(`Node: ${result.system.nodeVersion}`)}`);
  console.log(
    `  ${green(`Memory: ${result.system.memoryFree} free / ${result.system.memoryTotal}`)}`
  );
  console.log("\nWallet");
  if (result.wallet.exists && result.wallet.valid) {
    console.log(`  ${green(`Key: ${WALLET_FILE} (${result.wallet.source})`)}`);
    console.log(`  ${green(`EVM Address:    ${result.wallet.address}`)}`);
    if (result.wallet.solanaAddress) {
      console.log(`  ${green(`Solana Address: ${result.wallet.solanaAddress}`)}`);
    }
    const chainLabel = result.wallet.paymentChain === "solana" ? "Solana" : "Base";
    console.log(`  ${green(`Chain: ${chainLabel}`)}`);
    if (result.wallet.isEmpty) {
      console.log(
        `  ${red(`Balance: $0.00 - NEED TO FUND WITH USDC ON ${chainLabel.toUpperCase()}!`)}`
      );
      if (result.wallet.paymentChain === "base" && result.wallet.solanaAddress) {
        console.log(`  ${yellow(`Tip: funded Solana instead? Run /wallet solana to switch`)}`);
      }
    } else if (result.wallet.isLow) {
      console.log(`  ${yellow(`Balance: ${result.wallet.balance} (low)`)}`);
    } else if (result.wallet.balance) {
      console.log(`  ${green(`Balance: ${result.wallet.balance}`)}`);
    } else {
      console.log(`  ${yellow(`Balance: checking...`)}`);
    }
  } else {
    console.log(`  ${red("No wallet found")}`);
  }
  console.log("\nNetwork");
  if (result.network.blockrunApi.reachable) {
    console.log(
      `  ${green(`BlockRun API: reachable (${result.network.blockrunApi.latencyMs}ms)`)}`
    );
  } else {
    console.log(`  ${red("BlockRun API: unreachable")}`);
  }
  if (result.network.localProxy.running) {
    console.log(`  ${green(`Local proxy: running on :${result.network.localProxy.port}`)}`);
  } else {
    console.log(`  ${red(`Local proxy: not running on :${result.network.localProxy.port}`)}`);
  }
  console.log("\nLogs");
  console.log(
    `  ${green(`Last 24h: ${result.logs.requestsLast24h} requests, ${result.logs.costLast24h} spent`)}`
  );
  if (result.logs.errorsFound > 0) {
    console.log(`  ${yellow(`${result.logs.errorsFound} errors found in logs`)}`);
  }
  if (result.issues.length > 0) {
    console.log("\n\u26A0\uFE0F  Issues Found:");
    for (const issue of result.issues) {
      console.log(`  \u2022 ${issue}`);
    }
  }
}
var DOCTOR_MODELS = {
  sonnet: {
    id: "anthropic/claude-sonnet-4.6",
    name: "Claude Sonnet 4.6",
    cost: "~$0.003"
  },
  opus: {
    id: "anthropic/claude-opus-4.7",
    name: "Claude Opus 4.7",
    cost: "~$0.01"
  }
};
async function analyzeWithAI(diagnostics, userQuestion, model = "sonnet") {
  if (diagnostics.wallet.isEmpty) {
    console.log("\n\u{1F4B3} Wallet is empty - cannot call AI for analysis.");
    console.log(`   Fund your EVM wallet with USDC on Base: ${diagnostics.wallet.address}`);
    if (diagnostics.wallet.solanaAddress) {
      console.log(`   Fund your Solana wallet with USDC: ${diagnostics.wallet.solanaAddress}`);
    }
    console.log("   Get USDC: https://www.coinbase.com/price/usd-coin");
    console.log("   Bridge to Base: https://bridge.base.org\n");
    return;
  }
  const modelConfig = DOCTOR_MODELS[model];
  console.log(`
\u{1F4E4} Sending to ${modelConfig.name} (${modelConfig.cost})...
`);
  try {
    const { key } = await resolveOrGenerateWalletKey();
    const account = privateKeyToAccount(key);
    const publicClient = createPublicClient({ chain: base, transport: http() });
    const evmSigner = toClientEvmSigner(account, publicClient);
    const x402 = new x402Client();
    registerExactEvmScheme(x402, { signer: evmSigner });
    const paymentChain = diagnostics.wallet.paymentChain;
    if (paymentChain === "solana") {
      try {
        if (!existsSync2(MNEMONIC_FILE)) {
          throw new Error(`mnemonic file missing at ${MNEMONIC_FILE}`);
        }
        const mnemonic = readFileSync3(MNEMONIC_FILE, "utf8").trim();
        if (!mnemonic) throw new Error("mnemonic file empty");
        const { deriveSolanaKeyBytes: deriveSolanaKeyBytes2 } = await Promise.resolve().then(() => (init_wallet(), wallet_exports));
        const { registerExactSvmScheme: registerExactSvmScheme2 } = await Promise.resolve().then(() => (init_client3(), client_exports));
        const { createKeyPairSignerFromPrivateKeyBytes: createKeyPairSignerFromPrivateKeyBytes2 } = await Promise.resolve().then(() => (init_index_node37(), index_node_exports));
        const solanaKeyBytes = deriveSolanaKeyBytes2(mnemonic);
        const solanaSigner = await createKeyPairSignerFromPrivateKeyBytes2(solanaKeyBytes);
        registerExactSvmScheme2(x402, { signer: solanaSigner });
      } catch (err) {
        console.log(
          `  \u26A0 Could not register Solana signer: ${err instanceof Error ? err.message : String(err)}`
        );
        console.log(`  \u26A0 Falling back to Base (EVM) \u2014 doctor request may fail on Solana chain
`);
      }
    }
    const paymentFetch = wrapFetchWithPayment(fetch, x402);
    const apiUrl = paymentChain === "solana" ? "https://sol.blockrun.ai/api/v1/chat/completions" : "https://blockrun.ai/api/v1/chat/completions";
    const response = await paymentFetch(apiUrl, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        model: modelConfig.id,
        stream: false,
        messages: [
          {
            role: "system",
            content: `You are a technical support expert for BlockRun and ClawRouter.
Analyze the diagnostics and:
1. Identify the root cause of any issues
2. Provide specific, actionable fix commands (bash)
3. Explain why the issue occurred briefly
4. Be concise but thorough
5. Format commands in code blocks`
          },
          {
            role: "user",
            content: userQuestion ? `Here are my system diagnostics:

${JSON.stringify(diagnostics, null, 2)}

User's question: ${userQuestion}` : `Here are my system diagnostics:

${JSON.stringify(diagnostics, null, 2)}

Please analyze and help me fix any issues.`
          }
        ],
        max_tokens: 1e3
      })
    });
    if (!response.ok) {
      const text = await response.text();
      console.log(`Error: ${response.status} - ${text}`);
      return;
    }
    const data = await response.json();
    const content = data.choices?.[0]?.message?.content;
    if (content) {
      console.log("\u{1F916} AI Analysis:\n");
      console.log(content);
      console.log();
    } else {
      console.log("Error: No response from AI");
    }
  } catch (err) {
    console.log(`
Error calling AI: ${err instanceof Error ? err.message : String(err)}`);
    console.log("Try again or check your wallet balance.\n");
  }
}
async function runDoctor(userQuestion, model = "sonnet") {
  console.log(`
\u{1FA7A} BlockRun Doctor v${VERSION}
`);
  const [system, wallet, network, logs, latestVersion] = await Promise.all([
    collectSystemInfo(),
    collectWalletInfo(),
    collectNetworkInfo(),
    collectLogInfo(),
    fetchLatestVersion()
  ]);
  const result = {
    version: VERSION,
    latestVersion,
    timestamp: (/* @__PURE__ */ new Date()).toISOString(),
    system,
    wallet,
    network,
    logs,
    issues: []
  };
  result.issues = identifyIssues(result);
  printDiagnostics(result);
  await analyzeWithAI(result, userQuestion, model);
}

// src/cli.ts
init_partners();
function printHelp() {
  console.log(`
ClawRouter v${VERSION} - Smart LLM Router

Usage:
  clawrouter [options]
  clawrouter status                    # Live proxy status (wallet, balance, chain)
  clawrouter wallet                    # Wallet details + balance
  clawrouter models                    # List available models
  clawrouter stats [--days <n>]        # Usage stats (default: 7 days)
  clawrouter doctor [opus] [question]
  clawrouter partners [test]
  clawrouter report [daily|weekly|monthly] [--json]
  clawrouter logs [--days <n>]
  clawrouter setup                     # Finish OpenClaw integration after npm install -g
  clawrouter share last [--as=<im>]    # Convert most recent response for IM (default: feishu)
  clawrouter share list [--limit=<n>]  # Recent response ids + summaries
  clawrouter share <id> [--as=<im>]    # Convert a specific response by id
  clawrouter share last --all          # Write all 6 IM variants to /tmp/
                                       # IM presets: feishu, slack, discord, telegram, whatsapp, plain
  clawrouter phone numbers list                  # List wallet's active phone numbers + expiry
  clawrouter phone numbers buy <US|CA> [--area-code <code>]   # Buy 30-day number lease ($5)
  clawrouter phone numbers renew <+E.164>        # Extend lease 30 days ($5)
  clawrouter phone numbers release <+E.164>      # Release a wallet-owned number (free)
  clawrouter phone lookup <+E.164>               # Carrier + line type ($0.01)
  clawrouter phone fraud <+E.164>                # SIM-swap + forwarding fraud signals ($0.05)

Options:
  --version, -v     Show version number
  --help, -h        Show this help message
  --port <number>   Port to listen on (default: ${getProxyPort()})

Query Commands (talk to running proxy on localhost:${getProxyPort()}):
  status            Proxy status: wallet, balance, payment chain
  wallet            Wallet addresses + USDC balance
  models            List all available models with pricing
  stats             Usage breakdown: requests, cost, top models
  stats --days 14   Custom time range (max 30 days)
  cache             Response cache stats (hit rate, size)

Management Commands:
  setup             Finish OpenClaw integration (run after npm install -g).
                    Registers ClawRouter as a plugin, syncs the model allowlist,
                    and writes the auth profile. Idempotent \u2014 safe to re-run.
  doctor            AI-powered diagnostics (default: Sonnet ~$0.003)
  doctor opus       Use Opus for deeper analysis (~$0.01)
  logs              Per-request breakdown: model, cost, latency, status
  logs --days 7     Show last 7 days of requests (default: 1 day)
  partners          List available partner APIs with pricing
  partners test     Test partner API endpoints (expect 402 = alive)
  wallet recover    Restore wallet.key from mnemonic (if generated by ClawRouter)
  chain solana      Switch to Solana (persists)
  chain base        Switch to Base EVM (persists)

Environment Variables:
  BLOCKRUN_WALLET_KEY     Private key for x402 payments (auto-generated if not set)
  BLOCKRUN_PROXY_PORT     Default proxy port (default: 8402)

For more info: https://blockrun.ai/clawrouter.md
`);
}
async function queryProxy(path2, port) {
  const res = await fetch(`http://127.0.0.1:${port}${path2}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
  return res.json();
}
async function copyToClipboard(text) {
  const { spawn } = await import("child_process");
  const platform2 = process.platform;
  const candidates = platform2 === "darwin" ? [["pbcopy", []]] : platform2 === "win32" ? [["clip", []]] : [
    ["wl-copy", []],
    ["xclip", ["-selection", "clipboard"]],
    ["xsel", ["--clipboard", "--input"]]
  ];
  for (const [cmd, args] of candidates) {
    try {
      const child = spawn(cmd, args, { stdio: ["pipe", "ignore", "ignore"] });
      const ok = await new Promise((resolve) => {
        let settled = false;
        child.on("error", () => {
          if (!settled) {
            settled = true;
            resolve(false);
          }
        });
        child.on("close", (code) => {
          if (!settled) {
            settled = true;
            resolve(code === 0);
          }
        });
        child.stdin.end(text, "utf8");
      });
      if (ok) return null;
    } catch {
    }
  }
  return platform2 === "darwin" ? "pbcopy not available" : platform2 === "win32" ? "clip.exe not available" : "no clipboard tool found (install xclip, xsel, or wl-clipboard)";
}
var VALID_PRESETS = ["feishu", "slack", "discord", "telegram", "whatsapp", "plain"];
async function cmdShare(port, target, preset, limit, all) {
  const tgt = target ?? "last";
  if (tgt === "list") {
    try {
      const entries = await queryProxy(`/share/list?limit=${limit}`, port);
      if (entries.length === 0) {
        console.log("\nNo responses persisted yet.");
        console.log(
          "  Send a request through ClawRouter and try again, or check BLOCKRUN_RESPONSE_STORE.\n"
        );
        return;
      }
      console.log(`
Recent responses (${entries.length}):
`);
      for (const e7 of entries) {
        const t = new Date(e7.timestamp).toLocaleString();
        const summary = e7.requestSummary || "(no prompt)";
        const len = e7.responseLength ? ` ${e7.responseLength}b` : "";
        console.log(`  ${e7.id}  ${t}  [${e7.model ?? "?"}${len}]`);
        console.log(`    ${summary}`);
      }
      console.log(
        `
Use: clawrouter share <id> --as=<feishu|slack|discord|telegram|whatsapp|plain>
`
      );
    } catch (err) {
      console.error(`\u2717 Cannot fetch share list: ${err instanceof Error ? err.message : err}`);
      console.error(`  Is the proxy running on port ${port}?`);
      process.exit(1);
    }
    return;
  }
  const idOrLast = tgt === "last" ? "last" : tgt;
  if (all) {
    try {
      const { writeFile: writeFile3 } = await import("fs/promises");
      const { tmpdir } = await import("os");
      const { join: pjoin } = await import("path");
      const paths = [];
      for (const p of VALID_PRESETS) {
        const path2 = idOrLast === "last" ? `/share/last?as=${p}` : `/share/${idOrLast}/render?as=${p}`;
        const result = await queryProxy(path2, port);
        const file = pjoin(tmpdir(), `claw-share-${result.id}-${p}.txt`);
        await writeFile3(file, result.rendered, "utf8");
        paths.push(file);
      }
      console.log("\n\u2713 Wrote all 6 preset variants:");
      for (const p of paths) console.log(`  ${p}`);
      console.log();
    } catch (err) {
      console.error(`\u2717 Failed: ${err instanceof Error ? err.message : err}`);
      process.exit(1);
    }
    return;
  }
  const chosenPreset = preset ?? process.env.BLOCKRUN_DEFAULT_SHARE_PRESET ?? "feishu";
  if (!VALID_PRESETS.includes(chosenPreset)) {
    console.error(`\u2717 Unknown preset: ${chosenPreset}`);
    console.error(`  Valid: ${VALID_PRESETS.join(", ")}`);
    process.exit(1);
  }
  try {
    const path2 = idOrLast === "last" ? `/share/last?as=${chosenPreset}` : `/share/${idOrLast}/render?as=${chosenPreset}`;
    const result = await queryProxy(path2, port);
    process.stdout.write(result.rendered);
    if (!result.rendered.endsWith("\n")) process.stdout.write("\n");
    const clipErr = await copyToClipboard(result.rendered);
    const sizeKb = (result.rendered.length / 1024).toFixed(1);
    if (clipErr) {
      console.error(`
(clipboard skipped: ${clipErr})`);
    } else {
      console.error(`
\u2713 Copied to clipboard (preset=${chosenPreset}, ${sizeKb}KB)`);
    }
  } catch (err) {
    console.error(`\u2717 Cannot fetch share: ${err instanceof Error ? err.message : err}`);
    console.error(`  Is the proxy running on port ${port}?`);
    process.exit(1);
  }
}
async function cmdStatus(port) {
  try {
    const data = await queryProxy("/health?full=true", port);
    console.log(`
ClawRouter Status (port ${port})
`);
    console.log(`  Status:        ${data.status}`);
    console.log(`  Payment Chain: ${data.paymentChain}`);
    console.log(`  EVM Wallet:    ${data.wallet}`);
    if (data.solana) console.log(`  Solana Wallet: ${data.solana}`);
    console.log(`  Balance:       ${data.balance ?? "unknown"}`);
    if (data.isLow) console.log(`  \u26A0 Balance is low`);
    if (data.isEmpty) console.log(`  \u26A0 Balance is empty \u2014 using free models`);
    if (data.upstreamProxy) console.log(`  Upstream Proxy: ${data.upstreamProxy}`);
    console.log();
  } catch {
    console.error(`\u2717 Cannot connect to ClawRouter on port ${port}`);
    console.error(`  Is the proxy running? Start with: npx @blockrun/clawrouter`);
    process.exit(1);
  }
}
async function cmdWallet(port) {
  try {
    const data = await queryProxy("/health?full=true", port);
    console.log(`
ClawRouter Wallet
`);
    console.log(`  Payment Chain: ${data.paymentChain}`);
    console.log();
    console.log(`  Base (EVM):`);
    console.log(`    Address: ${data.wallet}`);
    console.log(`    Fund:    https://basescan.org/address/${data.wallet}`);
    if (data.solana) {
      console.log();
      console.log(`  Solana:`);
      console.log(`    Address: ${data.solana}`);
      console.log(`    Fund:    https://solscan.io/account/${data.solana}`);
    }
    console.log();
    console.log(`  Balance: ${data.balance ?? "unknown"} (USDC)`);
    if (data.isEmpty) console.log(`  \u26A0 Empty \u2014 fund wallet or use free models`);
    console.log();
  } catch {
    console.error(`\u2717 Cannot connect to ClawRouter on port ${port}`);
    process.exit(1);
  }
}
async function cmdModels(port) {
  try {
    const data = await queryProxy("/v1/models", port);
    console.log(`
Available Models (${data.data.length})
`);
    const groups = /* @__PURE__ */ new Map();
    for (const m of data.data) {
      const provider = m.id.includes("/") ? m.id.split("/")[0] : "blockrun";
      if (!groups.has(provider)) groups.set(provider, []);
      groups.get(provider).push(m.id);
    }
    for (const [provider, models] of groups) {
      console.log(`  ${provider} (${models.length}):`);
      for (const id of models) {
        console.log(`    ${id}`);
      }
      console.log();
    }
  } catch {
    console.error(`\u2717 Cannot connect to ClawRouter on port ${port}`);
    process.exit(1);
  }
}
async function cmdStats(port, days) {
  try {
    const data = await queryProxy(`/stats?days=${days}`, port);
    const stats = data;
    console.log(`
Usage Stats (last ${days} days)
`);
    console.log(`  Requests: ${stats.totalRequests ?? 0}`);
    console.log(`  Cost:     $${(stats.totalCostUsd ?? 0).toFixed(4)}`);
    if (stats.savedUsd) {
      console.log(
        `  Saved:    $${stats.savedUsd.toFixed(4)} (${stats.savingsPercent?.toFixed(0) ?? 0}% vs Opus)`
      );
    }
    if (stats.topModels && stats.topModels.length > 0) {
      console.log();
      console.log(`  Top Models:`);
      for (const m of stats.topModels.slice(0, 10)) {
        console.log(
          `    ${m.model.padEnd(40)} ${String(m.requests).padStart(5)} reqs  $${m.costUsd.toFixed(4)}`
        );
      }
    }
    console.log();
  } catch {
    console.error(`\u2717 Cannot connect to ClawRouter on port ${port}`);
    process.exit(1);
  }
}
async function cmdPhone(port, subcommand, numbersAction, arg, areaCode) {
  const base2 = `http://127.0.0.1:${port}`;
  async function postJson(path2, body) {
    const resp = await fetch(`${base2}${path2}`, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(body)
    });
    const text = await resp.text();
    if (!resp.ok) {
      if (resp.status === 402) {
        throw new Error(
          `Insufficient wallet balance (HTTP 402). Fund wallet via clawrouter wallet.
${text}`
        );
      }
      throw new Error(`HTTP ${resp.status}: ${text}`);
    }
    try {
      return JSON.parse(text);
    } catch {
      return text;
    }
  }
  function fmtExpiry(expiresAt) {
    const ms = new Date(expiresAt).getTime();
    if (!Number.isFinite(ms)) return expiresAt;
    const days = Math.round((ms - Date.now()) / (1e3 * 60 * 60 * 24));
    const dateStr = new Date(ms).toISOString().split("T")[0];
    if (days < 0) return `${dateStr} (expired ${-days}d ago)`;
    if (days <= 2) return `${dateStr} (in ${days}d) \u26A0 renew soon`;
    return `${dateStr} (in ${days}d)`;
  }
  try {
    if (subcommand === "numbers") {
      if (!numbersAction || numbersAction === "list") {
        const result = await postJson("/v1/phone/numbers/list", {});
        const numbers = result.numbers ?? [];
        if (numbers.length === 0) {
          console.log("\nNo phone numbers owned by this wallet.\n");
          console.log("Buy one with: clawrouter phone numbers buy US [--area-code 415]\n");
          return;
        }
        console.log(`
Active numbers (${numbers.length}):
`);
        const numWidth = Math.max(...numbers.map((n) => n.phone_number.length), 16);
        for (const n of numbers) {
          const country = (n.country ?? "??").padEnd(3);
          console.log(
            `  ${n.phone_number.padEnd(numWidth)}  ${country}  expires ${fmtExpiry(n.expires_at)}`
          );
        }
        console.log();
      } else if (numbersAction === "buy") {
        const country = (arg ?? "").toUpperCase();
        if (country !== "US" && country !== "CA") {
          console.error("\u2717 Country must be 'US' or 'CA'");
          console.error("  Usage: clawrouter phone numbers buy <US|CA> [--area-code <code>]");
          process.exit(1);
        }
        const body = { country };
        if (areaCode) body.areaCode = areaCode;
        console.log(
          `
Buying ${country} number${areaCode ? ` (area code ${areaCode})` : ""}... ($5.00 / 30-day lease)
`
        );
        const result = await postJson("/v1/phone/numbers/buy", body);
        if (result.phone_number) {
          console.log(`  \u2713 ${result.phone_number}`);
          if (result.expires_at) console.log(`    expires ${fmtExpiry(result.expires_at)}`);
          console.log();
        } else {
          console.log(JSON.stringify(result, null, 2));
        }
      } else if (numbersAction === "renew") {
        if (!arg) {
          console.error("\u2717 Usage: clawrouter phone numbers renew <+E.164-number>");
          process.exit(1);
        }
        console.log(`
Renewing ${arg}... ($5.00 / +30 days)
`);
        const result = await postJson("/v1/phone/numbers/renew", { phoneNumber: arg });
        console.log(`  \u2713 ${result.phone_number ?? arg}`);
        if (result.expires_at) console.log(`    expires ${fmtExpiry(result.expires_at)}`);
        console.log();
      } else if (numbersAction === "release") {
        if (!arg) {
          console.error("\u2717 Usage: clawrouter phone numbers release <+E.164-number>");
          process.exit(1);
        }
        console.log(`
Releasing ${arg}...
`);
        await postJson("/v1/phone/numbers/release", { phoneNumber: arg });
        console.log(`  \u2713 Released ${arg}
`);
      }
    } else if (subcommand === "lookup" || subcommand === "fraud") {
      if (!arg) {
        console.error(`\u2717 Usage: clawrouter phone ${subcommand} <+E.164-number>`);
        process.exit(1);
      }
      const path2 = subcommand === "fraud" ? "/v1/phone/lookup/fraud" : "/v1/phone/lookup";
      const price = subcommand === "fraud" ? "$0.05" : "$0.01";
      console.log(`
Looking up ${arg}... (${price})
`);
      const result = await postJson(path2, { phoneNumber: arg });
      console.log(JSON.stringify(result, null, 2));
      console.log();
    }
  } catch (err) {
    console.error(`\u2717 ${err instanceof Error ? err.message : String(err)}`);
    console.error(`  Is the proxy running on port ${port}? (start: npx @blockrun/clawrouter)`);
    process.exit(1);
  }
}
async function cmdCache(port) {
  try {
    const data = await queryProxy("/cache", port);
    console.log(`
Cache Stats
`);
    for (const [key, value] of Object.entries(data)) {
      console.log(`  ${key}: ${JSON.stringify(value)}`);
    }
    console.log();
  } catch {
    console.error(`\u2717 Cannot connect to ClawRouter on port ${port}`);
    process.exit(1);
  }
}
async function cmdSetup() {
  const { execFileSync, execSync } = await import("child_process");
  const { injectModelsConfig: injectModelsConfig2, injectAuthProfile: injectAuthProfile2 } = await Promise.resolve().then(() => (init_index(), index_exports));
  console.log("\u{1F99E} ClawRouter setup\n");
  let openclawPath;
  try {
    openclawPath = execSync("command -v openclaw", {
      encoding: "utf8",
      stdio: ["ignore", "pipe", "ignore"]
    }).trim();
    if (!openclawPath) throw new Error("not found");
    console.log(`  \u2713 Found openclaw at ${openclawPath}`);
  } catch {
    console.error("  \u2717 openclaw not found on PATH");
    console.error("    Install OpenClaw first: npm install -g openclaw");
    console.error("    Then re-run: clawrouter setup");
    process.exit(1);
  }
  console.log("\n\u2192 Registering ClawRouter with OpenClaw...");
  let installOk = false;
  try {
    execFileSync(openclawPath, ["plugins", "install", "--force", "@blockrun/clawrouter"], {
      stdio: "inherit"
    });
    installOk = true;
  } catch (err) {
    console.warn(
      `  \u26A0 openclaw plugins install reported a problem: ${err instanceof Error ? err.message : String(err)}`
    );
    console.warn("    Continuing with manual config sync \u2014 if validation rejected the install,");
    console.warn(
      "    re-run `openclaw plugins install --force @blockrun/clawrouter` after gateway start."
    );
  }
  console.log("\n\u2192 Syncing models allowlist + auth profile...");
  const setupLogger = {
    info: (msg) => console.log(`  ${msg}`)
  };
  try {
    injectModelsConfig2(setupLogger, { forceWrite: true });
    injectAuthProfile2(setupLogger);
  } catch (err) {
    console.error(`  \u2717 Config sync failed: ${err instanceof Error ? err.message : String(err)}`);
    process.exit(1);
  }
  if (installOk) {
    console.log("\n\u2713 Setup complete.");
  } else {
    console.log("\n\u2713 Models config synced (plugin registration may need a manual retry).");
  }
  console.log("\nNext: restart the gateway to load ClawRouter:");
  console.log("  openclaw gateway restart");
  console.log("\nThen verify in your bot: /models \u2014 you should see ~38 BlockRun models.");
}
function parseArgs(args) {
  const result = {
    version: false,
    help: false,
    doctor: false,
    logs: false,
    logsDays: 1,
    partners: false,
    partnersTest: false,
    report: false,
    reportPeriod: "daily",
    reportJson: false,
    walletRecover: false,
    chain: void 0,
    port: void 0,
    queryStatus: false,
    queryWallet: false,
    queryModels: false,
    queryStats: false,
    queryStatsDays: 7,
    queryCache: false,
    setup: false,
    share: false,
    shareTarget: void 0,
    sharePreset: void 0,
    shareLimit: 20,
    shareAll: false,
    phone: false,
    phoneSubcommand: void 0,
    phoneNumbersAction: void 0,
    phoneArg: void 0,
    phoneAreaCode: void 0
  };
  for (let i = 0; i < args.length; i++) {
    const arg = args[i];
    if (arg === "--version" || arg === "-v") {
      result.version = true;
    } else if (arg === "--help" || arg === "-h") {
      result.help = true;
    } else if (arg === "status") {
      result.queryStatus = true;
    } else if (arg === "models") {
      result.queryModels = true;
    } else if (arg === "stats") {
      result.queryStats = true;
      if (args[i + 1] === "--days" && args[i + 2]) {
        result.queryStatsDays = Math.min(parseInt(args[i + 2], 10) || 7, 30);
        i += 2;
      }
    } else if (arg === "cache") {
      result.queryCache = true;
    } else if (arg === "doctor" || arg === "--doctor") {
      result.doctor = true;
    } else if (arg === "logs") {
      result.logs = true;
      if (args[i + 1] === "--days" && args[i + 2]) {
        result.logsDays = parseInt(args[i + 2], 10) || 1;
        i += 2;
      }
    } else if (arg === "partners") {
      result.partners = true;
      if (args[i + 1] === "test") {
        result.partnersTest = true;
        i++;
      }
    } else if (arg === "report") {
      result.report = true;
      const next = args[i + 1];
      if (next && ["daily", "weekly", "monthly"].includes(next)) {
        result.reportPeriod = next;
        i++;
        if (args[i + 1] === "--json") {
          result.reportJson = true;
          i++;
        }
      } else if (next === "--json") {
        result.reportJson = true;
        i++;
      }
    } else if (arg === "wallet") {
      if (args[i + 1] === "recover") {
        result.walletRecover = true;
        i++;
      } else if (args[i + 1] === "solana" || args[i + 1] === "base") {
        result.chain = args[i + 1];
        i++;
      } else {
        result.queryWallet = true;
      }
    } else if ((arg === "chain" || arg === "/wallet") && (args[i + 1] === "solana" || args[i + 1] === "base")) {
      result.chain = args[i + 1];
      i++;
    } else if (arg === "--port" && args[i + 1]) {
      result.port = parseInt(args[i + 1], 10);
      i++;
    } else if (arg === "setup") {
      result.setup = true;
    } else if (arg === "phone") {
      result.phone = true;
      const next = args[i + 1];
      if (next === "numbers") {
        result.phoneSubcommand = "numbers";
        const action = args[i + 2];
        if (action === "list" || action === "buy" || action === "renew" || action === "release") {
          result.phoneNumbersAction = action;
          i += 2;
          const positional = args[i + 1];
          if (positional && !positional.startsWith("--")) {
            result.phoneArg = positional;
            i++;
          }
          while (i + 1 < args.length) {
            const flag = args[i + 1];
            if (flag === "--area-code" && args[i + 2]) {
              result.phoneAreaCode = args[i + 2];
              i += 2;
            } else if (flag.startsWith("--area-code=")) {
              result.phoneAreaCode = flag.slice("--area-code=".length);
              i++;
            } else break;
          }
        } else {
          i++;
        }
      } else if (next === "lookup" || next === "fraud") {
        result.phoneSubcommand = next;
        i++;
        const positional = args[i + 1];
        if (positional && !positional.startsWith("--")) {
          result.phoneArg = positional;
          i++;
        }
      }
    } else if (arg === "share") {
      result.share = true;
      const next = args[i + 1];
      if (next && !next.startsWith("--")) {
        result.shareTarget = next;
        i++;
      }
      while (i + 1 < args.length) {
        const flag = args[i + 1];
        if (flag === "--all") {
          result.shareAll = true;
          i++;
        } else if (flag === "--as" && args[i + 2]) {
          result.sharePreset = args[i + 2];
          i += 2;
        } else if (flag.startsWith("--as=")) {
          result.sharePreset = flag.slice("--as=".length);
          i++;
        } else if (flag === "--limit" && args[i + 2]) {
          result.shareLimit = Math.min(Math.max(parseInt(args[i + 2], 10) || 20, 1), 100);
          i += 2;
        } else if (flag.startsWith("--limit=")) {
          result.shareLimit = Math.min(
            Math.max(parseInt(flag.slice("--limit=".length), 10) || 20, 1),
            100
          );
          i++;
        } else {
          break;
        }
      }
    }
  }
  return result;
}
async function main() {
  const args = parseArgs(process.argv.slice(2));
  if (args.version) {
    console.log(VERSION);
    process.exit(0);
  }
  if (args.help) {
    printHelp();
    process.exit(0);
  }
  if (args.setup) {
    await cmdSetup();
    process.exit(0);
  }
  const queryPort = args.port ?? getProxyPort();
  if (args.queryStatus) {
    await cmdStatus(queryPort);
    process.exit(0);
  }
  if (args.queryWallet) {
    await cmdWallet(queryPort);
    process.exit(0);
  }
  if (args.queryModels) {
    await cmdModels(queryPort);
    process.exit(0);
  }
  if (args.queryStats) {
    await cmdStats(queryPort, args.queryStatsDays);
    process.exit(0);
  }
  if (args.queryCache) {
    await cmdCache(queryPort);
    process.exit(0);
  }
  if (args.share) {
    await cmdShare(queryPort, args.shareTarget, args.sharePreset, args.shareLimit, args.shareAll);
    process.exit(0);
  }
  if (args.phone) {
    if (!args.phoneSubcommand) {
      console.error("\u2717 Usage: clawrouter phone <numbers|lookup|fraud> ...");
      console.error("  See: clawrouter --help");
      process.exit(1);
    }
    await cmdPhone(
      queryPort,
      args.phoneSubcommand,
      args.phoneNumbersAction,
      args.phoneArg,
      args.phoneAreaCode
    );
    process.exit(0);
  }
  if (args.doctor) {
    const rawArgs = process.argv.slice(2);
    const doctorIndex = rawArgs.findIndex((a) => a === "doctor" || a === "--doctor");
    const afterDoctor = rawArgs.slice(doctorIndex + 1);
    let model = "sonnet";
    let questionArgs = afterDoctor;
    if (afterDoctor[0] === "opus") {
      model = "opus";
      questionArgs = afterDoctor.slice(1);
    } else if (afterDoctor[0] === "sonnet") {
      model = "sonnet";
      questionArgs = afterDoctor.slice(1);
    }
    const userQuestion = questionArgs.join(" ").trim() || void 0;
    await runDoctor(userQuestion, model);
    process.exit(0);
  }
  if (args.logs) {
    const output = await formatRecentLogs(args.logsDays);
    console.log(output);
    process.exit(0);
  }
  if (args.partners) {
    if (PARTNER_SERVICES.length === 0) {
      console.log("No partner APIs available.");
      process.exit(0);
    }
    console.log(`
ClawRouter Partner APIs (v${VERSION})
`);
    const byCategory = /* @__PURE__ */ new Map();
    for (const svc of PARTNER_SERVICES) {
      const bucket = byCategory.get(svc.category) ?? [];
      bucket.push(svc);
      byCategory.set(svc.category, bucket);
    }
    const toolWidth = Math.max(...PARTNER_SERVICES.map((s3) => `blockrun_${s3.id}`.length), 28);
    const priceWidth = Math.max(
      ...PARTNER_SERVICES.map(
        (s3) => s3.pricing.perUnit === "free" ? 4 : `${s3.pricing.perUnit}/${s3.pricing.unit}`.length
      ),
      12
    );
    for (const [category, services] of byCategory) {
      console.log(`${category}`);
      for (const svc of services) {
        const tool = `blockrun_${svc.id}`.padEnd(toolWidth);
        const price = (svc.pricing.perUnit === "free" ? "free" : `${svc.pricing.perUnit}/${svc.pricing.unit}`).padEnd(priceWidth);
        console.log(`  ${tool}  ${price}  ${svc.shortDescription}`);
      }
      console.log();
    }
    if (args.partnersTest) {
      console.log("Testing partner endpoints...\n");
      const apiBase = "https://blockrun.ai/api";
      for (const svc of PARTNER_SERVICES) {
        const url = `${apiBase}/v1${svc.proxyPath}`;
        try {
          const response = await fetch(url, { method: "GET" });
          const status = response.status;
          const ok = status === 402 ? "alive (402 = payment required)" : `status ${status}`;
          console.log(`  ${svc.id}: ${ok}`);
        } catch (err) {
          console.log(`  ${svc.id}: error - ${err instanceof Error ? err.message : String(err)}`);
        }
      }
      console.log();
    }
    process.exit(0);
  }
  if (args.walletRecover) {
    await recoverWalletFromMnemonic();
    process.exit(0);
  }
  if (args.chain) {
    const targetChain = args.chain;
    if (targetChain === "solana") {
      const { existsSync: existsSync5 } = await import("fs");
      const { MNEMONIC_FILE: MNEMONIC_FILE2, setupSolana: setupSolana2 } = await Promise.resolve().then(() => (init_auth(), auth_exports));
      const { deriveSolanaKeyBytes: deriveSolanaKeyBytes2, getSolanaAddress: getSolanaAddress2 } = await Promise.resolve().then(() => (init_wallet(), wallet_exports));
      let solanaAddr;
      if (existsSync5(MNEMONIC_FILE2)) {
        const { readFileSync: readFileSync4 } = await import("fs");
        const mnemonic = readFileSync4(MNEMONIC_FILE2, "utf8").trim();
        const keyBytes = deriveSolanaKeyBytes2(mnemonic);
        solanaAddr = await getSolanaAddress2(keyBytes);
        console.log(`[ClawRouter] Solana wallet already set up.`);
      } else {
        console.log(`[ClawRouter] Setting up Solana wallet...`);
        const { solanaPrivateKeyBytes } = await setupSolana2();
        solanaAddr = await getSolanaAddress2(solanaPrivateKeyBytes);
        console.log(`[ClawRouter] Solana wallet created.`);
        console.log(`[ClawRouter] \u26A0  Back up your mnemonic: ${MNEMONIC_FILE2}`);
      }
      await savePaymentChain("solana");
      console.log(`[ClawRouter] Payment chain \u2192 Solana`);
      console.log(`[ClawRouter] Solana address : ${solanaAddr}`);
      console.log(`[ClawRouter] Fund USDC at   : https://solscan.io/account/${solanaAddr}`);
    } else {
      await savePaymentChain("base");
      console.log(`[ClawRouter] Payment chain \u2192 Base (EVM)`);
    }
    console.log(
      `[ClawRouter] Restart gateway to apply: systemctl --user restart openclaw-gateway.service`
    );
    console.log(`[ClawRouter]   or: openclaw gateway restart`);
    process.exit(0);
  }
  if (args.report) {
    const report = await generateReport(args.reportPeriod, args.reportJson);
    console.log(report);
    process.exit(0);
  }
  const wallet = await resolveOrGenerateWalletKey();
  if (wallet.source === "generated") {
    console.log(`[ClawRouter] Generated new wallet: ${wallet.address}`);
  } else if (wallet.source === "saved") {
    console.log(`[ClawRouter] Using saved wallet: ${wallet.address}`);
  } else if (wallet.source === "config") {
    console.log(`[ClawRouter] Using wallet from plugin config: ${wallet.address}`);
  } else {
    console.log(`[ClawRouter] Using wallet from BLOCKRUN_WALLET_KEY: ${wallet.address}`);
  }
  if (wallet.solanaPrivateKeyBytes) {
    try {
      const solAddr = await getSolanaAddress(wallet.solanaPrivateKeyBytes);
      console.log(`[ClawRouter] Solana address: ${solAddr}`);
    } catch {
    }
  }
  const proxy = await startProxy({
    wallet,
    port: args.port,
    onReady: (port) => {
      console.log(`[ClawRouter] v${VERSION} | Proxy listening on http://127.0.0.1:${port}`);
      console.log(`[ClawRouter] Health check: http://127.0.0.1:${port}/health`);
    },
    onError: (error) => {
      console.error(`[ClawRouter] Error: ${error.message}`);
    },
    onRouted: (decision) => {
      const cost = decision.costEstimate.toFixed(4);
      const saved = (decision.savings * 100).toFixed(0);
      console.log(`[ClawRouter] [${decision.tier}] ${decision.model} $${cost} (saved ${saved}%)`);
    },
    onLowBalance: (info) => {
      console.warn(`[ClawRouter] Low balance: ${info.balanceUSD}. Fund: ${info.walletAddress}`);
    },
    onInsufficientFunds: (info) => {
      console.error(
        `[ClawRouter] Insufficient funds. Balance: ${info.balanceUSD}, Need: ${info.requiredUSD}`
      );
      console.error(`[ClawRouter] Need help? Run: npx @blockrun/clawrouter doctor`);
    }
  });
  const paymentChain = await resolvePaymentChain();
  const displayAddress = paymentChain === "solana" && proxy.solanaAddress ? proxy.solanaAddress : wallet.address;
  try {
    const balance = await proxy.balanceMonitor.checkBalance();
    if (balance.isEmpty) {
      console.log(`[ClawRouter] Wallet balance: $0.00 (using FREE model)`);
      console.log(`[ClawRouter] Fund wallet for premium models: ${displayAddress}`);
    } else if (balance.isLow) {
      console.log(`[ClawRouter] Wallet balance: ${balance.balanceUSD} (low)`);
    } else {
      console.log(`[ClawRouter] Wallet balance: ${balance.balanceUSD}`);
    }
    proxy.balanceMonitor.invalidate();
  } catch {
    console.log(`[ClawRouter] Wallet: ${displayAddress} (balance check pending)`);
  }
  console.log(`[ClawRouter] Ready - Ctrl+C to stop`);
  const shutdown = async (signal) => {
    console.log(`
[ClawRouter] Received ${signal}, shutting down...`);
    try {
      await proxy.close();
      console.log(`[ClawRouter] Proxy closed`);
      process.exit(0);
    } catch (err) {
      console.error(`[ClawRouter] Error during shutdown: ${err}`);
      process.exit(1);
    }
  };
  process.on("SIGINT", () => shutdown("SIGINT"));
  process.on("SIGTERM", () => shutdown("SIGTERM"));
  await new Promise(() => {
  });
}
main().catch((err) => {
  console.error(`[ClawRouter] Fatal error: ${err.message}`);
  console.error(`[ClawRouter] Need help? Run: npx @blockrun/clawrouter doctor`);
  process.exit(1);
});
/*! Bundled license information:

@noble/hashes/esm/utils.js:
@noble/hashes/esm/utils.js:
@noble/hashes/esm/utils.js:
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)

@noble/curves/esm/abstract/utils.js:
@noble/curves/esm/abstract/modular.js:
@noble/curves/esm/abstract/curve.js:
@noble/curves/esm/abstract/weierstrass.js:
@noble/curves/esm/_shortw_utils.js:
@noble/curves/esm/secp256k1.js:
@noble/curves/esm/abstract/utils.js:
@noble/curves/esm/abstract/modular.js:
@noble/curves/esm/abstract/curve.js:
@noble/curves/esm/abstract/weierstrass.js:
@noble/curves/esm/_shortw_utils.js:
@noble/curves/esm/secp256k1.js:
@noble/curves/utils.js:
@noble/curves/abstract/modular.js:
@noble/curves/abstract/curve.js:
@noble/curves/abstract/weierstrass.js:
@noble/curves/secp256k1.js:
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)

@scure/base/lib/esm/index.js:
@scure/base/index.js:
  (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)

@scure/bip39/esm/index.js:
  (*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *)

@scure/bip32/index.js:
  (*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *)

undici/lib/web/fetch/body.js:
  (*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> *)

undici/lib/web/websocket/frame.js:
  (*! ws. MIT License. Einar Otto Stangvik <einaros@gmail.com> *)
*/
//# sourceMappingURL=cli.js.map