UNPKG

agentswarm

Version:

LLM-agnostic typescript framework for creating OpenAI-style Swarm agents with the Vercel AI SDK

18,512 lines • 593 kB
import { createRequire } from "node:module";
var __create = Object.create;
var __getProtoOf = Object.getPrototypeOf;
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __toESM = (mod, isNodeMode, target) => {
  target = mod != null ? __create(__getProtoOf(mod)) : {};
  const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
  for (let key of __getOwnPropNames(mod))
    if (!__hasOwnProp.call(to, key))
      __defProp(to, key, {
        get: () => mod[key],
        enumerable: true
      });
  return to;
};
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __require = /* @__PURE__ */ createRequire(import.meta.url);

// node_modules/nunjucks/src/lib.js
var require_lib = __commonJS((exports, module) => {
  var ArrayProto = Array.prototype;
  var ObjProto = Object.prototype;
  var escapeMap = {
    "&": "&",
    '"': """,
    "'": "'",
    "<": "&lt;",
    ">": "&gt;",
    "\\": "&#92;"
  };
  var escapeRegex = /[&"'<>\\]/g;
  var _exports = module.exports = {};
  function hasOwnProp(obj, k) {
    return ObjProto.hasOwnProperty.call(obj, k);
  }
  _exports.hasOwnProp = hasOwnProp;
  function lookupEscape(ch) {
    return escapeMap[ch];
  }
  function _prettifyError(path, withInternals, err) {
    if (!err.Update) {
      err = new _exports.TemplateError(err);
    }
    err.Update(path);
    if (!withInternals) {
      var old = err;
      err = new Error(old.message);
      err.name = old.name;
    }
    return err;
  }
  _exports._prettifyError = _prettifyError;
  function TemplateError(message, lineno, colno) {
    var err;
    var cause;
    if (message instanceof Error) {
      cause = message;
      message = cause.name + ": " + cause.message;
    }
    if (Object.setPrototypeOf) {
      err = new Error(message);
      Object.setPrototypeOf(err, TemplateError.prototype);
    } else {
      err = this;
      Object.defineProperty(err, "message", {
        enumerable: false,
        writable: true,
        value: message
      });
    }
    Object.defineProperty(err, "name", {
      value: "Template render error"
    });
    if (Error.captureStackTrace) {
      Error.captureStackTrace(err, this.constructor);
    }
    var getStack;
    if (cause) {
      var stackDescriptor = Object.getOwnPropertyDescriptor(cause, "stack");
      getStack = stackDescriptor && (stackDescriptor.get || function() {
        return stackDescriptor.value;
      });
      if (!getStack) {
        getStack = function getStack() {
          return cause.stack;
        };
      }
    } else {
      var stack = new Error(message).stack;
      getStack = function getStack() {
        return stack;
      };
    }
    Object.defineProperty(err, "stack", {
      get: function get() {
        return getStack.call(err);
      }
    });
    Object.defineProperty(err, "cause", {
      value: cause
    });
    err.lineno = lineno;
    err.colno = colno;
    err.firstUpdate = true;
    err.Update = function Update(path) {
      var msg = "(" + (path || "unknown path") + ")";
      if (this.firstUpdate) {
        if (this.lineno && this.colno) {
          msg += " [Line " + this.lineno + ", Column " + this.colno + "]";
        } else if (this.lineno) {
          msg += " [Line " + this.lineno + "]";
        }
      }
      msg += `
 `;
      if (this.firstUpdate) {
        msg += " ";
      }
      this.message = msg + (this.message || "");
      this.firstUpdate = false;
      return this;
    };
    return err;
  }
  if (Object.setPrototypeOf) {
    Object.setPrototypeOf(TemplateError.prototype, Error.prototype);
  } else {
    TemplateError.prototype = Object.create(Error.prototype, {
      constructor: {
        value: TemplateError
      }
    });
  }
  _exports.TemplateError = TemplateError;
  function escape(val) {
    return val.replace(escapeRegex, lookupEscape);
  }
  _exports.escape = escape;
  function isFunction(obj) {
    return ObjProto.toString.call(obj) === "[object Function]";
  }
  _exports.isFunction = isFunction;
  function isArray(obj) {
    return ObjProto.toString.call(obj) === "[object Array]";
  }
  _exports.isArray = isArray;
  function isString(obj) {
    return ObjProto.toString.call(obj) === "[object String]";
  }
  _exports.isString = isString;
  function isObject(obj) {
    return ObjProto.toString.call(obj) === "[object Object]";
  }
  _exports.isObject = isObject;
  function _prepareAttributeParts(attr) {
    if (!attr) {
      return [];
    }
    if (typeof attr === "string") {
      return attr.split(".");
    }
    return [attr];
  }
  function getAttrGetter(attribute) {
    var parts = _prepareAttributeParts(attribute);
    return function attrGetter(item) {
      var _item = item;
      for (var i = 0;i < parts.length; i++) {
        var part = parts[i];
        if (hasOwnProp(_item, part)) {
          _item = _item[part];
        } else {
          return;
        }
      }
      return _item;
    };
  }
  _exports.getAttrGetter = getAttrGetter;
  function groupBy(obj, val, throwOnUndefined) {
    var result = {};
    var iterator = isFunction(val) ? val : getAttrGetter(val);
    for (var i = 0;i < obj.length; i++) {
      var value = obj[i];
      var key = iterator(value, i);
      if (key === undefined && throwOnUndefined === true) {
        throw new TypeError('groupby: attribute "' + val + '" resolved to undefined');
      }
      (result[key] || (result[key] = [])).push(value);
    }
    return result;
  }
  _exports.groupBy = groupBy;
  function toArray(obj) {
    return Array.prototype.slice.call(obj);
  }
  _exports.toArray = toArray;
  function without(array) {
    var result = [];
    if (!array) {
      return result;
    }
    var length = array.length;
    var contains = toArray(arguments).slice(1);
    var index = -1;
    while (++index < length) {
      if (indexOf(contains, array[index]) === -1) {
        result.push(array[index]);
      }
    }
    return result;
  }
  _exports.without = without;
  function repeat(char_, n) {
    var str = "";
    for (var i = 0;i < n; i++) {
      str += char_;
    }
    return str;
  }
  _exports.repeat = repeat;
  function each(obj, func, context) {
    if (obj == null) {
      return;
    }
    if (ArrayProto.forEach && obj.forEach === ArrayProto.forEach) {
      obj.forEach(func, context);
    } else if (obj.length === +obj.length) {
      for (var i = 0, l = obj.length;i < l; i++) {
        func.call(context, obj[i], i, obj);
      }
    }
  }
  _exports.each = each;
  function map(obj, func) {
    var results = [];
    if (obj == null) {
      return results;
    }
    if (ArrayProto.map && obj.map === ArrayProto.map) {
      return obj.map(func);
    }
    for (var i = 0;i < obj.length; i++) {
      results[results.length] = func(obj[i], i);
    }
    if (obj.length === +obj.length) {
      results.length = obj.length;
    }
    return results;
  }
  _exports.map = map;
  function asyncIter(arr, iter, cb) {
    var i = -1;
    function next() {
      i++;
      if (i < arr.length) {
        iter(arr[i], i, next, cb);
      } else {
        cb();
      }
    }
    next();
  }
  _exports.asyncIter = asyncIter;
  function asyncFor(obj, iter, cb) {
    var keys = keys_(obj || {});
    var len = keys.length;
    var i = -1;
    function next() {
      i++;
      var k = keys[i];
      if (i < len) {
        iter(k, obj[k], i, len, next);
      } else {
        cb();
      }
    }
    next();
  }
  _exports.asyncFor = asyncFor;
  function indexOf(arr, searchElement, fromIndex) {
    return Array.prototype.indexOf.call(arr || [], searchElement, fromIndex);
  }
  _exports.indexOf = indexOf;
  function keys_(obj) {
    var arr = [];
    for (var k in obj) {
      if (hasOwnProp(obj, k)) {
        arr.push(k);
      }
    }
    return arr;
  }
  _exports.keys = keys_;
  function _entries(obj) {
    return keys_(obj).map(function(k) {
      return [k, obj[k]];
    });
  }
  _exports._entries = _entries;
  function _values(obj) {
    return keys_(obj).map(function(k) {
      return obj[k];
    });
  }
  _exports._values = _values;
  function extend(obj1, obj2) {
    obj1 = obj1 || {};
    keys_(obj2).forEach(function(k) {
      obj1[k] = obj2[k];
    });
    return obj1;
  }
  _exports._assign = _exports.extend = extend;
  function inOperator(key, val) {
    if (isArray(val) || isString(val)) {
      return val.indexOf(key) !== -1;
    } else if (isObject(val)) {
      return key in val;
    }
    throw new Error('Cannot use "in" operator to search for "' + key + '" in unexpected types.');
  }
  _exports.inOperator = inOperator;
});

// node_modules/asap/raw.js
var require_raw = __commonJS((exports, module) => {
  var domain;
  var hasSetImmediate = typeof setImmediate === "function";
  module.exports = rawAsap;
  function rawAsap(task) {
    if (!queue.length) {
      requestFlush();
      flushing = true;
    }
    queue[queue.length] = task;
  }
  var queue = [];
  var flushing = false;
  var index = 0;
  var capacity = 1024;
  function flush() {
    while (index < queue.length) {
      var currentIndex = index;
      index = index + 1;
      queue[currentIndex].call();
      if (index > capacity) {
        for (var scan = 0, newLength = queue.length - index;scan < newLength; scan++) {
          queue[scan] = queue[scan + index];
        }
        queue.length -= index;
        index = 0;
      }
    }
    queue.length = 0;
    index = 0;
    flushing = false;
  }
  rawAsap.requestFlush = requestFlush;
  function requestFlush() {
    var parentDomain = process.domain;
    if (parentDomain) {
      if (!domain) {
        domain = __require("domain");
      }
      domain.active = process.domain = null;
    }
    if (flushing && hasSetImmediate) {
      setImmediate(flush);
    } else {
      process.nextTick(flush);
    }
    if (parentDomain) {
      domain.active = process.domain = parentDomain;
    }
  }
});

// node_modules/asap/asap.js
var require_asap = __commonJS((exports, module) => {
  var rawAsap = require_raw();
  var freeTasks = [];
  module.exports = asap;
  function asap(task) {
    var rawTask;
    if (freeTasks.length) {
      rawTask = freeTasks.pop();
    } else {
      rawTask = new RawTask;
    }
    rawTask.task = task;
    rawTask.domain = process.domain;
    rawAsap(rawTask);
  }
  function RawTask() {
    this.task = null;
    this.domain = null;
  }
  RawTask.prototype.call = function() {
    if (this.domain) {
      this.domain.enter();
    }
    var threw = true;
    try {
      this.task.call();
      threw = false;
      if (this.domain) {
        this.domain.exit();
      }
    } finally {
      if (threw) {
        rawAsap.requestFlush();
      }
      this.task = null;
      this.domain = null;
      freeTasks.push(this);
    }
  };
});

// node_modules/a-sync-waterfall/index.js
var require_a_sync_waterfall = __commonJS((exports, module) => {
  (function(globals) {
    var executeSync = function() {
      var args = Array.prototype.slice.call(arguments);
      if (typeof args[0] === "function") {
        args[0].apply(null, args.splice(1));
      }
    };
    var executeAsync = function(fn) {
      if (typeof setImmediate === "function") {
        setImmediate(fn);
      } else if (typeof process !== "undefined" && process.nextTick) {
        process.nextTick(fn);
      } else {
        setTimeout(fn, 0);
      }
    };
    var makeIterator = function(tasks) {
      var makeCallback = function(index) {
        var fn = function() {
          if (tasks.length) {
            tasks[index].apply(null, arguments);
          }
          return fn.next();
        };
        fn.next = function() {
          return index < tasks.length - 1 ? makeCallback(index + 1) : null;
        };
        return fn;
      };
      return makeCallback(0);
    };
    var _isArray = Array.isArray || function(maybeArray) {
      return Object.prototype.toString.call(maybeArray) === "[object Array]";
    };
    var waterfall = function(tasks, callback, forceAsync) {
      var nextTick = forceAsync ? executeAsync : executeSync;
      callback = callback || function() {
      };
      if (!_isArray(tasks)) {
        var err = new Error("First argument to waterfall must be an array of functions");
        return callback(err);
      }
      if (!tasks.length) {
        return callback();
      }
      var wrapIterator = function(iterator) {
        return function(err2) {
          if (err2) {
            callback.apply(null, arguments);
            callback = function() {
            };
          } else {
            var args = Array.prototype.slice.call(arguments, 1);
            var next = iterator.next();
            if (next) {
              args.push(wrapIterator(next));
            } else {
              args.push(callback);
            }
            nextTick(function() {
              iterator.apply(null, args);
            });
          }
        };
      };
      wrapIterator(makeIterator(tasks))();
    };
    if (typeof define !== "undefined" && define.amd) {
      define([], function() {
        return waterfall;
      });
    } else if (typeof module !== "undefined" && module.exports) {
      module.exports = waterfall;
    } else {
      globals.waterfall = waterfall;
    }
  })(exports);
});

// node_modules/nunjucks/src/lexer.js
var require_lexer = __commonJS((exports, module) => {
  var lib = require_lib();
  var whitespaceChars = ` 
\t\r `;
  var delimChars = "()[]{}%*-+~/#,:|.<>=!";
  var intChars = "0123456789";
  var BLOCK_START = "{%";
  var BLOCK_END = "%}";
  var VARIABLE_START = "{{";
  var VARIABLE_END = "}}";
  var COMMENT_START = "{#";
  var COMMENT_END = "#}";
  var TOKEN_STRING = "string";
  var TOKEN_WHITESPACE = "whitespace";
  var TOKEN_DATA = "data";
  var TOKEN_BLOCK_START = "block-start";
  var TOKEN_BLOCK_END = "block-end";
  var TOKEN_VARIABLE_START = "variable-start";
  var TOKEN_VARIABLE_END = "variable-end";
  var TOKEN_COMMENT = "comment";
  var TOKEN_LEFT_PAREN = "left-paren";
  var TOKEN_RIGHT_PAREN = "right-paren";
  var TOKEN_LEFT_BRACKET = "left-bracket";
  var TOKEN_RIGHT_BRACKET = "right-bracket";
  var TOKEN_LEFT_CURLY = "left-curly";
  var TOKEN_RIGHT_CURLY = "right-curly";
  var TOKEN_OPERATOR = "operator";
  var TOKEN_COMMA = "comma";
  var TOKEN_COLON = "colon";
  var TOKEN_TILDE = "tilde";
  var TOKEN_PIPE = "pipe";
  var TOKEN_INT = "int";
  var TOKEN_FLOAT = "float";
  var TOKEN_BOOLEAN = "boolean";
  var TOKEN_NONE = "none";
  var TOKEN_SYMBOL = "symbol";
  var TOKEN_SPECIAL = "special";
  var TOKEN_REGEX = "regex";
  function token(type, value, lineno, colno) {
    return {
      type,
      value,
      lineno,
      colno
    };
  }
  var Tokenizer = /* @__PURE__ */ function() {
    function Tokenizer2(str, opts) {
      this.str = str;
      this.index = 0;
      this.len = str.length;
      this.lineno = 0;
      this.colno = 0;
      this.in_code = false;
      opts = opts || {};
      var tags = opts.tags || {};
      this.tags = {
        BLOCK_START: tags.blockStart || BLOCK_START,
        BLOCK_END: tags.blockEnd || BLOCK_END,
        VARIABLE_START: tags.variableStart || VARIABLE_START,
        VARIABLE_END: tags.variableEnd || VARIABLE_END,
        COMMENT_START: tags.commentStart || COMMENT_START,
        COMMENT_END: tags.commentEnd || COMMENT_END
      };
      this.trimBlocks = !!opts.trimBlocks;
      this.lstripBlocks = !!opts.lstripBlocks;
    }
    var _proto = Tokenizer2.prototype;
    _proto.nextToken = function nextToken() {
      var lineno = this.lineno;
      var colno = this.colno;
      var tok;
      if (this.in_code) {
        var cur = this.current();
        if (this.isFinished()) {
          return null;
        } else if (cur === '"' || cur === "'") {
          return token(TOKEN_STRING, this._parseString(cur), lineno, colno);
        } else if (tok = this._extract(whitespaceChars)) {
          return token(TOKEN_WHITESPACE, tok, lineno, colno);
        } else if ((tok = this._extractString(this.tags.BLOCK_END)) || (tok = this._extractString("-" + this.tags.BLOCK_END))) {
          this.in_code = false;
          if (this.trimBlocks) {
            cur = this.current();
            if (cur === `
`) {
              this.forward();
            } else if (cur === "\r") {
              this.forward();
              cur = this.current();
              if (cur === `
`) {
                this.forward();
              } else {
                this.back();
              }
            }
          }
          return token(TOKEN_BLOCK_END, tok, lineno, colno);
        } else if ((tok = this._extractString(this.tags.VARIABLE_END)) || (tok = this._extractString("-" + this.tags.VARIABLE_END))) {
          this.in_code = false;
          return token(TOKEN_VARIABLE_END, tok, lineno, colno);
        } else if (cur === "r" && this.str.charAt(this.index + 1) === "/") {
          this.forwardN(2);
          var regexBody = "";
          while (!this.isFinished()) {
            if (this.current() === "/" && this.previous() !== "\\") {
              this.forward();
              break;
            } else {
              regexBody += this.current();
              this.forward();
            }
          }
          var POSSIBLE_FLAGS = ["g", "i", "m", "y"];
          var regexFlags = "";
          while (!this.isFinished()) {
            var isCurrentAFlag = POSSIBLE_FLAGS.indexOf(this.current()) !== -1;
            if (isCurrentAFlag) {
              regexFlags += this.current();
              this.forward();
            } else {
              break;
            }
          }
          return token(TOKEN_REGEX, {
            body: regexBody,
            flags: regexFlags
          }, lineno, colno);
        } else if (delimChars.indexOf(cur) !== -1) {
          this.forward();
          var complexOps = ["==", "===", "!=", "!==", "<=", ">=", "//", "**"];
          var curComplex = cur + this.current();
          var type;
          if (lib.indexOf(complexOps, curComplex) !== -1) {
            this.forward();
            cur = curComplex;
            if (lib.indexOf(complexOps, curComplex + this.current()) !== -1) {
              cur = curComplex + this.current();
              this.forward();
            }
          }
          switch (cur) {
            case "(":
              type = TOKEN_LEFT_PAREN;
              break;
            case ")":
              type = TOKEN_RIGHT_PAREN;
              break;
            case "[":
              type = TOKEN_LEFT_BRACKET;
              break;
            case "]":
              type = TOKEN_RIGHT_BRACKET;
              break;
            case "{":
              type = TOKEN_LEFT_CURLY;
              break;
            case "}":
              type = TOKEN_RIGHT_CURLY;
              break;
            case ",":
              type = TOKEN_COMMA;
              break;
            case ":":
              type = TOKEN_COLON;
              break;
            case "~":
              type = TOKEN_TILDE;
              break;
            case "|":
              type = TOKEN_PIPE;
              break;
            default:
              type = TOKEN_OPERATOR;
          }
          return token(type, cur, lineno, colno);
        } else {
          tok = this._extractUntil(whitespaceChars + delimChars);
          if (tok.match(/^[-+]?[0-9]+$/)) {
            if (this.current() === ".") {
              this.forward();
              var dec = this._extract(intChars);
              return token(TOKEN_FLOAT, tok + "." + dec, lineno, colno);
            } else {
              return token(TOKEN_INT, tok, lineno, colno);
            }
          } else if (tok.match(/^(true|false)$/)) {
            return token(TOKEN_BOOLEAN, tok, lineno, colno);
          } else if (tok === "none") {
            return token(TOKEN_NONE, tok, lineno, colno);
          } else if (tok === "null") {
            return token(TOKEN_NONE, tok, lineno, colno);
          } else if (tok) {
            return token(TOKEN_SYMBOL, tok, lineno, colno);
          } else {
            throw new Error("Unexpected value while parsing: " + tok);
          }
        }
      } else {
        var beginChars = this.tags.BLOCK_START.charAt(0) + this.tags.VARIABLE_START.charAt(0) + this.tags.COMMENT_START.charAt(0) + this.tags.COMMENT_END.charAt(0);
        if (this.isFinished()) {
          return null;
        } else if ((tok = this._extractString(this.tags.BLOCK_START + "-")) || (tok = this._extractString(this.tags.BLOCK_START))) {
          this.in_code = true;
          return token(TOKEN_BLOCK_START, tok, lineno, colno);
        } else if ((tok = this._extractString(this.tags.VARIABLE_START + "-")) || (tok = this._extractString(this.tags.VARIABLE_START))) {
          this.in_code = true;
          return token(TOKEN_VARIABLE_START, tok, lineno, colno);
        } else {
          tok = "";
          var data;
          var inComment = false;
          if (this._matches(this.tags.COMMENT_START)) {
            inComment = true;
            tok = this._extractString(this.tags.COMMENT_START);
          }
          while ((data = this._extractUntil(beginChars)) !== null) {
            tok += data;
            if ((this._matches(this.tags.BLOCK_START) || this._matches(this.tags.VARIABLE_START) || this._matches(this.tags.COMMENT_START)) && !inComment) {
              if (this.lstripBlocks && this._matches(this.tags.BLOCK_START) && this.colno > 0 && this.colno <= tok.length) {
                var lastLine = tok.slice(-this.colno);
                if (/^\s+$/.test(lastLine)) {
                  tok = tok.slice(0, -this.colno);
                  if (!tok.length) {
                    return this.nextToken();
                  }
                }
              }
              break;
            } else if (this._matches(this.tags.COMMENT_END)) {
              if (!inComment) {
                throw new Error("unexpected end of comment");
              }
              tok += this._extractString(this.tags.COMMENT_END);
              break;
            } else {
              tok += this.current();
              this.forward();
            }
          }
          if (data === null && inComment) {
            throw new Error("expected end of comment, got end of file");
          }
          return token(inComment ? TOKEN_COMMENT : TOKEN_DATA, tok, lineno, colno);
        }
      }
    };
    _proto._parseString = function _parseString(delimiter) {
      this.forward();
      var str = "";
      while (!this.isFinished() && this.current() !== delimiter) {
        var cur = this.current();
        if (cur === "\\") {
          this.forward();
          switch (this.current()) {
            case "n":
              str += `
`;
              break;
            case "t":
              str += "\t";
              break;
            case "r":
              str += "\r";
              break;
            default:
              str += this.current();
          }
          this.forward();
        } else {
          str += cur;
          this.forward();
        }
      }
      this.forward();
      return str;
    };
    _proto._matches = function _matches(str) {
      if (this.index + str.length > this.len) {
        return null;
      }
      var m = this.str.slice(this.index, this.index + str.length);
      return m === str;
    };
    _proto._extractString = function _extractString(str) {
      if (this._matches(str)) {
        this.forwardN(str.length);
        return str;
      }
      return null;
    };
    _proto._extractUntil = function _extractUntil(charString) {
      return this._extractMatching(true, charString || "");
    };
    _proto._extract = function _extract(charString) {
      return this._extractMatching(false, charString);
    };
    _proto._extractMatching = function _extractMatching(breakOnMatch, charString) {
      if (this.isFinished()) {
        return null;
      }
      var first = charString.indexOf(this.current());
      if (breakOnMatch && first === -1 || !breakOnMatch && first !== -1) {
        var t = this.current();
        this.forward();
        var idx = charString.indexOf(this.current());
        while ((breakOnMatch && idx === -1 || !breakOnMatch && idx !== -1) && !this.isFinished()) {
          t += this.current();
          this.forward();
          idx = charString.indexOf(this.current());
        }
        return t;
      }
      return "";
    };
    _proto._extractRegex = function _extractRegex(regex) {
      var matches = this.currentStr().match(regex);
      if (!matches) {
        return null;
      }
      this.forwardN(matches[0].length);
      return matches;
    };
    _proto.isFinished = function isFinished() {
      return this.index >= this.len;
    };
    _proto.forwardN = function forwardN(n) {
      for (var i = 0;i < n; i++) {
        this.forward();
      }
    };
    _proto.forward = function forward() {
      this.index++;
      if (this.previous() === `
`) {
        this.lineno++;
        this.colno = 0;
      } else {
        this.colno++;
      }
    };
    _proto.backN = function backN(n) {
      for (var i = 0;i < n; i++) {
        this.back();
      }
    };
    _proto.back = function back() {
      this.index--;
      if (this.current() === `
`) {
        this.lineno--;
        var idx = this.src.lastIndexOf(`
`, this.index - 1);
        if (idx === -1) {
          this.colno = this.index;
        } else {
          this.colno = this.index - idx;
        }
      } else {
        this.colno--;
      }
    };
    _proto.current = function current() {
      if (!this.isFinished()) {
        return this.str.charAt(this.index);
      }
      return "";
    };
    _proto.currentStr = function currentStr() {
      if (!this.isFinished()) {
        return this.str.substr(this.index);
      }
      return "";
    };
    _proto.previous = function previous() {
      return this.str.charAt(this.index - 1);
    };
    return Tokenizer2;
  }();
  module.exports = {
    lex: function lex(src, opts) {
      return new Tokenizer(src, opts);
    },
    TOKEN_STRING,
    TOKEN_WHITESPACE,
    TOKEN_DATA,
    TOKEN_BLOCK_START,
    TOKEN_BLOCK_END,
    TOKEN_VARIABLE_START,
    TOKEN_VARIABLE_END,
    TOKEN_COMMENT,
    TOKEN_LEFT_PAREN,
    TOKEN_RIGHT_PAREN,
    TOKEN_LEFT_BRACKET,
    TOKEN_RIGHT_BRACKET,
    TOKEN_LEFT_CURLY,
    TOKEN_RIGHT_CURLY,
    TOKEN_OPERATOR,
    TOKEN_COMMA,
    TOKEN_COLON,
    TOKEN_TILDE,
    TOKEN_PIPE,
    TOKEN_INT,
    TOKEN_FLOAT,
    TOKEN_BOOLEAN,
    TOKEN_NONE,
    TOKEN_SYMBOL,
    TOKEN_SPECIAL,
    TOKEN_REGEX
  };
});

// node_modules/nunjucks/src/object.js
var require_object = __commonJS((exports, module) => {
  function _defineProperties(target, props) {
    for (var i = 0;i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor)
        descriptor.writable = true;
      Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
    }
  }
  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps)
      _defineProperties(Constructor.prototype, protoProps);
    if (staticProps)
      _defineProperties(Constructor, staticProps);
    Object.defineProperty(Constructor, "prototype", { writable: false });
    return Constructor;
  }
  function _toPropertyKey(arg) {
    var key = _toPrimitive(arg, "string");
    return typeof key === "symbol" ? key : String(key);
  }
  function _toPrimitive(input, hint) {
    if (typeof input !== "object" || input === null)
      return input;
    var prim = input[Symbol.toPrimitive];
    if (prim !== undefined) {
      var res = prim.call(input, hint || "default");
      if (typeof res !== "object")
        return res;
      throw new TypeError("@@toPrimitive must return a primitive value.");
    }
    return (hint === "string" ? String : Number)(input);
  }
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o2, p2) {
      o2.__proto__ = p2;
      return o2;
    };
    return _setPrototypeOf(o, p);
  }
  var EventEmitter = __require("events");
  var lib = require_lib();
  function parentWrap(parent, prop) {
    if (typeof parent !== "function" || typeof prop !== "function") {
      return prop;
    }
    return function wrap() {
      var tmp = this.parent;
      this.parent = parent;
      var res = prop.apply(this, arguments);
      this.parent = tmp;
      return res;
    };
  }
  function extendClass(cls, name, props) {
    props = props || {};
    lib.keys(props).forEach(function(k) {
      props[k] = parentWrap(cls.prototype[k], props[k]);
    });
    var subclass = /* @__PURE__ */ function(_cls) {
      _inheritsLoose(subclass2, _cls);
      function subclass2() {
        return _cls.apply(this, arguments) || this;
      }
      _createClass(subclass2, [{
        key: "typename",
        get: function get() {
          return name;
        }
      }]);
      return subclass2;
    }(cls);
    lib._assign(subclass.prototype, props);
    return subclass;
  }
  var Obj = /* @__PURE__ */ function() {
    function Obj2() {
      this.init.apply(this, arguments);
    }
    var _proto = Obj2.prototype;
    _proto.init = function init() {
    };
    Obj2.extend = function extend(name, props) {
      if (typeof name === "object") {
        props = name;
        name = "anonymous";
      }
      return extendClass(this, name, props);
    };
    _createClass(Obj2, [{
      key: "typename",
      get: function get() {
        return this.constructor.name;
      }
    }]);
    return Obj2;
  }();
  var EmitterObj = /* @__PURE__ */ function(_EventEmitter) {
    _inheritsLoose(EmitterObj2, _EventEmitter);
    function EmitterObj2() {
      var _this2;
      var _this;
      _this = _EventEmitter.call(this) || this;
      (_this2 = _this).init.apply(_this2, arguments);
      return _this;
    }
    var _proto2 = EmitterObj2.prototype;
    _proto2.init = function init() {
    };
    EmitterObj2.extend = function extend(name, props) {
      if (typeof name === "object") {
        props = name;
        name = "anonymous";
      }
      return extendClass(this, name, props);
    };
    _createClass(EmitterObj2, [{
      key: "typename",
      get: function get() {
        return this.constructor.name;
      }
    }]);
    return EmitterObj2;
  }(EventEmitter);
  module.exports = {
    Obj,
    EmitterObj
  };
});

// node_modules/nunjucks/src/nodes.js
var require_nodes = __commonJS((exports, module) => {
  function _defineProperties(target, props) {
    for (var i = 0;i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor)
        descriptor.writable = true;
      Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
    }
  }
  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps)
      _defineProperties(Constructor.prototype, protoProps);
    if (staticProps)
      _defineProperties(Constructor, staticProps);
    Object.defineProperty(Constructor, "prototype", { writable: false });
    return Constructor;
  }
  function _toPropertyKey(arg) {
    var key = _toPrimitive(arg, "string");
    return typeof key === "symbol" ? key : String(key);
  }
  function _toPrimitive(input, hint) {
    if (typeof input !== "object" || input === null)
      return input;
    var prim = input[Symbol.toPrimitive];
    if (prim !== undefined) {
      var res = prim.call(input, hint || "default");
      if (typeof res !== "object")
        return res;
      throw new TypeError("@@toPrimitive must return a primitive value.");
    }
    return (hint === "string" ? String : Number)(input);
  }
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o2, p2) {
      o2.__proto__ = p2;
      return o2;
    };
    return _setPrototypeOf(o, p);
  }
  var _require = require_object();
  var Obj = _require.Obj;
  function traverseAndCheck(obj, type, results) {
    if (obj instanceof type) {
      results.push(obj);
    }
    if (obj instanceof Node) {
      obj.findAll(type, results);
    }
  }
  var Node = /* @__PURE__ */ function(_Obj) {
    _inheritsLoose(Node2, _Obj);
    function Node2() {
      return _Obj.apply(this, arguments) || this;
    }
    var _proto = Node2.prototype;
    _proto.init = function init(lineno, colno) {
      var _arguments = arguments, _this = this;
      for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2;_key < _len; _key++) {
        args[_key - 2] = arguments[_key];
      }
      this.lineno = lineno;
      this.colno = colno;
      this.fields.forEach(function(field, i) {
        var val = _arguments[i + 2];
        if (val === undefined) {
          val = null;
        }
        _this[field] = val;
      });
    };
    _proto.findAll = function findAll(type, results) {
      var _this2 = this;
      results = results || [];
      if (this instanceof NodeList) {
        this.children.forEach(function(child) {
          return traverseAndCheck(child, type, results);
        });
      } else {
        this.fields.forEach(function(field) {
          return traverseAndCheck(_this2[field], type, results);
        });
      }
      return results;
    };
    _proto.iterFields = function iterFields(func) {
      var _this3 = this;
      this.fields.forEach(function(field) {
        func(_this3[field], field);
      });
    };
    return Node2;
  }(Obj);
  var Value = /* @__PURE__ */ function(_Node) {
    _inheritsLoose(Value2, _Node);
    function Value2() {
      return _Node.apply(this, arguments) || this;
    }
    _createClass(Value2, [{
      key: "typename",
      get: function get() {
        return "Value";
      }
    }, {
      key: "fields",
      get: function get() {
        return ["value"];
      }
    }]);
    return Value2;
  }(Node);
  var NodeList = /* @__PURE__ */ function(_Node2) {
    _inheritsLoose(NodeList2, _Node2);
    function NodeList2() {
      return _Node2.apply(this, arguments) || this;
    }
    var _proto2 = NodeList2.prototype;
    _proto2.init = function init(lineno, colno, nodes) {
      _Node2.prototype.init.call(this, lineno, colno, nodes || []);
    };
    _proto2.addChild = function addChild(node) {
      this.children.push(node);
    };
    _createClass(NodeList2, [{
      key: "typename",
      get: function get() {
        return "NodeList";
      }
    }, {
      key: "fields",
      get: function get() {
        return ["children"];
      }
    }]);
    return NodeList2;
  }(Node);
  var Root = NodeList.extend("Root");
  var Literal = Value.extend("Literal");
  var _Symbol = Value.extend("Symbol");
  var Group = NodeList.extend("Group");
  var ArrayNode = NodeList.extend("Array");
  var Pair = Node.extend("Pair", {
    fields: ["key", "value"]
  });
  var Dict = NodeList.extend("Dict");
  var LookupVal = Node.extend("LookupVal", {
    fields: ["target", "val"]
  });
  var If = Node.extend("If", {
    fields: ["cond", "body", "else_"]
  });
  var IfAsync = If.extend("IfAsync");
  var InlineIf = Node.extend("InlineIf", {
    fields: ["cond", "body", "else_"]
  });
  var For = Node.extend("For", {
    fields: ["arr", "name", "body", "else_"]
  });
  var AsyncEach = For.extend("AsyncEach");
  var AsyncAll = For.extend("AsyncAll");
  var Macro = Node.extend("Macro", {
    fields: ["name", "args", "body"]
  });
  var Caller = Macro.extend("Caller");
  var Import = Node.extend("Import", {
    fields: ["template", "target", "withContext"]
  });
  var FromImport = /* @__PURE__ */ function(_Node3) {
    _inheritsLoose(FromImport2, _Node3);
    function FromImport2() {
      return _Node3.apply(this, arguments) || this;
    }
    var _proto3 = FromImport2.prototype;
    _proto3.init = function init(lineno, colno, template, names, withContext) {
      _Node3.prototype.init.call(this, lineno, colno, template, names || new NodeList, withContext);
    };
    _createClass(FromImport2, [{
      key: "typename",
      get: function get() {
        return "FromImport";
      }
    }, {
      key: "fields",
      get: function get() {
        return ["template", "names", "withContext"];
      }
    }]);
    return FromImport2;
  }(Node);
  var FunCall = Node.extend("FunCall", {
    fields: ["name", "args"]
  });
  var Filter = FunCall.extend("Filter");
  var FilterAsync = Filter.extend("FilterAsync", {
    fields: ["name", "args", "symbol"]
  });
  var KeywordArgs = Dict.extend("KeywordArgs");
  var Block = Node.extend("Block", {
    fields: ["name", "body"]
  });
  var Super = Node.extend("Super", {
    fields: ["blockName", "symbol"]
  });
  var TemplateRef = Node.extend("TemplateRef", {
    fields: ["template"]
  });
  var Extends = TemplateRef.extend("Extends");
  var Include = Node.extend("Include", {
    fields: ["template", "ignoreMissing"]
  });
  var Set2 = Node.extend("Set", {
    fields: ["targets", "value"]
  });
  var Switch = Node.extend("Switch", {
    fields: ["expr", "cases", "default"]
  });
  var Case = Node.extend("Case", {
    fields: ["cond", "body"]
  });
  var Output = NodeList.extend("Output");
  var Capture = Node.extend("Capture", {
    fields: ["body"]
  });
  var TemplateData = Literal.extend("TemplateData");
  var UnaryOp = Node.extend("UnaryOp", {
    fields: ["target"]
  });
  var BinOp = Node.extend("BinOp", {
    fields: ["left", "right"]
  });
  var In = BinOp.extend("In");
  var Is = BinOp.extend("Is");
  var Or = BinOp.extend("Or");
  var And = BinOp.extend("And");
  var Not = UnaryOp.extend("Not");
  var Add = BinOp.extend("Add");
  var Concat = BinOp.extend("Concat");
  var Sub = BinOp.extend("Sub");
  var Mul = BinOp.extend("Mul");
  var Div = BinOp.extend("Div");
  var FloorDiv = BinOp.extend("FloorDiv");
  var Mod = BinOp.extend("Mod");
  var Pow = BinOp.extend("Pow");
  var Neg = UnaryOp.extend("Neg");
  var Pos = UnaryOp.extend("Pos");
  var Compare = Node.extend("Compare", {
    fields: ["expr", "ops"]
  });
  var CompareOperand = Node.extend("CompareOperand", {
    fields: ["expr", "type"]
  });
  var CallExtension = Node.extend("CallExtension", {
    init: function init(ext, prop, args, contentArgs) {
      this.parent();
      this.extName = ext.__name || ext;
      this.prop = prop;
      this.args = args || new NodeList;
      this.contentArgs = contentArgs || [];
      this.autoescape = ext.autoescape;
    },
    fields: ["extName", "prop", "args", "contentArgs"]
  });
  var CallExtensionAsync = CallExtension.extend("CallExtensionAsync");
  function print(str, indent, inline) {
    var lines = str.split(`
`);
    lines.forEach(function(line, i) {
      if (line && (inline && i > 0 || !inline)) {
        process.stdout.write(" ".repeat(indent));
      }
      var nl = i === lines.length - 1 ? "" : `
`;
      process.stdout.write("" + line + nl);
    });
  }
  function printNodes(node, indent) {
    indent = indent || 0;
    print(node.typename + ": ", indent);
    if (node instanceof NodeList) {
      print(`
`);
      node.children.forEach(function(n) {
        printNodes(n, indent + 2);
      });
    } else if (node instanceof CallExtension) {
      print(node.extName + "." + node.prop + `
`);
      if (node.args) {
        printNodes(node.args, indent + 2);
      }
      if (node.contentArgs) {
        node.contentArgs.forEach(function(n) {
          printNodes(n, indent + 2);
        });
      }
    } else {
      var nodes = [];
      var props = null;
      node.iterFields(function(val, fieldName) {
        if (val instanceof Node) {
          nodes.push([fieldName, val]);
        } else {
          props = props || {};
          props[fieldName] = val;
        }
      });
      if (props) {
        print(JSON.stringify(props, null, 2) + `
`, null, true);
      } else {
        print(`
`);
      }
      nodes.forEach(function(_ref) {
        var fieldName = _ref[0], n = _ref[1];
        print("[" + fieldName + "] =>", indent + 2);
        printNodes(n, indent + 4);
      });
    }
  }
  module.exports = {
    Node,
    Root,
    NodeList,
    Value,
    Literal,
    Symbol: _Symbol,
    Group,
    Array: ArrayNode,
    Pair,
    Dict,
    Output,
    Capture,
    TemplateData,
    If,
    IfAsync,
    InlineIf,
    For,
    AsyncEach,
    AsyncAll,
    Macro,
    Caller,
    Import,
    FromImport,
    FunCall,
    Filter,
    FilterAsync,
    KeywordArgs,
    Block,
    Super,
    Extends,
    Include,
    Set: Set2,
    Switch,
    Case,
    LookupVal,
    BinOp,
    In,
    Is,
    Or,
    And,
    Not,
    Add,
    Concat,
    Sub,
    Mul,
    Div,
    FloorDiv,
    Mod,
    Pow,
    Neg,
    Pos,
    Compare,
    CompareOperand,
    CallExtension,
    CallExtensionAsync,
    printNodes
  };
});

// node_modules/nunjucks/src/parser.js
var require_parser = __commonJS((exports, module) => {
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o2, p2) {
      o2.__proto__ = p2;
      return o2;
    };
    return _setPrototypeOf(o, p);
  }
  var lexer = require_lexer();
  var nodes = require_nodes();
  var Obj = require_object().Obj;
  var lib = require_lib();
  var Parser = /* @__PURE__ */ function(_Obj) {
    _inheritsLoose(Parser2, _Obj);
    function Parser2() {
      return _Obj.apply(this, arguments) || this;
    }
    var _proto = Parser2.prototype;
    _proto.init = function init(tokens) {
      this.tokens = tokens;
      this.peeked = null;
      this.breakOnBlocks = null;
      this.dropLeadingWhitespace = false;
      this.extensions = [];
    };
    _proto.nextToken = function nextToken(withWhitespace) {
      var tok;
      if (this.peeked) {
        if (!withWhitespace && this.peeked.type === lexer.TOKEN_WHITESPACE) {
          this.peeked = null;
        } else {
          tok = this.peeked;
          this.peeked = null;
          return tok;
        }
      }
      tok = this.tokens.nextToken();
      if (!withWhitespace) {
        while (tok && tok.type === lexer.TOKEN_WHITESPACE) {
          tok = this.tokens.nextToken();
        }
      }
      return tok;
    };
    _proto.peekToken = function peekToken() {
      this.peeked = this.peeked || this.nextToken();
      return this.peeked;
    };
    _proto.pushToken = function pushToken(tok) {
      if (this.peeked) {
        throw new Error("pushToken: can only push one token on between reads");
      }
      this.peeked = tok;
    };
    _proto.error = function error(msg, lineno, colno) {
      if (lineno === undefined || colno === undefined) {
        var tok = this.peekToken() || {};
        lineno = tok.lineno;
        colno = tok.colno;
      }
      if (lineno !== undefined) {
        lineno += 1;
      }
      if (colno !== undefined) {
        colno += 1;
      }
      return new lib.TemplateError(msg, lineno, colno);
    };
    _proto.fail = function fail(msg, lineno, colno) {
      throw this.error(msg, lineno, colno);
    };
    _proto.skip = function skip(type) {
      var tok = this.nextToken();
      if (!tok || tok.type !== type) {
        this.pushToken(tok);
        return false;
      }
      return true;
    };
    _proto.expect = function expect(type) {
      var tok = this.nextToken();
      if (tok.type !== type) {
        this.fail("expected " + type + ", got " + tok.type, tok.lineno, tok.colno);
      }
      return tok;
    };
    _proto.skipValue = function skipValue(type, val) {
      var tok = this.nextToken();
      if (!tok || tok.type !== type || tok.value !== val) {
        this.pushToken(tok);
        return false;
      }
      return true;
    };
    _proto.skipSymbol = function skipSymbol(val) {
      return this.skipValue(lexer.TOKEN_SYMBOL, val);
    };
    _proto.advanceAfterBlockEnd = function advanceAfterBlockEnd(name) {
      var tok;
      if (!name) {
        tok = this.peekToken();
        if (!tok) {
          this.fail("unexpected end of file");
        }
        if (tok.type !== lexer.TOKEN_SYMBOL) {
          this.fail("advanceAfterBlockEnd: expected symbol token or " + "explicit name to be passed");
        }
        name = this.nextToken().value;
      }
      tok = this.nextToken();
      if (tok && tok.type === lexer.TOKEN_BLOCK_END) {
        if (tok.value.charAt(0) === "-") {
          this.dropLeadingWhitespace = true;
        }
      } else {
        this.fail("expected block end in " + name + " statement");
      }
      return tok;
    };
    _proto.advanceAfterVariableEnd = function advanceAfterVariableEnd() {
      var tok = this.nextToken();
      if (tok && tok.type === lexer.TOKEN_VARIABLE_END) {
        this.dropLeadingWhitespace = tok.value.charAt(tok.value.length - this.tokens.tags.VARIABLE_END.length - 1) === "-";
      } else {
        this.pushToken(tok);
        this.fail("expected variable end");
      }
    };
    _proto.parseFor = function parseFor() {
      var forTok = this.peekToken();
      var node;
      var endBlock;
      if (this.skipSymbol("for")) {
        node = new nodes.For(forTok.lineno, forTok.colno);
        endBlock = "endfor";
      } else if (this.skipSymbol("asyncEach")) {
        node = new nodes.AsyncEach(forTok.lineno, forTok.colno);
        endBlock = "endeach";
      } else if (this.skipSymbol("asyncAll")) {
        node = new nodes.AsyncAll(forTok.lineno, forTok.colno);
        endBlock = "endall";
      } else {
        this.fail("parseFor: expected for{Async}", forTok.lineno, forTok.colno);
      }
      node.name = this.parsePrimary();
      if (!(node.name instanceof nodes.Symbol)) {
        this.fail("parseFor: variable name expected for loop");
      }
      var type = this.peekToken().type;
      if (type === lexer.TOKEN_COMMA) {
        var key = node.name;
        node.name = new nodes.Array(key.lineno, key.colno);
        node.name.addChild(key);
        while (this.skip(lexer.TOKEN_COMMA)) {
          var prim = this.parsePrimary();
          node.name.addChild(prim);
        }
      }
      if (!this.skipSymbol("in")) {
        this.fail('parseFor: expected "in" keyword for loop', forTok.lineno, forTok.colno);
      }
      node.arr = this.parseExpression();
      this.advanceAfterBlockEnd(forTok.value);
      node.body = this.parseUntilBlocks(endBlock, "else");
      if (this.skipSymbol("else")) {
        this.advanceAfterBlockEnd("else");
        node.else_ = this.parseUntilBlocks(endBlock);
      }
      this.advanceAfterBlockEnd();
      return node;
    };
    _proto.parseMacro = function parseMacro() {
      var macroTok = this.peekToken();
      if (!this.skipSymbol("macro")) {
        this.fail("expected macro");
      }
      var name = this.parsePrimary(true);
      var args = this.parseSignature();
      var node = new nodes.Macro(macroTok.lineno, macroTok.colno, name, args);
      this.advanceAfterBlockEnd(macroTok.value);
      node.body = this.parseUntilBlocks("endmacro");
      this.advanceAfterBlockEnd();
      return node;
    };
    _proto.parseCall = function parseCall() {
      var callTok = this.peekToken();
      if (!this.skipSymbol("call")) {
        this.fail("expected call");
      }
      var callerArgs = this.parseSignature(true) || new nodes.NodeList;
      var macroCall = this.parsePrimary();
      this.advanceAfterBlockEnd(callTok.value);
      var body = this.parseUntilBlocks("endcall");
      this.advanceAfterBlockEnd();
      var callerName = new nodes.Symbol(callTok.lineno, callTok.colno, "caller");
      var callerNode = new nodes.Caller(callTok.lineno, callTok.colno, callerName, callerArgs, body);
      var args = macroCall.args.children;
      if (!(args[args.length - 1] instanceof nodes.KeywordArgs)) {
        args.push(new nodes.KeywordArgs);
      }
      var kwargs = args[args.length - 1];
      kwargs.addChild(new nodes.Pair(callTok.lineno, callTok.colno, callerName, callerNode));
      return new nodes.Output(callTok.lineno, callTok.colno, [macroCall]);
    };
    _proto.parseWithContext = function parseWithContext() {
      var tok = this.peekToken();
      var withContext = null;
      if (this.skipSymbol("with")) {
        withContext = true;
      } else if (this.skipSymbol("without")) {
        withContext = false;
      }
      if (withContext !== null) {
        if (!this.skipSymbol("context")) {
          this.fail("parseFrom: expected context after with/without", tok.lineno, tok.colno);
        }
      }
      return withContext;
    };
    _proto.parseImport = function parseImport() {
      var importTok = this.peekToken();
      if (!this.skipSymbol("import")) {
        this.fail("parseImport: expected import", importTok.lineno, importTok.colno);
      }
      var template = this.parseExpression();
      if (!this.skipSymbol("as")) {
        this.fail('parseImport: expected "as" keyword', importTok.lineno, importTok.colno);
      }
      var target = this.parseExpression();
      var withContext = this.parseWithContext();
      var node = new nodes.Import(importTok.lineno, importTok.colno, template, target, withContext);
      this.advanceAfterBlockEnd(importTok.value);
      return node;
    };
    _proto.parseFrom = function parseFrom() {
      var fromTok = this.peekToken();
      if (!this.skipSymbol("from")) {
        this.fail("parseFrom: expected from");
      }
      var template = this.parseExpression();
      if (!this.skipSymbol("import")) {
        this.fail("parseFrom: expected import", fromTok.lineno, fromTok.colno);
      }
      var names = new nodes.NodeList;
      var withContext;
      while (true) {
        var nextTok = this.peekToken();
        if (nextTok.type === lexer.TOKEN_BLOCK_END) {
          if (!names.children.length) {
            this.fail("parseFrom: Expected at least one import name", fromTok.lineno, fromTok.colno);
          }
          if (nextTok.value.charAt(0) === "-") {
            this.dropLeadingWhitespace = true;
          }
          this.nextToken();
          break;
        }
        if (names.children.length > 0 && !this.skip(lexer.TOKEN_COMMA)) {
          this.fail("parseFrom: expected comma", fromTok.lineno, fromTok.colno);
        }
        var name = this.parsePrimary();
        if (name.value.charAt(0) === "_") {
          this.fail("parseFrom: names starting with an underscore cannot be imported", name.lineno, name.colno);
        }
        if (this.skipSymbol("as")) {
          var alias = this.parsePrimary();
          names.addChild(new nodes.Pair(name.lineno, name.colno, name, alias));
        } else {
          names.addChild(name);
        }
        withContext = this.parseWithContext();
      }
      return new nodes.FromImport(fromTok.lineno, fromTok.colno, template, names, withContext);
    };
    _proto.parseBlock = function parseBlock() {
      var tag = this.peekToken();
      if (!this.skipSymbol("block")) {
        this.fail("parseBlock: expected block", tag.lineno, tag.colno);
      }
      var node = new nodes.Block(tag.lineno, tag.colno);
      node.name = this.parsePrimary();
      if (!(node.name instanceof nodes.Symbol)) {
        this.fail("parseBlock: variable name expected", tag.lineno, tag.colno);
      }
      this.advanceAfterBlockEnd(tag.value);
      node.body = this.parseUntilBlocks("endblock");
      this.skipSymbol("endblock");
      this.skipSymbol(node.name.value);
      var tok = this.peekToken();
      if (!tok) {
        this.fail("parseBlock: expected endblock, got end of file");
      }
      this.advanceAfterBlockEnd(tok.value);
      return node;
    };
    _proto.parseExtends = function parseExtends() {
      var tagName = "extends";
      var tag = this.peekToken();
      if (!this.skipSymbol(tagName)) {
        this.fail("parseTemplateRef: expected " + tagName);
      }
      var node = new nodes.Extends(tag.lineno, tag.colno);
      node.template = this.parseExpression();
      this.advanceAfterBlockEnd(tag.value);
      return node;
    };
    _proto.parseInclude = function parseInclude() {
      var tagName = "include";
      var tag = this.peekToken();
      if (!this.skipSymbol(tagName)) {
        this.fail("parseInclude: expected " + tagName);
      }
      var node = new nodes.Include(tag.lineno, tag.colno);
      node.template = this.parseExpression();
      if (this.skipSymbol("ignore") && this.skipSymbol("missing")) {
        node.ignoreMissing = true;
      }
      this.advanceAfterBlockEnd(tag.value);
      return node;
    };
    _proto.parseIf = function parseIf() {
      var tag = this.peekToken();
      var node;
      if (this.skipSymbol("if") || this.skipSymbol("elif") || this.skipSymbol("elseif")) {
        node = new nodes.If(tag.lineno, tag.colno);
      } else if (this.skipSymbol("ifAsync")) {
        node = new nodes.IfAsync(tag.lineno, tag.colno);
      } else {
        this.fail("parseIf: expected if, elif, or elseif", tag.lineno, tag.colno);
      }
      node.cond = this.parseExpression();
      this.advanceAfterBlockEnd(tag.value);
      node.body = this.parseUntilBlocks("elif", "elseif", "else", "endif");
      var tok = this.peekToken();
      switch (tok && tok.value) {
        case "elseif":
        case "elif":
          node.else_ = this.parseIf();
          break;
        case "else":
          this.advanceAfterBlockEnd();
          node.else_ = this.parseUntilBlocks("endif");
          this.advanceAfterBlockEnd();
          break;
        case "endif":
          node.else_ = null;
          this.advanceAfterBlockEnd();
          break;
        default:
          this.fail("parseIf: expected elif, else, or endif, got end of file");
      }
      return node;
    };
    _proto.parseSet = function parseSet() {
      var tag = this.peekToken();
      if (!this.skipSymbol("set")) {
        this.fail("parseSet: expected set", tag.lineno, tag.colno);
      }
      var node = new nodes.Set(tag.lineno, tag.colno, []);
      var target;
      while (target = this.parsePrimary()) {
        node.targets.push(target);
        if (!this.skip(lexer.TOKEN_COMMA)) {
          break;
        }
      }
      if (!this.skipValue(lexer.TOKEN_OPERATOR, "=")) {
        if (!this.skip(lexer.TOKEN_BLOCK_END)) {
          this.fail("parseSet: expected = or block end in set tag", tag.lineno, tag.colno);
        } else {
          node.body = new nodes.Capture(tag.lineno, tag.colno, this.parseUntilBlocks("endset"));
          node.value = null;
          this.advanceAfterBlockEnd();
        }
      } else {
        node.value = this.parseExpression();
        this.advanceAfterBlockEnd(tag.value);
      }
      return node;
    };
    _proto.parseSwitch = function parseSwitch() {
      var switchStart = "switch";
      var switchEnd = "endswitch";
      var caseStart = "case";
      var caseDefault = "default";
      var tag = this.peekToken();
      if (!this.skipSymbol(switchStart) && !this.skipSymbol(caseStart) && !this.skipSymbol(caseDefault)) {
        this.fail('parseSwitch: expected "switch," "case" or "default"', tag.lineno, tag.colno);
      }
      var expr = this.parseExpression();
      this.advanceAfterBlockEnd(switchStart);
      this.parseUntilBlocks(caseStart, caseDefault, switchEnd);
      var tok = this.peekToken();
      var cases = [];
      var defaultCase;
      do {
        this.skipSymbol(caseStart);
        var cond = this.parseExpression();
        this.advanceAfterBlockEnd(switchStart);
        var body = this.parseUntilBlocks(caseStart, caseDefault, switchEnd);
        cases.push(new nodes.Case(tok.line, tok.col, cond, body));
        tok = this.peekToken();
      } while (tok && tok.value === caseStart);
      switch (tok.value) {
        case caseDefault:
          this.advanceAfterBlockEnd();
          defaultCase = this.parseUntilBlocks(switchEnd);
          this.advanceAfterBlockEnd();
          break;
        case switchEnd:
          this.advanceAfterBlockEnd();
          break;
        default:
          this.fail('parseSwitch: expected "case," "default" or "endswitch," got EOF.');
      }
      return new nodes.Switch(tag.lineno, tag.colno, expr, cases, defaultCase);
    };
    _proto.parseStatement = function parseStatement() {
      var tok = this.peekToken();
      var node;
      if (tok.type !== lexer.TOKEN_SYMBOL) {
        this.fail("tag name expected", tok.lineno, tok.colno);
      }
      if (this.breakOnBlocks && lib.indexOf(this.breakOnBlocks, tok.value) !== -1) {
        return null;
      }
      switch (tok.value) {
        case "raw":
          return this.parseRaw();
        case "verbatim":
          return this.parseRaw("verbatim");
        case "if":
        case "ifAsync":
          return this.parseIf();
        case "for":
        case "asyncEach":
        case "asyncAll":
          return this.parseFor();
        case "block":
          return this.parseBlock();
        case "extends":
          return this.parseExtends();
        case "include":
          return this.parseInclude();
        case "set":
          return this.parseSet();
        case "macro":
          return this.parseMacro();
        case "call":
          return this.parseCall();
        case "import":
          return this.parseImport();
        case "from":
          return this.parseFrom();
        case "filter":
          return this.parseFilterStatement();
        case "switch":
          return this.parseSwitch();
        default:
          if (this.extensions.length) {
            for (var i = 0;i < this.extensions.length; i++) {
              var ext = this.extensions[i];
              if (lib.indexOf(ext.tags || [], tok.value) !== -1) {
                return ext.parse(this, nodes, lexer);
              }
            }
          }
          this.fail("unknown block tag: " + tok.value, tok.lineno, tok.colno);
      }
      return node;
    };
    _proto.parseRaw = function parseRaw(tagName) {
      tagName = tagName || "raw";
      var endTagName = "end" + tagName;
      var rawBlockRegex = new RegExp("([\\s\\S]*?){%\\s*(" + tagName + "|" + endTagName + ")\\s*(?=%})%}");
      var rawLevel = 1;
      var str = "";
      var matches = null;
      var begun = this.advanceAfterBlockEnd();
      while ((matches = this.tokens._extractRegex(rawBlockRegex)) && rawLevel > 0) {
        var all = matches[0];
        var pre = matches[1];
        var blockName = matches[2];
        if (blockName === tagName) {
          rawLevel += 1;
        } else if (blockName === endTagName) {
          rawLevel -= 1;
        }
        if (rawLevel === 0) {
          str += pre;
          this.tokens.backN(all.length - pre.length);
        } else {
          str += all;
        }
      }
      return new nodes.Output(begun.lineno, begun.colno, [new nodes.TemplateData(begun.lineno, begun.colno, str)]);
    };
    _proto.parsePostfix = function parsePostfix(node) {
      var lookup;
      var tok = this.peekToken();
      while (tok) {
        if (tok.type === lexer.TOKEN_LEFT_PAREN) {
          node = new nodes.FunCall(tok.lineno, tok.colno, node, this.parseSignature());
        } else if (tok.type === lexer.TOKEN_LEFT_BRACKET) {
          lookup = this.parseAggregate();
          if (lookup.children.length > 1) {
            this.fail("invalid index");
          }
          node = new nodes.LookupVal(tok.lineno, tok.colno, node, lookup.children[0]);
        } else if (tok.type === lexer.TOKEN_OPERATOR && tok.value === ".") {
          this.nextToken();
          var val = this.nextToken();
          if (val.type !== lexer.TOKEN_SYMBOL) {
            this.fail("expected name as lookup value, got " + val.value, val.lineno, val.colno);
          }
          lookup = new nodes.Literal(val.lineno, val.colno, val.value);
          node = new nodes.LookupVal(tok.lineno, tok.colno, node, lookup);
        } else {
          break;
        }
        tok = this.peekToken();
      }
      return node;
    };
    _proto.parseExpression = function parseExpression() {
      var node = this.parseInlineIf();
      return node;
    };
    _proto.parseInlineIf = function parseInlineIf() {
      var node = this.parseOr();
      if (this.skipSymbol("if")) {
        var condNode = this.parseOr();
        var bodyNode = node;
        node = new nodes.InlineIf(node.lineno, node.colno);
        node.body = bodyNode;
        node.cond = condNode;
        if (this.skipSymbol("else")) {
          node.else_ = this.parseOr();
        } else {
          node.else_ = null;
        }
      }
      return node;
    };
    _proto.parseOr = function parseOr() {
      var node = this.parseAnd();
      while (this.skipSymbol("or")) {
        var node2 = this.parseAnd();
        node = new nodes.Or(node.lineno, node.colno, node, node2);
      }
      return node;
    };
    _proto.parseAnd = function parseAnd() {
      var node = this.parseNot();
      while (this.skipSymbol("and")) {
        var node2 = this.parseNot();
        node = new nodes.And(node.lineno, node.colno, node, node2);
      }
      return node;
    };
    _proto.parseNot = function parseNot() {
      var tok = this.peekToken();
      if (this.skipSymbol("not")) {
        return new nodes.Not(tok.lineno, tok.colno, this.parseNot());
      }
      return this.parseIn();
    };
    _proto.parseIn = function parseIn() {
      var node = this.parseIs();
      while (true) {
        var tok = this.nextToken();
        if (!tok) {
          break;
        }
        var invert = tok.type === lexer.TOKEN_SYMBOL && tok.value === "not";
        if (!invert) {
          this.pushToken(tok);
        }
        if (this.skipSymbol("in")) {
          var node2 = this.parseIs();
          node = new nodes.In(node.lineno, node.colno, node, node2);
          if (invert) {
            node = new nodes.Not(node.lineno, node.colno, node);
          }
        } else {
          if (invert) {
            this.pushToken(tok);
          }
          break;
        }
      }
      return node;
    };
    _proto.parseIs = function parseIs() {
      var node = this.parseCompare();
      if (this.skipSymbol("is")) {
        var not = this.skipSymbol("not");
        var node2 = this.parseCompare();
        node = new nodes.Is(node.lineno, node.colno, node, node2);
        if (not) {
          node = new nodes.Not(node.lineno, node.colno, node);
        }
      }
      return node;
    };
    _proto.parseCompare = function parseCompare() {
      var compareOps = ["==", "===", "!=", "!==", "<", ">", "<=", ">="];
      var expr = this.parseConcat();
      var ops = [];
      while (true) {
        var tok = this.nextToken();
        if (!tok) {
          break;
        } else if (compareOps.indexOf(tok.value) !== -1) {
          ops.push(new nodes.CompareOperand(tok.lineno, tok.colno, this.parseConcat(), tok.value));
        } else {
          this.pushToken(tok);
          break;
        }
      }
      if (ops.length) {
        return new nodes.Compare(ops[0].lineno, ops[0].colno, expr, ops);
      } else {
        return expr;
      }
    };
    _proto.parseConcat = function parseConcat() {
      var node = this.parseAdd();
      while (this.skipValue(lexer.TOKEN_TILDE, "~")) {
        var node2 = this.parseAdd();
        node = new nodes.Concat(node.lineno, node.colno, node, node2);
      }
      return node;
    };
    _proto.parseAdd = function parseAdd() {
      var node = this.parseSub();
      while (this.skipValue(lexer.TOKEN_OPERATOR, "+")) {
        var node2 = this.parseSub();
        node = new nodes.Add(node.lineno, node.colno, node, node2);
      }
      return node;
    };
    _proto.parseSub = function parseSub() {
      var node = this.parseMul();
      while (this.skipValue(lexer.TOKEN_OPERATOR, "-")) {
        var node2 = this.parseMul();
        node = new nodes.Sub(node.lineno, node.colno, node, node2);
      }
      return node;
    };
    _proto.parseMul = function parseMul() {
      var node = this.parseDiv();
      while (this.skipValue(lexer.TOKEN_OPERATOR, "*")) {
        var node2 = this.parseDiv();
        node = new nodes.Mul(node.lineno, node.colno, node, node2);
      }
      return node;
    };
    _proto.parseDiv = function parseDiv() {
      var node = this.parseFloorDiv();
      while (this.skipValue(lexer.TOKEN_OPERATOR, "/")) {
        var node2 = this.parseFloorDiv();
        node = new nodes.Div(node.lineno, node.colno, node, node2);
      }
      return node;
    };
    _proto.parseFloorDiv = function parseFloorDiv() {
      var node = this.parseMod();
      while (this.skipValue(lexer.TOKEN_OPERATOR, "//")) {
        var node2 = this.parseMod();
        node = new nodes.FloorDiv(node.lineno, node.colno, node, node2);
      }
      return node;
    };
    _proto.parseMod = function parseMod() {
      var node = this.parsePow();
      while (this.skipValue(lexer.TOKEN_OPERATOR, "%")) {
        var node2 = this.parsePow();
        node = new nodes.Mod(node.lineno, node.colno, node, node2);
      }
      return node;
    };
    _proto.parsePow = function parsePow() {
      var node = this.parseUnary();
      while (this.skipValue(lexer.TOKEN_OPERATOR, "**")) {
        var node2 = this.parseUnary();
        node = new nodes.Pow(node.lineno, node.colno, node, node2);
      }
      return node;
    };
    _proto.parseUnary = function parseUnary(noFilters) {
      var tok = this.peekToken();
      var node;
      if (this.skipValue(lexer.TOKEN_OPERATOR, "-")) {
        node = new nodes.Neg(tok.lineno, tok.colno, this.parseUnary(true));
      } else if (this.skipValue(lexer.TOKEN_OPERATOR, "+")) {
        node = new nodes.Pos(tok.lineno, tok.colno, this.parseUnary(true));
      } else {
        node = this.parsePrimary();
      }
      if (!noFilters) {
        node = this.parseFilter(node);
      }
      return node;
    };
    _proto.parsePrimary = function parsePrimary(noPostfix) {
      var tok = this.nextToken();
      var val;
      var node = null;
      if (!tok) {
        this.fail("expected expression, got end of file");
      } else if (tok.type === lexer.TOKEN_STRING) {
        val = tok.value;
      } else if (tok.type === lexer.TOKEN_INT) {
        val = parseInt(tok.value, 10);
      } else if (tok.type === lexer.TOKEN_FLOAT) {
        val = parseFloat(tok.value);
      } else if (tok.type === lexer.TOKEN_BOOLEAN) {
        if (tok.value === "true") {
          val = true;
        } else if (tok.value === "false") {
          val = false;
        } else {
          this.fail("invalid boolean: " + tok.value, tok.lineno, tok.colno);
        }
      } else if (tok.type === lexer.TOKEN_NONE) {
        val = null;
      } else if (tok.type === lexer.TOKEN_REGEX) {
        val = new RegExp(tok.value.body, tok.value.flags);
      }
      if (val !== undefined) {
        node = new nodes.Literal(tok.lineno, tok.colno, val);
      } else if (tok.type === lexer.TOKEN_SYMBOL) {
        node = new nodes.Symbol(tok.lineno, tok.colno, tok.value);
      } else {
        this.pushToken(tok);
        node = this.parseAggregate();
      }
      if (!noPostfix) {
        node = this.parsePostfix(node);
      }
      if (node) {
        return node;
      } else {
        throw this.error("unexpected token: " + tok.value, tok.lineno, tok.colno);
      }
    };
    _proto.parseFilterName = function parseFilterName() {
      var tok = this.expect(lexer.TOKEN_SYMBOL);
      var name = tok.value;
      while (this.skipValue(lexer.TOKEN_OPERATOR, ".")) {
        name += "." + this.expect(lexer.TOKEN_SYMBOL).value;
      }
      return new nodes.Symbol(tok.lineno, tok.colno, name);
    };
    _proto.parseFilterArgs = function parseFilterArgs(node) {
      if (this.peekToken().type === lexer.TOKEN_LEFT_PAREN) {
        var call = this.parsePostfix(node);
        return call.args.children;
      }
      return [];
    };
    _proto.parseFilter = function parseFilter(node) {
      while (this.skip(lexer.TOKEN_PIPE)) {
        var name = this.parseFilterName();
        node = new nodes.Filter(name.lineno, name.colno, name, new nodes.NodeList(name.lineno, name.colno, [node].concat(this.parseFilterArgs(node))));
      }
      return node;
    };
    _proto.parseFilterStatement = function parseFilterStatement() {
      var filterTok = this.peekToken();
      if (!this.skipSymbol("filter")) {
        this.fail("parseFilterStatement: expected filter");
      }
      var name = this.parseFilterName();
      var args = this.parseFilterArgs(name);
      this.advanceAfterBlockEnd(filterTok.value);
      var body = new nodes.Capture(name.lineno, name.colno, this.parseUntilBlocks("endfilter"));
      this.advanceAfterBlockEnd();
      var node = new nodes.Filter(name.lineno, name.colno, name, new nodes.NodeList(name.lineno, name.colno, [body].concat(args)));
      return new nodes.Output(name.lineno, name.colno, [node]);
    };
    _proto.parseAggregate = function parseAggregate() {
      var tok = this.nextToken();
      var node;
      switch (tok.type) {
        case lexer.TOKEN_LEFT_PAREN:
          node = new nodes.Group(tok.lineno, tok.colno);
          break;
        case lexer.TOKEN_LEFT_BRACKET:
          node = new nodes.Array(tok.lineno, tok.colno);
          break;
        case lexer.TOKEN_LEFT_CURLY:
          node = new nodes.Dict(tok.lineno, tok.colno);
          break;
        default:
          return null;
      }
      while (true) {
        var type = this.peekToken().type;
        if (type === lexer.TOKEN_RIGHT_PAREN || type === lexer.TOKEN_RIGHT_BRACKET || type === lexer.TOKEN_RIGHT_CURLY) {
          this.nextToken();
          break;
        }
        if (node.children.length > 0) {
          if (!this.skip(lexer.TOKEN_COMMA)) {
            this.fail("parseAggregate: expected comma after expression", tok.lineno, tok.colno);
          }
        }
        if (node instanceof nodes.Dict) {
          var key = this.parsePrimary();
          if (!this.skip(lexer.TOKEN_COLON)) {
            this.fail("parseAggregate: expected colon after dict key", tok.lineno, tok.colno);
          }
          var value = this.parseExpression();
          node.addChild(new nodes.Pair(key.lineno, key.colno, key, value));
        } else {
          var expr = this.parseExpression();
          node.addChild(expr);
        }
      }
      return node;
    };
    _proto.parseSignature = function parseSignature(tolerant, noParens) {
      var tok = this.peekToken();
      if (!noParens && tok.type !== lexer.TOKEN_LEFT_PAREN) {
        if (tolerant) {
          return null;
        } else {
          this.fail("expected arguments", tok.lineno, tok.colno);
        }
      }
      if (tok.type === lexer.TOKEN_LEFT_PAREN) {
        tok = this.nextToken();
      }
      var args = new nodes.NodeList(tok.lineno, tok.colno);
      var kwargs = new nodes.KeywordArgs(tok.lineno, tok.colno);
      var checkComma = false;
      while (true) {
        tok = this.peekToken();
        if (!noParens && tok.type === lexer.TOKEN_RIGHT_PAREN) {
          this.nextToken();
          break;
        } else if (noParens && tok.type === lexer.TOKEN_BLOCK_END) {
          break;
        }
        if (checkComma && !this.skip(lexer.TOKEN_COMMA)) {
          this.fail("parseSignature: expected comma after expression", tok.lineno, tok.colno);
        } else {
          var arg = this.parseExpression();
          if (this.skipValue(lexer.TOKEN_OPERATOR, "=")) {
            kwargs.addChild(new nodes.Pair(arg.lineno, arg.colno, arg, this.parseExpression()));
          } else {
            args.addChild(arg);
          }
        }
        checkComma = true;
      }
      if (kwargs.children.length) {
        args.addChild(kwargs);
      }
      return args;
    };
    _proto.parseUntilBlocks = function parseUntilBlocks() {
      var prev = this.breakOnBlocks;
      for (var _len = arguments.length, blockNames = new Array(_len), _key = 0;_key < _len; _key++) {
        blockNames[_key] = arguments[_key];
      }
      this.breakOnBlocks = blockNames;
      var ret = this.parse();
      this.breakOnBlocks = prev;
      return ret;
    };
    _proto.parseNodes = function parseNodes() {
      var tok;
      var buf = [];
      while (tok = this.nextToken()) {
        if (tok.type === lexer.TOKEN_DATA) {
          var data = tok.value;
          var nextToken = this.peekToken();
          var nextVal = nextToken && nextToken.value;
          if (this.dropLeadingWhitespace) {
            data = data.replace(/^\s*/, "");
            this.dropLeadingWhitespace = false;
          }
          if (nextToken && (nextToken.type === lexer.TOKEN_BLOCK_START && nextVal.charAt(nextVal.length - 1) === "-" || nextToken.type === lexer.TOKEN_VARIABLE_START && nextVal.charAt(this.tokens.tags.VARIABLE_START.length) === "-" || nextToken.type === lexer.TOKEN_COMMENT && nextVal.charAt(this.tokens.tags.COMMENT_START.length) === "-")) {
            data = data.replace(/\s*$/, "");
          }
          buf.push(new nodes.Output(tok.lineno, tok.colno, [new nodes.TemplateData(tok.lineno, tok.colno, data)]));
        } else if (tok.type === lexer.TOKEN_BLOCK_START) {
          this.dropLeadingWhitespace = false;
          var n = this.parseStatement();
          if (!n) {
            break;
          }
          buf.push(n);
        } else if (tok.type === lexer.TOKEN_VARIABLE_START) {
          var e = this.parseExpression();
          this.dropLeadingWhitespace = false;
          this.advanceAfterVariableEnd();
          buf.push(new nodes.Output(tok.lineno, tok.colno, [e]));
        } else if (tok.type === lexer.TOKEN_COMMENT) {
          this.dropLeadingWhitespace = tok.value.charAt(tok.value.length - this.tokens.tags.COMMENT_END.length - 1) === "-";
        } else {
          this.fail("Unexpected token at top-level: " + tok.type, tok.lineno, tok.colno);
        }
      }
      return buf;
    };
    _proto.parse = function parse() {
      return new nodes.NodeList(0, 0, this.parseNodes());
    };
    _proto.parseAsRoot = function parseAsRoot() {
      return new nodes.Root(0, 0, this.parseNodes());
    };
    return Parser2;
  }(Obj);
  module.exports = {
    parse: function parse(src, extensions, opts) {
      var p = new Parser(lexer.lex(src, opts));
      if (extensions !== undefined) {
        p.extensions = extensions;
      }
      return p.parseAsRoot();
    },
    Parser
  };
});

// node_modules/nunjucks/src/transformer.js
var require_transformer = __commonJS((exports, module) => {
  var nodes = require_nodes();
  var lib = require_lib();
  var sym = 0;
  function gensym() {
    return "hole_" + sym++;
  }
  function mapCOW(arr, func) {
    var res = null;
    for (var i = 0;i < arr.length; i++) {
      var item = func(arr[i]);
      if (item !== arr[i]) {
        if (!res) {
          res = arr.slice();
        }
        res[i] = item;
      }
    }
    return res || arr;
  }
  function walk(ast, func, depthFirst) {
    if (!(ast instanceof nodes.Node)) {
      return ast;
    }
    if (!depthFirst) {
      var astT = func(ast);
      if (astT && astT !== ast) {
        return astT;
      }
    }
    if (ast instanceof nodes.NodeList) {
      var children = mapCOW(ast.children, function(node) {
        return walk(node, func, depthFirst);
      });
      if (children !== ast.children) {
        ast = new nodes[ast.typename](ast.lineno, ast.colno, children);
      }
    } else if (ast instanceof nodes.CallExtension) {
      var args = walk(ast.args, func, depthFirst);
      var contentArgs = mapCOW(ast.contentArgs, function(node) {
        return walk(node, func, depthFirst);
      });
      if (args !== ast.args || contentArgs !== ast.contentArgs) {
        ast = new nodes[ast.typename](ast.extName, ast.prop, args, contentArgs);
      }
    } else {
      var props = ast.fields.map(function(field) {
        return ast[field];
      });
      var propsT = mapCOW(props, function(prop) {
        return walk(prop, func, depthFirst);
      });
      if (propsT !== props) {
        ast = new nodes[ast.typename](ast.lineno, ast.colno);
        propsT.forEach(function(prop, i) {
          ast[ast.fields[i]] = prop;
        });
      }
    }
    return depthFirst ? func(ast) || ast : ast;
  }
  function depthWalk(ast, func) {
    return walk(ast, func, true);
  }
  function _liftFilters(node, asyncFilters, prop) {
    var children = [];
    var walked = depthWalk(prop ? node[prop] : node, function(descNode) {
      var symbol;
      if (descNode instanceof nodes.Block) {
        return descNode;
      } else if (descNode instanceof nodes.Filter && lib.indexOf(asyncFilters, descNode.name.value) !== -1 || descNode instanceof nodes.CallExtensionAsync) {
        symbol = new nodes.Symbol(descNode.lineno, descNode.colno, gensym());
        children.push(new nodes.FilterAsync(descNode.lineno, descNode.colno, descNode.name, descNode.args, symbol));
      }
      return symbol;
    });
    if (prop) {
      node[prop] = walked;
    } else {
      node = walked;
    }
    if (children.length) {
      children.push(node);
      return new nodes.NodeList(node.lineno, node.colno, children);
    } else {
      return node;
    }
  }
  function liftFilters(ast, asyncFilters) {
    return depthWalk(ast, function(node) {
      if (node instanceof nodes.Output) {
        return _liftFilters(node, asyncFilters);
      } else if (node instanceof nodes.Set) {
        return _liftFilters(node, asyncFilters, "value");
      } else if (node instanceof nodes.For) {
        return _liftFilters(node, asyncFilters, "arr");
      } else if (node instanceof nodes.If) {
        return _liftFilters(node, asyncFilters, "cond");
      } else if (node instanceof nodes.CallExtension) {
        return _liftFilters(node, asyncFilters, "args");
      } else {
        return;
      }
    });
  }
  function liftSuper(ast) {
    return walk(ast, function(blockNode) {
      if (!(blockNode instanceof nodes.Block)) {
        return;
      }
      var hasSuper = false;
      var symbol = gensym();
      blockNode.body = walk(blockNode.body, function(node) {
        if (node instanceof nodes.FunCall && node.name.value === "super") {
          hasSuper = true;
          return new nodes.Symbol(node.lineno, node.colno, symbol);
        }
      });
      if (hasSuper) {
        blockNode.body.children.unshift(new nodes.Super(0, 0, blockNode.name, new nodes.Symbol(0, 0, symbol)));
      }
    });
  }
  function convertStatements(ast) {
    return depthWalk(ast, function(node) {
      if (!(node instanceof nodes.If) && !(node instanceof nodes.For)) {
        return;
      }
      var async = false;
      walk(node, function(child) {
        if (child instanceof nodes.FilterAsync || child instanceof nodes.IfAsync || child instanceof nodes.AsyncEach || child instanceof nodes.AsyncAll || child instanceof nodes.CallExtensionAsync) {
          async = true;
          return child;
        }
        return;
      });
      if (async) {
        if (node instanceof nodes.If) {
          return new nodes.IfAsync(node.lineno, node.colno, node.cond, node.body, node.else_);
        } else if (node instanceof nodes.For && !(node instanceof nodes.AsyncAll)) {
          return new nodes.AsyncEach(node.lineno, node.colno, node.arr, node.name, node.body, node.else_);
        }
      }
      return;
    });
  }
  function cps(ast, asyncFilters) {
    return convertStatements(liftSuper(liftFilters(ast, asyncFilters)));
  }
  function transform(ast, asyncFilters) {
    return cps(ast, asyncFilters || []);
  }
  module.exports = {
    transform
  };
});

// node_modules/nunjucks/src/runtime.js
var require_runtime = __commonJS((exports, module) => {
  var lib = require_lib();
  var arrayFrom = Array.from;
  var supportsIterators = typeof Symbol === "function" && Symbol.iterator && typeof arrayFrom === "function";
  var Frame = /* @__PURE__ */ function() {
    function Frame2(parent, isolateWrites) {
      this.variables = Object.create(null);
      this.parent = parent;
      this.topLevel = false;
      this.isolateWrites = isolateWrites;
    }
    var _proto = Frame2.prototype;
    _proto.set = function set(name, val, resolveUp) {
      var parts = name.split(".");
      var obj = this.variables;
      var frame = this;
      if (resolveUp) {
        if (frame = this.resolve(parts[0], true)) {
          frame.set(name, val);
          return;
        }
      }
      for (var i = 0;i < parts.length - 1; i++) {
        var id = parts[i];
        if (!obj[id]) {
          obj[id] = {};
        }
        obj = obj[id];
      }
      obj[parts[parts.length - 1]] = val;
    };
    _proto.get = function get(name) {
      var val = this.variables[name];
      if (val !== undefined) {
        return val;
      }
      return null;
    };
    _proto.lookup = function lookup(name) {
      var p = this.parent;
      var val = this.variables[name];
      if (val !== undefined) {
        return val;
      }
      return p && p.lookup(name);
    };
    _proto.resolve = function resolve(name, forWrite) {
      var p = forWrite && this.isolateWrites ? undefined : this.parent;
      var val = this.variables[name];
      if (val !== undefined) {
        return this;
      }
      return p && p.resolve(name);
    };
    _proto.push = function push(isolateWrites) {
      return new Frame2(this, isolateWrites);
    };
    _proto.pop = function pop() {
      return this.parent;
    };
    return Frame2;
  }();
  function makeMacro(argNames, kwargNames, func) {
    return function macro() {
      for (var _len = arguments.length, macroArgs = new Array(_len), _key = 0;_key < _len; _key++) {
        macroArgs[_key] = arguments[_key];
      }
      var argCount = numArgs(macroArgs);
      var args;
      var kwargs = getKeywordArgs(macroArgs);
      if (argCount > argNames.length) {
        args = macroArgs.slice(0, argNames.length);
        macroArgs.slice(args.length, argCount).forEach(function(val, i2) {
          if (i2 < kwargNames.length) {
            kwargs[kwargNames[i2]] = val;
          }
        });
        args.push(kwargs);
      } else if (argCount < argNames.length) {
        args = macroArgs.slice(0, argCount);
        for (var i = argCount;i < argNames.length; i++) {
          var arg = argNames[i];
          args.push(kwargs[arg]);
          delete kwargs[arg];
        }
        args.push(kwargs);
      } else {
        args = macroArgs;
      }
      return func.apply(this, args);
    };
  }
  function makeKeywordArgs(obj) {
    obj.__keywords = true;
    return obj;
  }
  function isKeywordArgs(obj) {
    return obj && Object.prototype.hasOwnProperty.call(obj, "__keywords");
  }
  function getKeywordArgs(args) {
    var len = args.length;
    if (len) {
      var lastArg = args[len - 1];
      if (isKeywordArgs(lastArg)) {
        return lastArg;
      }
    }
    return {};
  }
  function numArgs(args) {
    var len = args.length;
    if (len === 0) {
      return 0;
    }
    var lastArg = args[len - 1];
    if (isKeywordArgs(lastArg)) {
      return len - 1;
    } else {
      return len;
    }
  }
  function SafeString(val) {
    if (typeof val !== "string") {
      return val;
    }
    this.val = val;
    this.length = val.length;
  }
  SafeString.prototype = Object.create(String.prototype, {
    length: {
      writable: true,
      configurable: true,
      value: 0
    }
  });
  SafeString.prototype.valueOf = function valueOf() {
    return this.val;
  };
  SafeString.prototype.toString = function toString() {
    return this.val;
  };
  function copySafeness(dest, target) {
    if (dest instanceof SafeString) {
      return new SafeString(target);
    }
    return target.toString();
  }
  function markSafe(val) {
    var type = typeof val;
    if (type === "string") {
      return new SafeString(val);
    } else if (type !== "function") {
      return val;
    } else {
      return function wrapSafe(args) {
        var ret = val.apply(this, arguments);
        if (typeof ret === "string") {
          return new SafeString(ret);
        }
        return ret;
      };
    }
  }
  function suppressValue(val, autoescape) {
    val = val !== undefined && val !== null ? val : "";
    if (autoescape && !(val instanceof SafeString)) {
      val = lib.escape(val.toString());
    }
    return val;
  }
  function ensureDefined(val, lineno, colno) {
    if (val === null || val === undefined) {
      throw new lib.TemplateError("attempted to output null or undefined value", lineno + 1, colno + 1);
    }
    return val;
  }
  function memberLookup(obj, val) {
    if (obj === undefined || obj === null) {
      return;
    }
    if (typeof obj[val] === "function") {
      return function() {
        for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0;_key2 < _len2; _key2++) {
          args[_key2] = arguments[_key2];
        }
        return obj[val].apply(obj, args);
      };
    }
    return obj[val];
  }
  function callWrap(obj, name, context, args) {
    if (!obj) {
      throw new Error("Unable to call `" + name + "`, which is undefined or falsey");
    } else if (typeof obj !== "function") {
      throw new Error("Unable to call `" + name + "`, which is not a function");
    }
    return obj.apply(context, args);
  }
  function contextOrFrameLookup(context, frame, name) {
    var val = frame.lookup(name);
    return val !== undefined ? val : context.lookup(name);
  }
  function handleError(error, lineno, colno) {
    if (error.lineno) {
      return error;
    } else {
      return new lib.TemplateError(error, lineno, colno);
    }
  }
  function asyncEach(arr, dimen, iter, cb) {
    if (lib.isArray(arr)) {
      var len = arr.length;
      lib.asyncIter(arr, function iterCallback(item, i, next) {
        switch (dimen) {
          case 1:
            iter(item, i, len, next);
            break;
          case 2:
            iter(item[0], item[1], i, len, next);
            break;
          case 3:
            iter(item[0], item[1], item[2], i, len, next);
            break;
          default:
            item.push(i, len, next);
            iter.apply(this, item);
        }
      }, cb);
    } else {
      lib.asyncFor(arr, function iterCallback(key, val, i, len2, next) {
        iter(key, val, i, len2, next);
      }, cb);
    }
  }
  function asyncAll(arr, dimen, func, cb) {
    var finished = 0;
    var len;
    var outputArr;
    function done(i2, output) {
      finished++;
      outputArr[i2] = output;
      if (finished === len) {
        cb(null, outputArr.join(""));
      }
    }
    if (lib.isArray(arr)) {
      len = arr.length;
      outputArr = new Array(len);
      if (len === 0) {
        cb(null, "");
      } else {
        for (var i = 0;i < arr.length; i++) {
          var item = arr[i];
          switch (dimen) {
            case 1:
              func(item, i, len, done);
              break;
            case 2:
              func(item[0], item[1], i, len, done);
              break;
            case 3:
              func(item[0], item[1], item[2], i, len, done);
              break;
            default:
              item.push(i, len, done);
              func.apply(this, item);
          }
        }
      }
    } else {
      var keys = lib.keys(arr || {});
      len = keys.length;
      outputArr = new Array(len);
      if (len === 0) {
        cb(null, "");
      } else {
        for (var _i = 0;_i < keys.length; _i++) {
          var k = keys[_i];
          func(k, arr[k], _i, len, done);
        }
      }
    }
  }
  function fromIterator(arr) {
    if (typeof arr !== "object" || arr === null || lib.isArray(arr)) {
      return arr;
    } else if (supportsIterators && Symbol.iterator in arr) {
      return arrayFrom(arr);
    } else {
      return arr;
    }
  }
  module.exports = {
    Frame,
    makeMacro,
    makeKeywordArgs,
    numArgs,
    suppressValue,
    ensureDefined,
    memberLookup,
    contextOrFrameLookup,
    callWrap,
    handleError,
    isArray: lib.isArray,
    keys: lib.keys,
    SafeString,
    copySafeness,
    markSafe,
    asyncEach,
    asyncAll,
    inOperator: lib.inOperator,
    fromIterator
  };
});

// node_modules/nunjucks/src/compiler.js
var require_compiler = __commonJS((exports, module) => {
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o2, p2) {
      o2.__proto__ = p2;
      return o2;
    };
    return _setPrototypeOf(o, p);
  }
  var parser = require_parser();
  var transformer = require_transformer();
  var nodes = require_nodes();
  var _require = require_lib();
  var TemplateError = _require.TemplateError;
  var _require2 = require_runtime();
  var Frame = _require2.Frame;
  var _require3 = require_object();
  var Obj = _require3.Obj;
  var compareOps = {
    "==": "==",
    "===": "===",
    "!=": "!=",
    "!==": "!==",
    "<": "<",
    ">": ">",
    "<=": "<=",
    ">=": ">="
  };
  var Compiler = /* @__PURE__ */ function(_Obj) {
    _inheritsLoose(Compiler2, _Obj);
    function Compiler2() {
      return _Obj.apply(this, arguments) || this;
    }
    var _proto = Compiler2.prototype;
    _proto.init = function init(templateName, throwOnUndefined) {
      this.templateName = templateName;
      this.codebuf = [];
      this.lastId = 0;
      this.buffer = null;
      this.bufferStack = [];
      this._scopeClosers = "";
      this.inBlock = false;
      this.throwOnUndefined = throwOnUndefined;
    };
    _proto.fail = function fail(msg, lineno, colno) {
      if (lineno !== undefined) {
        lineno += 1;
      }
      if (colno !== undefined) {
        colno += 1;
      }
      throw new TemplateError(msg, lineno, colno);
    };
    _proto._pushBuffer = function _pushBuffer() {
      var id = this._tmpid();
      this.bufferStack.push(this.buffer);
      this.buffer = id;
      this._emit("var " + this.buffer + ' = "";');
      return id;
    };
    _proto._popBuffer = function _popBuffer() {
      this.buffer = this.bufferStack.pop();
    };
    _proto._emit = function _emit(code) {
      this.codebuf.push(code);
    };
    _proto._emitLine = function _emitLine(code) {
      this._emit(code + `
`);
    };
    _proto._emitLines = function _emitLines() {
      var _this = this;
      for (var _len = arguments.length, lines = new Array(_len), _key = 0;_key < _len; _key++) {
        lines[_key] = arguments[_key];
      }
      lines.forEach(function(line) {
        return _this._emitLine(line);
      });
    };
    _proto._emitFuncBegin = function _emitFuncBegin(node, name) {
      this.buffer = "output";
      this._scopeClosers = "";
      this._emitLine("function " + name + "(env, context, frame, runtime, cb) {");
      this._emitLine("var lineno = " + node.lineno + ";");
      this._emitLine("var colno = " + node.colno + ";");
      this._emitLine("var " + this.buffer + ' = "";');
      this._emitLine("try {");
    };
    _proto._emitFuncEnd = function _emitFuncEnd(noReturn) {
      if (!noReturn) {
        this._emitLine("cb(null, " + this.buffer + ");");
      }
      this._closeScopeLevels();
      this._emitLine("} catch (e) {");
      this._emitLine("  cb(runtime.handleError(e, lineno, colno));");
      this._emitLine("}");
      this._emitLine("}");
      this.buffer = null;
    };
    _proto._addScopeLevel = function _addScopeLevel() {
      this._scopeClosers += "})";
    };
    _proto._closeScopeLevels = function _closeScopeLevels() {
      this._emitLine(this._scopeClosers + ";");
      this._scopeClosers = "";
    };
    _proto._withScopedSyntax = function _withScopedSyntax(func) {
      var _scopeClosers = this._scopeClosers;
      this._scopeClosers = "";
      func.call(this);
      this._closeScopeLevels();
      this._scopeClosers = _scopeClosers;
    };
    _proto._makeCallback = function _makeCallback(res) {
      var err = this._tmpid();
      return "function(" + err + (res ? "," + res : "") + `) {
` + "if(" + err + ") { cb(" + err + "); return; }";
    };
    _proto._tmpid = function _tmpid() {
      this.lastId++;
      return "t_" + this.lastId;
    };
    _proto._templateName = function _templateName() {
      return this.templateName == null ? "undefined" : JSON.stringify(this.templateName);
    };
    _proto._compileChildren = function _compileChildren(node, frame) {
      var _this2 = this;
      node.children.forEach(function(child) {
        _this2.compile(child, frame);
      });
    };
    _proto._compileAggregate = function _compileAggregate(node, frame, startChar, endChar) {
      var _this3 = this;
      if (startChar) {
        this._emit(startChar);
      }
      node.children.forEach(function(child, i) {
        if (i > 0) {
          _this3._emit(",");
        }
        _this3.compile(child, frame);
      });
      if (endChar) {
        this._emit(endChar);
      }
    };
    _proto._compileExpression = function _compileExpression(node, frame) {
      this.assertType(node, nodes.Literal, nodes.Symbol, nodes.Group, nodes.Array, nodes.Dict, nodes.FunCall, nodes.Caller, nodes.Filter, nodes.LookupVal, nodes.Compare, nodes.InlineIf, nodes.In, nodes.Is, nodes.And, nodes.Or, nodes.Not, nodes.Add, nodes.Concat, nodes.Sub, nodes.Mul, nodes.Div, nodes.FloorDiv, nodes.Mod, nodes.Pow, nodes.Neg, nodes.Pos, nodes.Compare, nodes.NodeList);
      this.compile(node, frame);
    };
    _proto.assertType = function assertType(node) {
      for (var _len2 = arguments.length, types = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1;_key2 < _len2; _key2++) {
        types[_key2 - 1] = arguments[_key2];
      }
      if (!types.some(function(t) {
        return node instanceof t;
      })) {
        this.fail("assertType: invalid type: " + node.typename, node.lineno, node.colno);
      }
    };
    _proto.compileCallExtension = function compileCallExtension(node, frame, async) {
      var _this4 = this;
      var args = node.args;
      var contentArgs = node.contentArgs;
      var autoescape = typeof node.autoescape === "boolean" ? node.autoescape : true;
      if (!async) {
        this._emit(this.buffer + " += runtime.suppressValue(");
      }
      this._emit('env.getExtension("' + node.extName + '")["' + node.prop + '"](');
      this._emit("context");
      if (args || contentArgs) {
        this._emit(",");
      }
      if (args) {
        if (!(args instanceof nodes.NodeList)) {
          this.fail("compileCallExtension: arguments must be a NodeList, " + "use `parser.parseSignature`");
        }
        args.children.forEach(function(arg, i) {
          _this4._compileExpression(arg, frame);
          if (i !== args.children.length - 1 || contentArgs.length) {
            _this4._emit(",");
          }
        });
      }
      if (contentArgs.length) {
        contentArgs.forEach(function(arg, i) {
          if (i > 0) {
            _this4._emit(",");
          }
          if (arg) {
            _this4._emitLine("function(cb) {");
            _this4._emitLine("if(!cb) { cb = function(err) { if(err) { throw err; }}}");
            var id = _this4._pushBuffer();
            _this4._withScopedSyntax(function() {
              _this4.compile(arg, frame);
              _this4._emitLine("cb(null, " + id + ");");
            });
            _this4._popBuffer();
            _this4._emitLine("return " + id + ";");
            _this4._emitLine("}");
          } else {
            _this4._emit("null");
          }
        });
      }
      if (async) {
        var res = this._tmpid();
        this._emitLine(", " + this._makeCallback(res));
        this._emitLine(this.buffer + " += runtime.suppressValue(" + res + ", " + autoescape + " && env.opts.autoescape);");
        this._addScopeLevel();
      } else {
        this._emit(")");
        this._emit(", " + autoescape + ` && env.opts.autoescape);
`);
      }
    };
    _proto.compileCallExtensionAsync = function compileCallExtensionAsync(node, frame) {
      this.compileCallExtension(node, frame, true);
    };
    _proto.compileNodeList = function compileNodeList(node, frame) {
      this._compileChildren(node, frame);
    };
    _proto.compileLiteral = function compileLiteral(node) {
      if (typeof node.value === "string") {
        var val = node.value.replace(/\\/g, "\\\\");
        val = val.replace(/"/g, "\\\"");
        val = val.replace(/\n/g, "\\n");
        val = val.replace(/\r/g, "\\r");
        val = val.replace(/\t/g, "\\t");
        val = val.replace(/\u2028/g, "\\u2028");
        this._emit('"' + val + '"');
      } else if (node.value === null) {
        this._emit("null");
      } else {
        this._emit(node.value.toString());
      }
    };
    _proto.compileSymbol = function compileSymbol(node, frame) {
      var name = node.value;
      var v = frame.lookup(name);
      if (v) {
        this._emit(v);
      } else {
        this._emit("runtime.contextOrFrameLookup(" + 'context, frame, "' + name + '")');
      }
    };
    _proto.compileGroup = function compileGroup(node, frame) {
      this._compileAggregate(node, frame, "(", ")");
    };
    _proto.compileArray = function compileArray(node, frame) {
      this._compileAggregate(node, frame, "[", "]");
    };
    _proto.compileDict = function compileDict(node, frame) {
      this._compileAggregate(node, frame, "{", "}");
    };
    _proto.compilePair = function compilePair(node, frame) {
      var key = node.key;
      var val = node.value;
      if (key instanceof nodes.Symbol) {
        key = new nodes.Literal(key.lineno, key.colno, key.value);
      } else if (!(key instanceof nodes.Literal && typeof key.value === "string")) {
        this.fail("compilePair: Dict keys must be strings or names", key.lineno, key.colno);
      }
      this.compile(key, frame);
      this._emit(": ");
      this._compileExpression(val, frame);
    };
    _proto.compileInlineIf = function compileInlineIf(node, frame) {
      this._emit("(");
      this.compile(node.cond, frame);
      this._emit("?");
      this.compile(node.body, frame);
      this._emit(":");
      if (node.else_ !== null) {
        this.compile(node.else_, frame);
      } else {
        this._emit('""');
      }
      this._emit(")");
    };
    _proto.compileIn = function compileIn(node, frame) {
      this._emit("runtime.inOperator(");
      this.compile(node.left, frame);
      this._emit(",");
      this.compile(node.right, frame);
      this._emit(")");
    };
    _proto.compileIs = function compileIs(node, frame) {
      var right = node.right.name ? node.right.name.value : node.right.value;
      this._emit('env.getTest("' + right + '").call(context, ');
      this.compile(node.left, frame);
      if (node.right.args) {
        this._emit(",");
        this.compile(node.right.args, frame);
      }
      this._emit(") === true");
    };
    _proto._binOpEmitter = function _binOpEmitter(node, frame, str) {
      this.compile(node.left, frame);
      this._emit(str);
      this.compile(node.right, frame);
    };
    _proto.compileOr = function compileOr(node, frame) {
      return this._binOpEmitter(node, frame, " || ");
    };
    _proto.compileAnd = function compileAnd(node, frame) {
      return this._binOpEmitter(node, frame, " && ");
    };
    _proto.compileAdd = function compileAdd(node, frame) {
      return this._binOpEmitter(node, frame, " + ");
    };
    _proto.compileConcat = function compileConcat(node, frame) {
      return this._binOpEmitter(node, frame, ' + "" + ');
    };
    _proto.compileSub = function compileSub(node, frame) {
      return this._binOpEmitter(node, frame, " - ");
    };
    _proto.compileMul = function compileMul(node, frame) {
      return this._binOpEmitter(node, frame, " * ");
    };
    _proto.compileDiv = function compileDiv(node, frame) {
      return this._binOpEmitter(node, frame, " / ");
    };
    _proto.compileMod = function compileMod(node, frame) {
      return this._binOpEmitter(node, frame, " % ");
    };
    _proto.compileNot = function compileNot(node, frame) {
      this._emit("!");
      this.compile(node.target, frame);
    };
    _proto.compileFloorDiv = function compileFloorDiv(node, frame) {
      this._emit("Math.floor(");
      this.compile(node.left, frame);
      this._emit(" / ");
      this.compile(node.right, frame);
      this._emit(")");
    };
    _proto.compilePow = function compilePow(node, frame) {
      this._emit("Math.pow(");
      this.compile(node.left, frame);
      this._emit(", ");
      this.compile(node.right, frame);
      this._emit(")");
    };
    _proto.compileNeg = function compileNeg(node, frame) {
      this._emit("-");
      this.compile(node.target, frame);
    };
    _proto.compilePos = function compilePos(node, frame) {
      this._emit("+");
      this.compile(node.target, frame);
    };
    _proto.compileCompare = function compileCompare(node, frame) {
      var _this5 = this;
      this.compile(node.expr, frame);
      node.ops.forEach(function(op) {
        _this5._emit(" " + compareOps[op.type] + " ");
        _this5.compile(op.expr, frame);
      });
    };
    _proto.compileLookupVal = function compileLookupVal(node, frame) {
      this._emit("runtime.memberLookup((");
      this._compileExpression(node.target, frame);
      this._emit("),");
      this._compileExpression(node.val, frame);
      this._emit(")");
    };
    _proto._getNodeName = function _getNodeName(node) {
      switch (node.typename) {
        case "Symbol":
          return node.value;
        case "FunCall":
          return "the return value of (" + this._getNodeName(node.name) + ")";
        case "LookupVal":
          return this._getNodeName(node.target) + '["' + this._getNodeName(node.val) + '"]';
        case "Literal":
          return node.value.toString();
        default:
          return "--expression--";
      }
    };
    _proto.compileFunCall = function compileFunCall(node, frame) {
      this._emit("(lineno = " + node.lineno + ", colno = " + node.colno + ", ");
      this._emit("runtime.callWrap(");
      this._compileExpression(node.name, frame);
      this._emit(', "' + this._getNodeName(node.name).replace(/"/g, "\\\"") + '", context, ');
      this._compileAggregate(node.args, frame, "[", "])");
      this._emit(")");
    };
    _proto.compileFilter = function compileFilter(node, frame) {
      var name = node.name;
      this.assertType(name, nodes.Symbol);
      this._emit('env.getFilter("' + name.value + '").call(context, ');
      this._compileAggregate(node.args, frame);
      this._emit(")");
    };
    _proto.compileFilterAsync = function compileFilterAsync(node, frame) {
      var name = node.name;
      var symbol = node.symbol.value;
      this.assertType(name, nodes.Symbol);
      frame.set(symbol, symbol);
      this._emit('env.getFilter("' + name.value + '").call(context, ');
      this._compileAggregate(node.args, frame);
      this._emitLine(", " + this._makeCallback(symbol));
      this._addScopeLevel();
    };
    _proto.compileKeywordArgs = function compileKeywordArgs(node, frame) {
      this._emit("runtime.makeKeywordArgs(");
      this.compileDict(node, frame);
      this._emit(")");
    };
    _proto.compileSet = function compileSet(node, frame) {
      var _this6 = this;
      var ids = [];
      node.targets.forEach(function(target) {
        var name = target.value;
        var id = frame.lookup(name);
        if (id === null || id === undefined) {
          id = _this6._tmpid();
          _this6._emitLine("var " + id + ";");
        }
        ids.push(id);
      });
      if (node.value) {
        this._emit(ids.join(" = ") + " = ");
        this._compileExpression(node.value, frame);
        this._emitLine(";");
      } else {
        this._emit(ids.join(" = ") + " = ");
        this.compile(node.body, frame);
        this._emitLine(";");
      }
      node.targets.forEach(function(target, i) {
        var id = ids[i];
        var name = target.value;
        _this6._emitLine('frame.set("' + name + '", ' + id + ", true);");
        _this6._emitLine("if(frame.topLevel) {");
        _this6._emitLine('context.setVariable("' + name + '", ' + id + ");");
        _this6._emitLine("}");
        if (name.charAt(0) !== "_") {
          _this6._emitLine("if(frame.topLevel) {");
          _this6._emitLine('context.addExport("' + name + '", ' + id + ");");
          _this6._emitLine("}");
        }
      });
    };
    _proto.compileSwitch = function compileSwitch(node, frame) {
      var _this7 = this;
      this._emit("switch (");
      this.compile(node.expr, frame);
      this._emit(") {");
      node.cases.forEach(function(c, i) {
        _this7._emit("case ");
        _this7.compile(c.cond, frame);
        _this7._emit(": ");
        _this7.compile(c.body, frame);
        if (c.body.children.length) {
          _this7._emitLine("break;");
        }
      });
      if (node.default) {
        this._emit("default:");
        this.compile(node.default, frame);
      }
      this._emit("}");
    };
    _proto.compileIf = function compileIf(node, frame, async) {
      var _this8 = this;
      this._emit("if(");
      this._compileExpression(node.cond, frame);
      this._emitLine(") {");
      this._withScopedSyntax(function() {
        _this8.compile(node.body, frame);
        if (async) {
          _this8._emit("cb()");
        }
      });
      if (node.else_) {
        this._emitLine(`}
else {`);
        this._withScopedSyntax(function() {
          _this8.compile(node.else_, frame);
          if (async) {
            _this8._emit("cb()");
          }
        });
      } else if (async) {
        this._emitLine(`}
else {`);
        this._emit("cb()");
      }
      this._emitLine("}");
    };
    _proto.compileIfAsync = function compileIfAsync(node, frame) {
      this._emit("(function(cb) {");
      this.compileIf(node, frame, true);
      this._emit("})(" + this._makeCallback());
      this._addScopeLevel();
    };
    _proto._emitLoopBindings = function _emitLoopBindings(node, arr, i, len) {
      var _this9 = this;
      var bindings = [{
        name: "index",
        val: i + " + 1"
      }, {
        name: "index0",
        val: i
      }, {
        name: "revindex",
        val: len + " - " + i
      }, {
        name: "revindex0",
        val: len + " - " + i + " - 1"
      }, {
        name: "first",
        val: i + " === 0"
      }, {
        name: "last",
        val: i + " === " + len + " - 1"
      }, {
        name: "length",
        val: len
      }];
      bindings.forEach(function(b) {
        _this9._emitLine('frame.set("loop.' + b.name + '", ' + b.val + ");");
      });
    };
    _proto.compileFor = function compileFor(node, frame) {
      var _this10 = this;
      var i = this._tmpid();
      var len = this._tmpid();
      var arr = this._tmpid();
      frame = frame.push();
      this._emitLine("frame = frame.push();");
      this._emit("var " + arr + " = ");
      this._compileExpression(node.arr, frame);
      this._emitLine(";");
      this._emit("if(" + arr + ") {");
      this._emitLine(arr + " = runtime.fromIterator(" + arr + ");");
      if (node.name instanceof nodes.Array) {
        this._emitLine("var " + i + ";");
        this._emitLine("if(runtime.isArray(" + arr + ")) {");
        this._emitLine("var " + len + " = " + arr + ".length;");
        this._emitLine("for(" + i + "=0; " + i + " < " + arr + ".length; " + i + "++) {");
        node.name.children.forEach(function(child, u) {
          var tid = _this10._tmpid();
          _this10._emitLine("var " + tid + " = " + arr + "[" + i + "][" + u + "];");
          _this10._emitLine('frame.set("' + child + '", ' + arr + "[" + i + "][" + u + "]);");
          frame.set(node.name.children[u].value, tid);
        });
        this._emitLoopBindings(node, arr, i, len);
        this._withScopedSyntax(function() {
          _this10.compile(node.body, frame);
        });
        this._emitLine("}");
        this._emitLine("} else {");
        var _node$name$children = node.name.children, key = _node$name$children[0], val = _node$name$children[1];
        var k = this._tmpid();
        var v = this._tmpid();
        frame.set(key.value, k);
        frame.set(val.value, v);
        this._emitLine(i + " = -1;");
        this._emitLine("var " + len + " = runtime.keys(" + arr + ").length;");
        this._emitLine("for(var " + k + " in " + arr + ") {");
        this._emitLine(i + "++;");
        this._emitLine("var " + v + " = " + arr + "[" + k + "];");
        this._emitLine('frame.set("' + key.value + '", ' + k + ");");
        this._emitLine('frame.set("' + val.value + '", ' + v + ");");
        this._emitLoopBindings(node, arr, i, len);
        this._withScopedSyntax(function() {
          _this10.compile(node.body, frame);
        });
        this._emitLine("}");
        this._emitLine("}");
      } else {
        var _v = this._tmpid();
        frame.set(node.name.value, _v);
        this._emitLine("var " + len + " = " + arr + ".length;");
        this._emitLine("for(var " + i + "=0; " + i + " < " + arr + ".length; " + i + "++) {");
        this._emitLine("var " + _v + " = " + arr + "[" + i + "];");
        this._emitLine('frame.set("' + node.name.value + '", ' + _v + ");");
        this._emitLoopBindings(node, arr, i, len);
        this._withScopedSyntax(function() {
          _this10.compile(node.body, frame);
        });
        this._emitLine("}");
      }
      this._emitLine("}");
      if (node.else_) {
        this._emitLine("if (!" + len + ") {");
        this.compile(node.else_, frame);
        this._emitLine("}");
      }
      this._emitLine("frame = frame.pop();");
    };
    _proto._compileAsyncLoop = function _compileAsyncLoop(node, frame, parallel) {
      var _this11 = this;
      var i = this._tmpid();
      var len = this._tmpid();
      var arr = this._tmpid();
      var asyncMethod = parallel ? "asyncAll" : "asyncEach";
      frame = frame.push();
      this._emitLine("frame = frame.push();");
      this._emit("var " + arr + " = runtime.fromIterator(");
      this._compileExpression(node.arr, frame);
      this._emitLine(");");
      if (node.name instanceof nodes.Array) {
        var arrayLen = node.name.children.length;
        this._emit("runtime." + asyncMethod + "(" + arr + ", " + arrayLen + ", function(");
        node.name.children.forEach(function(name) {
          _this11._emit(name.value + ",");
        });
        this._emit(i + "," + len + ",next) {");
        node.name.children.forEach(function(name) {
          var id2 = name.value;
          frame.set(id2, id2);
          _this11._emitLine('frame.set("' + id2 + '", ' + id2 + ");");
        });
      } else {
        var id = node.name.value;
        this._emitLine("runtime." + asyncMethod + "(" + arr + ", 1, function(" + id + ", " + i + ", " + len + ",next) {");
        this._emitLine('frame.set("' + id + '", ' + id + ");");
        frame.set(id, id);
      }
      this._emitLoopBindings(node, arr, i, len);
      this._withScopedSyntax(function() {
        var buf;
        if (parallel) {
          buf = _this11._pushBuffer();
        }
        _this11.compile(node.body, frame);
        _this11._emitLine("next(" + i + (buf ? "," + buf : "") + ");");
        if (parallel) {
          _this11._popBuffer();
        }
      });
      var output = this._tmpid();
      this._emitLine("}, " + this._makeCallback(output));
      this._addScopeLevel();
      if (parallel) {
        this._emitLine(this.buffer + " += " + output + ";");
      }
      if (node.else_) {
        this._emitLine("if (!" + arr + ".length) {");
        this.compile(node.else_, frame);
        this._emitLine("}");
      }
      this._emitLine("frame = frame.pop();");
    };
    _proto.compileAsyncEach = function compileAsyncEach(node, frame) {
      this._compileAsyncLoop(node, frame);
    };
    _proto.compileAsyncAll = function compileAsyncAll(node, frame) {
      this._compileAsyncLoop(node, frame, true);
    };
    _proto._compileMacro = function _compileMacro(node, frame) {
      var _this12 = this;
      var args = [];
      var kwargs = null;
      var funcId = "macro_" + this._tmpid();
      var keepFrame = frame !== undefined;
      node.args.children.forEach(function(arg, i) {
        if (i === node.args.children.length - 1 && arg instanceof nodes.Dict) {
          kwargs = arg;
        } else {
          _this12.assertType(arg, nodes.Symbol);
          args.push(arg);
        }
      });
      var realNames = [].concat(args.map(function(n) {
        return "l_" + n.value;
      }), ["kwargs"]);
      var argNames = args.map(function(n) {
        return '"' + n.value + '"';
      });
      var kwargNames = (kwargs && kwargs.children || []).map(function(n) {
        return '"' + n.key.value + '"';
      });
      var currFrame;
      if (keepFrame) {
        currFrame = frame.push(true);
      } else {
        currFrame = new Frame;
      }
      this._emitLines("var " + funcId + " = runtime.makeMacro(", "[" + argNames.join(", ") + "], ", "[" + kwargNames.join(", ") + "], ", "function (" + realNames.join(", ") + ") {", "var callerFrame = frame;", "frame = " + (keepFrame ? "frame.push(true);" : "new runtime.Frame();"), "kwargs = kwargs || {};", 'if (Object.prototype.hasOwnProperty.call(kwargs, "caller")) {', 'frame.set("caller", kwargs.caller); }');
      args.forEach(function(arg) {
        _this12._emitLine('frame.set("' + arg.value + '", l_' + arg.value + ");");
        currFrame.set(arg.value, "l_" + arg.value);
      });
      if (kwargs) {
        kwargs.children.forEach(function(pair) {
          var name = pair.key.value;
          _this12._emit('frame.set("' + name + '", ');
          _this12._emit('Object.prototype.hasOwnProperty.call(kwargs, "' + name + '")');
          _this12._emit(' ? kwargs["' + name + '"] : ');
          _this12._compileExpression(pair.value, currFrame);
          _this12._emit(");");
        });
      }
      var bufferId = this._pushBuffer();
      this._withScopedSyntax(function() {
        _this12.compile(node.body, currFrame);
      });
      this._emitLine("frame = " + (keepFrame ? "frame.pop();" : "callerFrame;"));
      this._emitLine("return new runtime.SafeString(" + bufferId + ");");
      this._emitLine("});");
      this._popBuffer();
      return funcId;
    };
    _proto.compileMacro = function compileMacro(node, frame) {
      var funcId = this._compileMacro(node);
      var name = node.name.value;
      frame.set(name, funcId);
      if (frame.parent) {
        this._emitLine('frame.set("' + name + '", ' + funcId + ");");
      } else {
        if (node.name.value.charAt(0) !== "_") {
          this._emitLine('context.addExport("' + name + '");');
        }
        this._emitLine('context.setVariable("' + name + '", ' + funcId + ");");
      }
    };
    _proto.compileCaller = function compileCaller(node, frame) {
      this._emit("(function (){");
      var funcId = this._compileMacro(node, frame);
      this._emit("return " + funcId + ";})()");
    };
    _proto._compileGetTemplate = function _compileGetTemplate(node, frame, eagerCompile, ignoreMissing) {
      var parentTemplateId = this._tmpid();
      var parentName = this._templateName();
      var cb = this._makeCallback(parentTemplateId);
      var eagerCompileArg = eagerCompile ? "true" : "false";
      var ignoreMissingArg = ignoreMissing ? "true" : "false";
      this._emit("env.getTemplate(");
      this._compileExpression(node.template, frame);
      this._emitLine(", " + eagerCompileArg + ", " + parentName + ", " + ignoreMissingArg + ", " + cb);
      return parentTemplateId;
    };
    _proto.compileImport = function compileImport(node, frame) {
      var target = node.target.value;
      var id = this._compileGetTemplate(node, frame, false, false);
      this._addScopeLevel();
      this._emitLine(id + ".getExported(" + (node.withContext ? "context.getVariables(), frame, " : "") + this._makeCallback(id));
      this._addScopeLevel();
      frame.set(target, id);
      if (frame.parent) {
        this._emitLine('frame.set("' + target + '", ' + id + ");");
      } else {
        this._emitLine('context.setVariable("' + target + '", ' + id + ");");
      }
    };
    _proto.compileFromImport = function compileFromImport(node, frame) {
      var _this13 = this;
      var importedId = this._compileGetTemplate(node, frame, false, false);
      this._addScopeLevel();
      this._emitLine(importedId + ".getExported(" + (node.withContext ? "context.getVariables(), frame, " : "") + this._makeCallback(importedId));
      this._addScopeLevel();
      node.names.children.forEach(function(nameNode) {
        var name;
        var alias;
        var id = _this13._tmpid();
        if (nameNode instanceof nodes.Pair) {
          name = nameNode.key.value;
          alias = nameNode.value.value;
        } else {
          name = nameNode.value;
          alias = name;
        }
        _this13._emitLine("if(Object.prototype.hasOwnProperty.call(" + importedId + ', "' + name + '")) {');
        _this13._emitLine("var " + id + " = " + importedId + "." + name + ";");
        _this13._emitLine("} else {");
        _this13._emitLine(`cb(new Error("cannot import '` + name + `'")); return;`);
        _this13._emitLine("}");
        frame.set(alias, id);
        if (frame.parent) {
          _this13._emitLine('frame.set("' + alias + '", ' + id + ");");
        } else {
          _this13._emitLine('context.setVariable("' + alias + '", ' + id + ");");
        }
      });
    };
    _proto.compileBlock = function compileBlock(node) {
      var id = this._tmpid();
      if (!this.inBlock) {
        this._emit('(parentTemplate ? function(e, c, f, r, cb) { cb(""); } : ');
      }
      this._emit('context.getBlock("' + node.name.value + '")');
      if (!this.inBlock) {
        this._emit(")");
      }
      this._emitLine("(env, context, frame, runtime, " + this._makeCallback(id));
      this._emitLine(this.buffer + " += " + id + ";");
      this._addScopeLevel();
    };
    _proto.compileSuper = function compileSuper(node, frame) {
      var name = node.blockName.value;
      var id = node.symbol.value;
      var cb = this._makeCallback(id);
      this._emitLine('context.getSuper(env, "' + name + '", b_' + name + ", frame, runtime, " + cb);
      this._emitLine(id + " = runtime.markSafe(" + id + ");");
      this._addScopeLevel();
      frame.set(id, id);
    };
    _proto.compileExtends = function compileExtends(node, frame) {
      var k = this._tmpid();
      var parentTemplateId = this._compileGetTemplate(node, frame, true, false);
      this._emitLine("parentTemplate = " + parentTemplateId);
      this._emitLine("for(var " + k + " in parentTemplate.blocks) {");
      this._emitLine("context.addBlock(" + k + ", parentTemplate.blocks[" + k + "]);");
      this._emitLine("}");
      this._addScopeLevel();
    };
    _proto.compileInclude = function compileInclude(node, frame) {
      this._emitLine("var tasks = [];");
      this._emitLine("tasks.push(");
      this._emitLine("function(callback) {");
      var id = this._compileGetTemplate(node, frame, false, node.ignoreMissing);
      this._emitLine("callback(null," + id + ");});");
      this._emitLine("});");
      var id2 = this._tmpid();
      this._emitLine("tasks.push(");
      this._emitLine("function(template, callback){");
      this._emitLine("template.render(context.getVariables(), frame, " + this._makeCallback(id2));
      this._emitLine("callback(null," + id2 + ");});");
      this._emitLine("});");
      this._emitLine("tasks.push(");
      this._emitLine("function(result, callback){");
      this._emitLine(this.buffer + " += result;");
      this._emitLine("callback(null);");
      this._emitLine("});");
      this._emitLine("env.waterfall(tasks, function(){");
      this._addScopeLevel();
    };
    _proto.compileTemplateData = function compileTemplateData(node, frame) {
      this.compileLiteral(node, frame);
    };
    _proto.compileCapture = function compileCapture(node, frame) {
      var _this14 = this;
      var buffer = this.buffer;
      this.buffer = "output";
      this._emitLine("(function() {");
      this._emitLine('var output = "";');
      this._withScopedSyntax(function() {
        _this14.compile(node.body, frame);
      });
      this._emitLine("return output;");
      this._emitLine("})()");
      this.buffer = buffer;
    };
    _proto.compileOutput = function compileOutput(node, frame) {
      var _this15 = this;
      var children = node.children;
      children.forEach(function(child) {
        if (child instanceof nodes.TemplateData) {
          if (child.value) {
            _this15._emit(_this15.buffer + " += ");
            _this15.compileLiteral(child, frame);
            _this15._emitLine(";");
          }
        } else {
          _this15._emit(_this15.buffer + " += runtime.suppressValue(");
          if (_this15.throwOnUndefined) {
            _this15._emit("runtime.ensureDefined(");
          }
          _this15.compile(child, frame);
          if (_this15.throwOnUndefined) {
            _this15._emit("," + node.lineno + "," + node.colno + ")");
          }
          _this15._emit(`, env.opts.autoescape);
`);
        }
      });
    };
    _proto.compileRoot = function compileRoot(node, frame) {
      var _this16 = this;
      if (frame) {
        this.fail("compileRoot: root node can't have frame");
      }
      frame = new Frame;
      this._emitFuncBegin(node, "root");
      this._emitLine("var parentTemplate = null;");
      this._compileChildren(node, frame);
      this._emitLine("if(parentTemplate) {");
      this._emitLine("parentTemplate.rootRenderFunc(env, context, frame, runtime, cb);");
      this._emitLine("} else {");
      this._emitLine("cb(null, " + this.buffer + ");");
      this._emitLine("}");
      this._emitFuncEnd(true);
      this.inBlock = true;
      var blockNames = [];
      var blocks = node.findAll(nodes.Block);
      blocks.forEach(function(block, i) {
        var name = block.name.value;
        if (blockNames.indexOf(name) !== -1) {
          throw new Error('Block "' + name + '" defined more than once.');
        }
        blockNames.push(name);
        _this16._emitFuncBegin(block, "b_" + name);
        var tmpFrame = new Frame;
        _this16._emitLine("var frame = frame.push(true);");
        _this16.compile(block.body, tmpFrame);
        _this16._emitFuncEnd();
      });
      this._emitLine("return {");
      blocks.forEach(function(block, i) {
        var blockName = "b_" + block.name.value;
        _this16._emitLine(blockName + ": " + blockName + ",");
      });
      this._emitLine(`root: root
};`);
    };
    _proto.compile = function compile(node, frame) {
      var _compile = this["compile" + node.typename];
      if (_compile) {
        _compile.call(this, node, frame);
      } else {
        this.fail("compile: Cannot compile node: " + node.typename, node.lineno, node.colno);
      }
    };
    _proto.getCode = function getCode() {
      return this.codebuf.join("");
    };
    return Compiler2;
  }(Obj);
  module.exports = {
    compile: function compile(src, asyncFilters, extensions, name, opts) {
      if (opts === undefined) {
        opts = {};
      }
      var c = new Compiler(name, opts.throwOnUndefined);
      var preprocessors = (extensions || []).map(function(ext) {
        return ext.preprocess;
      }).filter(function(f) {
        return !!f;
      });
      var processedSrc = preprocessors.reduce(function(s, processor) {
        return processor(s);
      }, src);
      c.compile(transformer.transform(parser.parse(processedSrc, extensions, opts), asyncFilters, name));
      return c.getCode();
    },
    Compiler
  };
});

// node_modules/nunjucks/src/filters.js
var require_filters = __commonJS((exports, module) => {
  var lib = require_lib();
  var r = require_runtime();
  var _exports = module.exports = {};
  function normalize(value, defaultValue) {
    if (value === null || value === undefined || value === false) {
      return defaultValue;
    }
    return value;
  }
  _exports.abs = Math.abs;
  function isNaN2(num) {
    return num !== num;
  }
  function batch(arr, linecount, fillWith) {
    var i;
    var res = [];
    var tmp = [];
    for (i = 0;i < arr.length; i++) {
      if (i % linecount === 0 && tmp.length) {
        res.push(tmp);
        tmp = [];
      }
      tmp.push(arr[i]);
    }
    if (tmp.length) {
      if (fillWith) {
        for (i = tmp.length;i < linecount; i++) {
          tmp.push(fillWith);
        }
      }
      res.push(tmp);
    }
    return res;
  }
  _exports.batch = batch;
  function capitalize(str) {
    str = normalize(str, "");
    var ret = str.toLowerCase();
    return r.copySafeness(str, ret.charAt(0).toUpperCase() + ret.slice(1));
  }
  _exports.capitalize = capitalize;
  function center(str, width) {
    str = normalize(str, "");
    width = width || 80;
    if (str.length >= width) {
      return str;
    }
    var spaces = width - str.length;
    var pre = lib.repeat(" ", spaces / 2 - spaces % 2);
    var post = lib.repeat(" ", spaces / 2);
    return r.copySafeness(str, pre + str + post);
  }
  _exports.center = center;
  function default_(val, def, bool) {
    if (bool) {
      return val || def;
    } else {
      return val !== undefined ? val : def;
    }
  }
  _exports["default"] = default_;
  function dictsort(val, caseSensitive, by) {
    if (!lib.isObject(val)) {
      throw new lib.TemplateError("dictsort filter: val must be an object");
    }
    var array = [];
    for (var k in val) {
      array.push([k, val[k]]);
    }
    var si;
    if (by === undefined || by === "key") {
      si = 0;
    } else if (by === "value") {
      si = 1;
    } else {
      throw new lib.TemplateError("dictsort filter: You can only sort by either key or value");
    }
    array.sort(function(t1, t2) {
      var a = t1[si];
      var b = t2[si];
      if (!caseSensitive) {
        if (lib.isString(a)) {
          a = a.toUpperCase();
        }
        if (lib.isString(b)) {
          b = b.toUpperCase();
        }
      }
      return a > b ? 1 : a === b ? 0 : -1;
    });
    return array;
  }
  _exports.dictsort = dictsort;
  function dump(obj, spaces) {
    return JSON.stringify(obj, null, spaces);
  }
  _exports.dump = dump;
  function escape(str) {
    if (str instanceof r.SafeString) {
      return str;
    }
    str = str === null || str === undefined ? "" : str;
    return r.markSafe(lib.escape(str.toString()));
  }
  _exports.escape = escape;
  function safe(str) {
    if (str instanceof r.SafeString) {
      return str;
    }
    str = str === null || str === undefined ? "" : str;
    return r.markSafe(str.toString());
  }
  _exports.safe = safe;
  function first(arr) {
    return arr[0];
  }
  _exports.first = first;
  function forceescape(str) {
    str = str === null || str === undefined ? "" : str;
    return r.markSafe(lib.escape(str.toString()));
  }
  _exports.forceescape = forceescape;
  function groupby(arr, attr) {
    return lib.groupBy(arr, attr, this.env.opts.throwOnUndefined);
  }
  _exports.groupby = groupby;
  function indent(str, width, indentfirst) {
    str = normalize(str, "");
    if (str === "") {
      return "";
    }
    width = width || 4;
    var lines = str.split(`
`);
    var sp = lib.repeat(" ", width);
    var res = lines.map(function(l, i) {
      return i === 0 && !indentfirst ? l : "" + sp + l;
    }).join(`
`);
    return r.copySafeness(str, res);
  }
  _exports.indent = indent;
  function join(arr, del, attr) {
    del = del || "";
    if (attr) {
      arr = lib.map(arr, function(v) {
        return v[attr];
      });
    }
    return arr.join(del);
  }
  _exports.join = join;
  function last(arr) {
    return arr[arr.length - 1];
  }
  _exports.last = last;
  function lengthFilter(val) {
    var value = normalize(val, "");
    if (value !== undefined) {
      if (typeof Map === "function" && value instanceof Map || typeof Set === "function" && value instanceof Set) {
        return value.size;
      }
      if (lib.isObject(value) && !(value instanceof r.SafeString)) {
        return lib.keys(value).length;
      }
      return value.length;
    }
    return 0;
  }
  _exports.length = lengthFilter;
  function list(val) {
    if (lib.isString(val)) {
      return val.split("");
    } else if (lib.isObject(val)) {
      return lib._entries(val || {}).map(function(_ref) {
        var key = _ref[0], value = _ref[1];
        return {
          key,
          value
        };
      });
    } else if (lib.isArray(val)) {
      return val;
    } else {
      throw new lib.TemplateError("list filter: type not iterable");
    }
  }
  _exports.list = list;
  function lower(str) {
    str = normalize(str, "");
    return str.toLowerCase();
  }
  _exports.lower = lower;
  function nl2br(str) {
    if (str === null || str === undefined) {
      return "";
    }
    return r.copySafeness(str, str.replace(/\r\n|\n/g, `<br />
`));
  }
  _exports.nl2br = nl2br;
  function random(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
  }
  _exports.random = random;
  function getSelectOrReject(expectedTestResult) {
    function filter(arr, testName, secondArg) {
      if (testName === undefined) {
        testName = "truthy";
      }
      var context = this;
      var test = context.env.getTest(testName);
      return lib.toArray(arr).filter(function examineTestResult(item) {
        return test.call(context, item, secondArg) === expectedTestResult;
      });
    }
    return filter;
  }
  _exports.reject = getSelectOrReject(false);
  function rejectattr(arr, attr) {
    return arr.filter(function(item) {
      return !item[attr];
    });
  }
  _exports.rejectattr = rejectattr;
  _exports.select = getSelectOrReject(true);
  function selectattr(arr, attr) {
    return arr.filter(function(item) {
      return !!item[attr];
    });
  }
  _exports.selectattr = selectattr;
  function replace(str, old, new_, maxCount) {
    var originalStr = str;
    if (old instanceof RegExp) {
      return str.replace(old, new_);
    }
    if (typeof maxCount === "undefined") {
      maxCount = -1;
    }
    var res = "";
    if (typeof old === "number") {
      old = "" + old;
    } else if (typeof old !== "string") {
      return str;
    }
    if (typeof str === "number") {
      str = "" + str;
    }
    if (typeof str !== "string" && !(str instanceof r.SafeString)) {
      return str;
    }
    if (old === "") {
      res = new_ + str.split("").join(new_) + new_;
      return r.copySafeness(str, res);
    }
    var nextIndex = str.indexOf(old);
    if (maxCount === 0 || nextIndex === -1) {
      return str;
    }
    var pos = 0;
    var count = 0;
    while (nextIndex > -1 && (maxCount === -1 || count < maxCount)) {
      res += str.substring(pos, nextIndex) + new_;
      pos = nextIndex + old.length;
      count++;
      nextIndex = str.indexOf(old, pos);
    }
    if (pos < str.length) {
      res += str.substring(pos);
    }
    return r.copySafeness(originalStr, res);
  }
  _exports.replace = replace;
  function reverse(val) {
    var arr;
    if (lib.isString(val)) {
      arr = list(val);
    } else {
      arr = lib.map(val, function(v) {
        return v;
      });
    }
    arr.reverse();
    if (lib.isString(val)) {
      return r.copySafeness(val, arr.join(""));
    }
    return arr;
  }
  _exports.reverse = reverse;
  function round(val, precision, method) {
    precision = precision || 0;
    var factor = Math.pow(10, precision);
    var rounder;
    if (method === "ceil") {
      rounder = Math.ceil;
    } else if (method === "floor") {
      rounder = Math.floor;
    } else {
      rounder = Math.round;
    }
    return rounder(val * factor) / factor;
  }
  _exports.round = round;
  function slice(arr, slices, fillWith) {
    var sliceLength = Math.floor(arr.length / slices);
    var extra = arr.length % slices;
    var res = [];
    var offset = 0;
    for (var i = 0;i < slices; i++) {
      var start = offset + i * sliceLength;
      if (i < extra) {
        offset++;
      }
      var end = offset + (i + 1) * sliceLength;
      var currSlice = arr.slice(start, end);
      if (fillWith && i >= extra) {
        currSlice.push(fillWith);
      }
      res.push(currSlice);
    }
    return res;
  }
  _exports.slice = slice;
  function sum(arr, attr, start) {
    if (start === undefined) {
      start = 0;
    }
    if (attr) {
      arr = lib.map(arr, function(v) {
        return v[attr];
      });
    }
    return start + arr.reduce(function(a, b) {
      return a + b;
    }, 0);
  }
  _exports.sum = sum;
  _exports.sort = r.makeMacro(["value", "reverse", "case_sensitive", "attribute"], [], function sortFilter(arr, reversed, caseSens, attr) {
    var _this = this;
    var array = lib.map(arr, function(v) {
      return v;
    });
    var getAttribute = lib.getAttrGetter(attr);
    array.sort(function(a, b) {
      var x = attr ? getAttribute(a) : a;
      var y = attr ? getAttribute(b) : b;
      if (_this.env.opts.throwOnUndefined && attr && (x === undefined || y === undefined)) {
        throw new TypeError('sort: attribute "' + attr + '" resolved to undefined');
      }
      if (!caseSens && lib.isString(x) && lib.isString(y)) {
        x = x.toLowerCase();
        y = y.toLowerCase();
      }
      if (x < y) {
        return reversed ? 1 : -1;
      } else if (x > y) {
        return reversed ? -1 : 1;
      } else {
        return 0;
      }
    });
    return array;
  });
  function string(obj) {
    return r.copySafeness(obj, obj);
  }
  _exports.string = string;
  function striptags(input, preserveLinebreaks) {
    input = normalize(input, "");
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>|<!--[\s\S]*?-->/gi;
    var trimmedInput = trim(input.replace(tags, ""));
    var res = "";
    if (preserveLinebreaks) {
      res = trimmedInput.replace(/^ +| +$/gm, "").replace(/ +/g, " ").replace(/(\r\n)/g, `
`).replace(/\n\n\n+/g, `

`);
    } else {
      res = trimmedInput.replace(/\s+/gi, " ");
    }
    return r.copySafeness(input, res);
  }
  _exports.striptags = striptags;
  function title(str) {
    str = normalize(str, "");
    var words = str.split(" ").map(function(word) {
      return capitalize(word);
    });
    return r.copySafeness(str, words.join(" "));
  }
  _exports.title = title;
  function trim(str) {
    return r.copySafeness(str, str.replace(/^\s*|\s*$/g, ""));
  }
  _exports.trim = trim;
  function truncate(input, length, killwords, end) {
    var orig = input;
    input = normalize(input, "");
    length = length || 255;
    if (input.length <= length) {
      return input;
    }
    if (killwords) {
      input = input.substring(0, length);
    } else {
      var idx = input.lastIndexOf(" ", length);
      if (idx === -1) {
        idx = length;
      }
      input = input.substring(0, idx);
    }
    input += end !== undefined && end !== null ? end : "...";
    return r.copySafeness(orig, input);
  }
  _exports.truncate = truncate;
  function upper(str) {
    str = normalize(str, "");
    return str.toUpperCase();
  }
  _exports.upper = upper;
  function urlencode(obj) {
    var enc = encodeURIComponent;
    if (lib.isString(obj)) {
      return enc(obj);
    } else {
      var keyvals = lib.isArray(obj) ? obj : lib._entries(obj);
      return keyvals.map(function(_ref2) {
        var k = _ref2[0], v = _ref2[1];
        return enc(k) + "=" + enc(v);
      }).join("&");
    }
  }
  _exports.urlencode = urlencode;
  var puncRe = /^(?:\(|<|&lt;)?(.*?)(?:\.|,|\)|\n|&gt;)?$/;
  var emailRe = /^[\w.!#$%&'*+\-\/=?\^`{|}~]+@[a-z\d\-]+(\.[a-z\d\-]+)+$/i;
  var httpHttpsRe = /^https?:\/\/.*$/;
  var wwwRe = /^www\./;
  var tldRe = /\.(?:org|net|com)(?:\:|\/|$)/;
  function urlize(str, length, nofollow) {
    if (isNaN2(length)) {
      length = Infinity;
    }
    var noFollowAttr = nofollow === true ? ' rel="nofollow"' : "";
    var words = str.split(/(\s+)/).filter(function(word) {
      return word && word.length;
    }).map(function(word) {
      var matches = word.match(puncRe);
      var possibleUrl = matches ? matches[1] : word;
      var shortUrl = possibleUrl.substr(0, length);
      if (httpHttpsRe.test(possibleUrl)) {
        return '<a href="' + possibleUrl + '"' + noFollowAttr + ">" + shortUrl + "</a>";
      }
      if (wwwRe.test(possibleUrl)) {
        return '<a href="http://' + possibleUrl + '"' + noFollowAttr + ">" + shortUrl + "</a>";
      }
      if (emailRe.test(possibleUrl)) {
        return '<a href="mailto:' + possibleUrl + '">' + possibleUrl + "</a>";
      }
      if (tldRe.test(possibleUrl)) {
        return '<a href="http://' + possibleUrl + '"' + noFollowAttr + ">" + shortUrl + "</a>";
      }
      return word;
    });
    return words.join("");
  }
  _exports.urlize = urlize;
  function wordcount(str) {
    str = normalize(str, "");
    var words = str ? str.match(/\w+/g) : null;
    return words ? words.length : null;
  }
  _exports.wordcount = wordcount;
  function float(val, def) {
    var res = parseFloat(val);
    return isNaN2(res) ? def : res;
  }
  _exports.float = float;
  var intFilter = r.makeMacro(["value", "default", "base"], [], function doInt(value, defaultValue, base) {
    if (base === undefined) {
      base = 10;
    }
    var res = parseInt(value, base);
    return isNaN2(res) ? defaultValue : res;
  });
  _exports.int = intFilter;
  _exports.d = _exports.default;
  _exports.e = _exports.escape;
});

// node_modules/nunjucks/src/loader.js
var require_loader = __commonJS((exports, module) => {
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o2, p2) {
      o2.__proto__ = p2;
      return o2;
    };
    return _setPrototypeOf(o, p);
  }
  var path = __require("path");
  var _require = require_object();
  var EmitterObj = _require.EmitterObj;
  module.exports = /* @__PURE__ */ function(_EmitterObj) {
    _inheritsLoose(Loader, _EmitterObj);
    function Loader() {
      return _EmitterObj.apply(this, arguments) || this;
    }
    var _proto = Loader.prototype;
    _proto.resolve = function resolve(from, to) {
      return path.resolve(path.dirname(from), to);
    };
    _proto.isRelative = function isRelative(filename) {
      return filename.indexOf("./") === 0 || filename.indexOf("../") === 0;
    };
    return Loader;
  }(EmitterObj);
});

// node_modules/nunjucks/src/precompiled-loader.js
var require_precompiled_loader = __commonJS((exports, module) => {
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o2, p2) {
      o2.__proto__ = p2;
      return o2;
    };
    return _setPrototypeOf(o, p);
  }
  var Loader = require_loader();
  var PrecompiledLoader = /* @__PURE__ */ function(_Loader) {
    _inheritsLoose(PrecompiledLoader2, _Loader);
    function PrecompiledLoader2(compiledTemplates) {
      var _this;
      _this = _Loader.call(this) || this;
      _this.precompiled = compiledTemplates || {};
      return _this;
    }
    var _proto = PrecompiledLoader2.prototype;
    _proto.getSource = function getSource(name) {
      if (this.precompiled[name]) {
        return {
          src: {
            type: "code",
            obj: this.precompiled[name]
          },
          path: name
        };
      }
      return null;
    };
    return PrecompiledLoader2;
  }(Loader);
  module.exports = {
    PrecompiledLoader
  };
});

// node_modules/nunjucks/src/node-loaders.js
var require_node_loaders = __commonJS((exports, module) => {
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o2, p2) {
      o2.__proto__ = p2;
      return o2;
    };
    return _setPrototypeOf(o, p);
  }
  var fs = __require("fs");
  var path = __require("path");
  var Loader = require_loader();
  var _require = require_precompiled_loader();
  var PrecompiledLoader = _require.PrecompiledLoader;
  var chokidar;
  var FileSystemLoader = /* @__PURE__ */ function(_Loader) {
    _inheritsLoose(FileSystemLoader2, _Loader);
    function FileSystemLoader2(searchPaths, opts) {
      var _this;
      _this = _Loader.call(this) || this;
      if (typeof opts === "boolean") {
        console.log("[nunjucks] Warning: you passed a boolean as the second " + "argument to FileSystemLoader, but it now takes an options " + "object. See http://mozilla.github.io/nunjucks/api.html#filesystemloader");
      }
      opts = opts || {};
      _this.pathsToNames = {};
      _this.noCache = !!opts.noCache;
      if (searchPaths) {
        searchPaths = Array.isArray(searchPaths) ? searchPaths : [searchPaths];
        _this.searchPaths = searchPaths.map(path.normalize);
      } else {
        _this.searchPaths = ["."];
      }
      if (opts.watch) {
        try {
          chokidar = (()=>{throw new Error("Cannot require module "+"chokidar");})();
        } catch (e) {
          throw new Error("watch requires chokidar to be installed");
        }
        var paths = _this.searchPaths.filter(fs.existsSync);
        var watcher = chokidar.watch(paths);
        watcher.on("all", function(event, fullname) {
          fullname = path.resolve(fullname);
          if (event === "change" && fullname in _this.pathsToNames) {
            _this.emit("update", _this.pathsToNames[fullname], fullname);
          }
        });
        watcher.on("error", function(error) {
          console.log("Watcher error: " + error);
        });
      }
      return _this;
    }
    var _proto = FileSystemLoader2.prototype;
    _proto.getSource = function getSource(name) {
      var fullpath = null;
      var paths = this.searchPaths;
      for (var i = 0;i < paths.length; i++) {
        var basePath = path.resolve(paths[i]);
        var p = path.resolve(paths[i], name);
        if (p.indexOf(basePath) === 0 && fs.existsSync(p)) {
          fullpath = p;
          break;
        }
      }
      if (!fullpath) {
        return null;
      }
      this.pathsToNames[fullpath] = name;
      var source = {
        src: fs.readFileSync(fullpath, "utf-8"),
        path: fullpath,
        noCache: this.noCache
      };
      this.emit("load", name, source);
      return source;
    };
    return FileSystemLoader2;
  }(Loader);
  var NodeResolveLoader = /* @__PURE__ */ function(_Loader2) {
    _inheritsLoose(NodeResolveLoader2, _Loader2);
    function NodeResolveLoader2(opts) {
      var _this2;
      _this2 = _Loader2.call(this) || this;
      opts = opts || {};
      _this2.pathsToNames = {};
      _this2.noCache = !!opts.noCache;
      if (opts.watch) {
        try {
          chokidar = (()=>{throw new Error("Cannot require module "+"chokidar");})();
        } catch (e) {
          throw new Error("watch requires chokidar to be installed");
        }
        _this2.watcher = chokidar.watch();
        _this2.watcher.on("change", function(fullname) {
          _this2.emit("update", _this2.pathsToNames[fullname], fullname);
        });
        _this2.watcher.on("error", function(error) {
          console.log("Watcher error: " + error);
        });
        _this2.on("load", function(name, source) {
          _this2.watcher.add(source.path);
        });
      }
      return _this2;
    }
    var _proto2 = NodeResolveLoader2.prototype;
    _proto2.getSource = function getSource(name) {
      if (/^\.?\.?(\/|\\)/.test(name)) {
        return null;
      }
      if (/^[A-Z]:/.test(name)) {
        return null;
      }
      var fullpath;
      try {
        fullpath = __require.resolve(name);
      } catch (e) {
        return null;
      }
      this.pathsToNames[fullpath] = name;
      var source = {
        src: fs.readFileSync(fullpath, "utf-8"),
        path: fullpath,
        noCache: this.noCache
      };
      this.emit("load", name, source);
      return source;
    };
    return NodeResolveLoader2;
  }(Loader);
  module.exports = {
    FileSystemLoader,
    PrecompiledLoader,
    NodeResolveLoader
  };
});

// node_modules/nunjucks/src/tests.js
var require_tests = __commonJS((exports) => {
  var SafeString = require_runtime().SafeString;
  function callable(value) {
    return typeof value === "function";
  }
  exports.callable = callable;
  function defined(value) {
    return value !== undefined;
  }
  exports.defined = defined;
  function divisibleby(one, two) {
    return one % two === 0;
  }
  exports.divisibleby = divisibleby;
  function escaped(value) {
    return value instanceof SafeString;
  }
  exports.escaped = escaped;
  function equalto(one, two) {
    return one === two;
  }
  exports.equalto = equalto;
  exports.eq = exports.equalto;
  exports.sameas = exports.equalto;
  function even(value) {
    return value % 2 === 0;
  }
  exports.even = even;
  function falsy(value) {
    return !value;
  }
  exports.falsy = falsy;
  function ge(one, two) {
    return one >= two;
  }
  exports.ge = ge;
  function greaterthan(one, two) {
    return one > two;
  }
  exports.greaterthan = greaterthan;
  exports.gt = exports.greaterthan;
  function le(one, two) {
    return one <= two;
  }
  exports.le = le;
  function lessthan(one, two) {
    return one < two;
  }
  exports.lessthan = lessthan;
  exports.lt = exports.lessthan;
  function lower(value) {
    return value.toLowerCase() === value;
  }
  exports.lower = lower;
  function ne(one, two) {
    return one !== two;
  }
  exports.ne = ne;
  function nullTest(value) {
    return value === null;
  }
  exports.null = nullTest;
  function number(value) {
    return typeof value === "number";
  }
  exports.number = number;
  function odd(value) {
    return value % 2 === 1;
  }
  exports.odd = odd;
  function string(value) {
    return typeof value === "string";
  }
  exports.string = string;
  function truthy(value) {
    return !!value;
  }
  exports.truthy = truthy;
  function undefinedTest(value) {
    return value === undefined;
  }
  exports.undefined = undefinedTest;
  function upper(value) {
    return value.toUpperCase() === value;
  }
  exports.upper = upper;
  function iterable(value) {
    if (typeof Symbol !== "undefined") {
      return !!value[Symbol.iterator];
    } else {
      return Array.isArray(value) || typeof value === "string";
    }
  }
  exports.iterable = iterable;
  function mapping(value) {
    var bool = value !== null && value !== undefined && typeof value === "object" && !Array.isArray(value);
    if (Set) {
      return bool && !(value instanceof Set);
    } else {
      return bool;
    }
  }
  exports.mapping = mapping;
});

// node_modules/nunjucks/src/globals.js
var require_globals = __commonJS((exports, module) => {
  function _cycler(items) {
    var index = -1;
    return {
      current: null,
      reset: function reset() {
        index = -1;
        this.current = null;
      },
      next: function next() {
        index++;
        if (index >= items.length) {
          index = 0;
        }
        this.current = items[index];
        return this.current;
      }
    };
  }
  function _joiner(sep) {
    sep = sep || ",";
    var first = true;
    return function() {
      var val = first ? "" : sep;
      first = false;
      return val;
    };
  }
  function globals() {
    return {
      range: function range(start, stop, step) {
        if (typeof stop === "undefined") {
          stop = start;
          start = 0;
          step = 1;
        } else if (!step) {
          step = 1;
        }
        var arr = [];
        if (step > 0) {
          for (var i = start;i < stop; i += step) {
            arr.push(i);
          }
        } else {
          for (var _i = start;_i > stop; _i += step) {
            arr.push(_i);
          }
        }
        return arr;
      },
      cycler: function cycler() {
        return _cycler(Array.prototype.slice.call(arguments));
      },
      joiner: function joiner(sep) {
        return _joiner(sep);
      }
    };
  }
  module.exports = globals;
});

// node_modules/nunjucks/src/express-app.js
var require_express_app = __commonJS((exports, module) => {
  var path = __require("path");
  module.exports = function express(env, app) {
    function NunjucksView(name, opts) {
      this.name = name;
      this.path = name;
      this.defaultEngine = opts.defaultEngine;
      this.ext = path.extname(name);
      if (!this.ext && !this.defaultEngine) {
        throw new Error("No default engine was specified and no extension was provided.");
      }
      if (!this.ext) {
        this.name += this.ext = (this.defaultEngine[0] !== "." ? "." : "") + this.defaultEngine;
      }
    }
    NunjucksView.prototype.render = function render(opts, cb) {
      env.render(this.name, opts, cb);
    };
    app.set("view", NunjucksView);
    app.set("nunjucksEnv", env);
    return env;
  };
});

// node_modules/nunjucks/src/environment.js
var require_environment = __commonJS((exports, module) => {
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o2, p2) {
      o2.__proto__ = p2;
      return o2;
    };
    return _setPrototypeOf(o, p);
  }
  var asap = require_asap();
  var _waterfall = require_a_sync_waterfall();
  var lib = require_lib();
  var compiler = require_compiler();
  var filters = require_filters();
  var _require = require_node_loaders();
  var FileSystemLoader = _require.FileSystemLoader;
  var WebLoader = _require.WebLoader;
  var PrecompiledLoader = _require.PrecompiledLoader;
  var tests = require_tests();
  var globals = require_globals();
  var _require2 = require_object();
  var Obj = _require2.Obj;
  var EmitterObj = _require2.EmitterObj;
  var globalRuntime = require_runtime();
  var handleError = globalRuntime.handleError;
  var Frame = globalRuntime.Frame;
  var expressApp = require_express_app();
  function callbackAsap(cb, err, res) {
    asap(function() {
      cb(err, res);
    });
  }
  var noopTmplSrc = {
    type: "code",
    obj: {
      root: function root(env, context, frame, runtime, cb) {
        try {
          cb(null, "");
        } catch (e) {
          cb(handleError(e, null, null));
        }
      }
    }
  };
  var Environment = /* @__PURE__ */ function(_EmitterObj) {
    _inheritsLoose(Environment2, _EmitterObj);
    function Environment2() {
      return _EmitterObj.apply(this, arguments) || this;
    }
    var _proto = Environment2.prototype;
    _proto.init = function init(loaders, opts) {
      var _this = this;
      opts = this.opts = opts || {};
      this.opts.dev = !!opts.dev;
      this.opts.autoescape = opts.autoescape != null ? opts.autoescape : true;
      this.opts.throwOnUndefined = !!opts.throwOnUndefined;
      this.opts.trimBlocks = !!opts.trimBlocks;
      this.opts.lstripBlocks = !!opts.lstripBlocks;
      this.loaders = [];
      if (!loaders) {
        if (FileSystemLoader) {
          this.loaders = [new FileSystemLoader("views")];
        } else if (WebLoader) {
          this.loaders = [new WebLoader("/views")];
        }
      } else {
        this.loaders = lib.isArray(loaders) ? loaders : [loaders];
      }
      if (typeof window !== "undefined" && window.nunjucksPrecompiled) {
        this.loaders.unshift(new PrecompiledLoader(window.nunjucksPrecompiled));
      }
      this._initLoaders();
      this.globals = globals();
      this.filters = {};
      this.tests = {};
      this.asyncFilters = [];
      this.extensions = {};
      this.extensionsList = [];
      lib._entries(filters).forEach(function(_ref) {
        var name = _ref[0], filter = _ref[1];
        return _this.addFilter(name, filter);
      });
      lib._entries(tests).forEach(function(_ref2) {
        var name = _ref2[0], test = _ref2[1];
        return _this.addTest(name, test);
      });
    };
    _proto._initLoaders = function _initLoaders() {
      var _this2 = this;
      this.loaders.forEach(function(loader) {
        loader.cache = {};
        if (typeof loader.on === "function") {
          loader.on("update", function(name, fullname) {
            loader.cache[name] = null;
            _this2.emit("update", name, fullname, loader);
          });
          loader.on("load", function(name, source) {
            _this2.emit("load", name, source, loader);
          });
        }
      });
    };
    _proto.invalidateCache = function invalidateCache() {
      this.loaders.forEach(function(loader) {
        loader.cache = {};
      });
    };
    _proto.addExtension = function addExtension(name, extension) {
      extension.__name = name;
      this.extensions[name] = extension;
      this.extensionsList.push(extension);
      return this;
    };
    _proto.removeExtension = function removeExtension(name) {
      var extension = this.getExtension(name);
      if (!extension) {
        return;
      }
      this.extensionsList = lib.without(this.extensionsList, extension);
      delete this.extensions[name];
    };
    _proto.getExtension = function getExtension(name) {
      return this.extensions[name];
    };
    _proto.hasExtension = function hasExtension(name) {
      return !!this.extensions[name];
    };
    _proto.addGlobal = function addGlobal(name, value) {
      this.globals[name] = value;
      return this;
    };
    _proto.getGlobal = function getGlobal(name) {
      if (typeof this.globals[name] === "undefined") {
        throw new Error("global not found: " + name);
      }
      return this.globals[name];
    };
    _proto.addFilter = function addFilter(name, func, async) {
      var wrapped = func;
      if (async) {
        this.asyncFilters.push(name);
      }
      this.filters[name] = wrapped;
      return this;
    };
    _proto.getFilter = function getFilter(name) {
      if (!this.filters[name]) {
        throw new Error("filter not found: " + name);
      }
      return this.filters[name];
    };
    _proto.addTest = function addTest(name, func) {
      this.tests[name] = func;
      return this;
    };
    _proto.getTest = function getTest(name) {
      if (!this.tests[name]) {
        throw new Error("test not found: " + name);
      }
      return this.tests[name];
    };
    _proto.resolveTemplate = function resolveTemplate(loader, parentName, filename) {
      var isRelative = loader.isRelative && parentName ? loader.isRelative(filename) : false;
      return isRelative && loader.resolve ? loader.resolve(parentName, filename) : filename;
    };
    _proto.getTemplate = function getTemplate(name, eagerCompile, parentName, ignoreMissing, cb) {
      var _this3 = this;
      var that = this;
      var tmpl = null;
      if (name && name.raw) {
        name = name.raw;
      }
      if (lib.isFunction(parentName)) {
        cb = parentName;
        parentName = null;
        eagerCompile = eagerCompile || false;
      }
      if (lib.isFunction(eagerCompile)) {
        cb = eagerCompile;
        eagerCompile = false;
      }
      if (name instanceof Template) {
        tmpl = name;
      } else if (typeof name !== "string") {
        throw new Error("template names must be a string: " + name);
      } else {
        for (var i = 0;i < this.loaders.length; i++) {
          var loader = this.loaders[i];
          tmpl = loader.cache[this.resolveTemplate(loader, parentName, name)];
          if (tmpl) {
            break;
          }
        }
      }
      if (tmpl) {
        if (eagerCompile) {
          tmpl.compile();
        }
        if (cb) {
          cb(null, tmpl);
          return;
        } else {
          return tmpl;
        }
      }
      var syncResult;
      var createTemplate = function createTemplate(err, info) {
        if (!info && !err && !ignoreMissing) {
          err = new Error("template not found: " + name);
        }
        if (err) {
          if (cb) {
            cb(err);
            return;
          } else {
            throw err;
          }
        }
        var newTmpl;
        if (!info) {
          newTmpl = new Template(noopTmplSrc, _this3, "", eagerCompile);
        } else {
          newTmpl = new Template(info.src, _this3, info.path, eagerCompile);
          if (!info.noCache) {
            info.loader.cache[name] = newTmpl;
          }
        }
        if (cb) {
          cb(null, newTmpl);
        } else {
          syncResult = newTmpl;
        }
      };
      lib.asyncIter(this.loaders, function(loader2, i2, next, done) {
        function handle(err, src) {
          if (err) {
            done(err);
          } else if (src) {
            src.loader = loader2;
            done(null, src);
          } else {
            next();
          }
        }
        name = that.resolveTemplate(loader2, parentName, name);
        if (loader2.async) {
          loader2.getSource(name, handle);
        } else {
          handle(null, loader2.getSource(name));
        }
      }, createTemplate);
      return syncResult;
    };
    _proto.express = function express(app) {
      return expressApp(this, app);
    };
    _proto.render = function render(name, ctx, cb) {
      if (lib.isFunction(ctx)) {
        cb = ctx;
        ctx = null;
      }
      var syncResult = null;
      this.getTemplate(name, function(err, tmpl) {
        if (err && cb) {
          callbackAsap(cb, err);
        } else if (err) {
          throw err;
        } else {
          syncResult = tmpl.render(ctx, cb);
        }
      });
      return syncResult;
    };
    _proto.renderString = function renderString(src, ctx, opts, cb) {
      if (lib.isFunction(opts)) {
        cb = opts;
        opts = {};
      }
      opts = opts || {};
      var tmpl = new Template(src, this, opts.path);
      return tmpl.render(ctx, cb);
    };
    _proto.waterfall = function waterfall(tasks, callback, forceAsync) {
      return _waterfall(tasks, callback, forceAsync);
    };
    return Environment2;
  }(EmitterObj);
  var Context = /* @__PURE__ */ function(_Obj) {
    _inheritsLoose(Context2, _Obj);
    function Context2() {
      return _Obj.apply(this, arguments) || this;
    }
    var _proto2 = Context2.prototype;
    _proto2.init = function init(ctx, blocks, env) {
      var _this4 = this;
      this.env = env || new Environment;
      this.ctx = lib.extend({}, ctx);
      this.blocks = {};
      this.exported = [];
      lib.keys(blocks).forEach(function(name) {
        _this4.addBlock(name, blocks[name]);
      });
    };
    _proto2.lookup = function lookup(name) {
      if (name in this.env.globals && !(name in this.ctx)) {
        return this.env.globals[name];
      } else {
        return this.ctx[name];
      }
    };
    _proto2.setVariable = function setVariable(name, val) {
      this.ctx[name] = val;
    };
    _proto2.getVariables = function getVariables() {
      return this.ctx;
    };
    _proto2.addBlock = function addBlock(name, block) {
      this.blocks[name] = this.blocks[name] || [];
      this.blocks[name].push(block);
      return this;
    };
    _proto2.getBlock = function getBlock(name) {
      if (!this.blocks[name]) {
        throw new Error('unknown block "' + name + '"');
      }
      return this.blocks[name][0];
    };
    _proto2.getSuper = function getSuper(env, name, block, frame, runtime, cb) {
      var idx = lib.indexOf(this.blocks[name] || [], block);
      var blk = this.blocks[name][idx + 1];
      var context = this;
      if (idx === -1 || !blk) {
        throw new Error('no super block available for "' + name + '"');
      }
      blk(env, context, frame, runtime, cb);
    };
    _proto2.addExport = function addExport(name) {
      this.exported.push(name);
    };
    _proto2.getExported = function getExported() {
      var _this5 = this;
      var exported = {};
      this.exported.forEach(function(name) {
        exported[name] = _this5.ctx[name];
      });
      return exported;
    };
    return Context2;
  }(Obj);
  var Template = /* @__PURE__ */ function(_Obj2) {
    _inheritsLoose(Template2, _Obj2);
    function Template2() {
      return _Obj2.apply(this, arguments) || this;
    }
    var _proto3 = Template2.prototype;
    _proto3.init = function init(src, env, path, eagerCompile) {
      this.env = env || new Environment;
      if (lib.isObject(src)) {
        switch (src.type) {
          case "code":
            this.tmplProps = src.obj;
            break;
          case "string":
            this.tmplStr = src.obj;
            break;
          default:
            throw new Error("Unexpected template object type " + src.type + "; expected 'code', or 'string'");
        }
      } else if (lib.isString(src)) {
        this.tmplStr = src;
      } else {
        throw new Error("src must be a string or an object describing the source");
      }
      this.path = path;
      if (eagerCompile) {
        try {
          this._compile();
        } catch (err) {
          throw lib._prettifyError(this.path, this.env.opts.dev, err);
        }
      } else {
        this.compiled = false;
      }
    };
    _proto3.render = function render(ctx, parentFrame, cb) {
      var _this6 = this;
      if (typeof ctx === "function") {
        cb = ctx;
        ctx = {};
      } else if (typeof parentFrame === "function") {
        cb = parentFrame;
        parentFrame = null;
      }
      var forceAsync = !parentFrame;
      try {
        this.compile();
      } catch (e) {
        var err = lib._prettifyError(this.path, this.env.opts.dev, e);
        if (cb) {
          return callbackAsap(cb, err);
        } else {
          throw err;
        }
      }
      var context = new Context(ctx || {}, this.blocks, this.env);
      var frame = parentFrame ? parentFrame.push(true) : new Frame;
      frame.topLevel = true;
      var syncResult = null;
      var didError = false;
      this.rootRenderFunc(this.env, context, frame, globalRuntime, function(err2, res) {
        if (didError && cb && typeof res !== "undefined") {
          return;
        }
        if (err2) {
          err2 = lib._prettifyError(_this6.path, _this6.env.opts.dev, err2);
          didError = true;
        }
        if (cb) {
          if (forceAsync) {
            callbackAsap(cb, err2, res);
          } else {
            cb(err2, res);
          }
        } else {
          if (err2) {
            throw err2;
          }
          syncResult = res;
        }
      });
      return syncResult;
    };
    _proto3.getExported = function getExported(ctx, parentFrame, cb) {
      if (typeof ctx === "function") {
        cb = ctx;
        ctx = {};
      }
      if (typeof parentFrame === "function") {
        cb = parentFrame;
        parentFrame = null;
      }
      try {
        this.compile();
      } catch (e) {
        if (cb) {
          return cb(e);
        } else {
          throw e;
        }
      }
      var frame = parentFrame ? parentFrame.push() : new Frame;
      frame.topLevel = true;
      var context = new Context(ctx || {}, this.blocks, this.env);
      this.rootRenderFunc(this.env, context, frame, globalRuntime, function(err) {
        if (err) {
          cb(err, null);
        } else {
          cb(null, context.getExported());
        }
      });
    };
    _proto3.compile = function compile() {
      if (!this.compiled) {
        this._compile();
      }
    };
    _proto3._compile = function _compile() {
      var props;
      if (this.tmplProps) {
        props = this.tmplProps;
      } else {
        var source = compiler.compile(this.tmplStr, this.env.asyncFilters, this.env.extensionsList, this.path, this.env.opts);
        var func = new Function(source);
        props = func();
      }
      this.blocks = this._getBlocks(props);
      this.rootRenderFunc = props.root;
      this.compiled = true;
    };
    _proto3._getBlocks = function _getBlocks(props) {
      var blocks = {};
      lib.keys(props).forEach(function(k) {
        if (k.slice(0, 2) === "b_") {
          blocks[k.slice(2)] = props[k];
        }
      });
      return blocks;
    };
    return Template2;
  }(Obj);
  module.exports = {
    Environment,
    Template
  };
});

// node_modules/nunjucks/src/precompile-global.js
var require_precompile_global = __commonJS((exports, module) => {
  function precompileGlobal(templates, opts) {
    var out = "";
    opts = opts || {};
    for (var i = 0;i < templates.length; i++) {
      var name = JSON.stringify(templates[i].name);
      var template = templates[i].template;
      out += "(function() {" + "(window.nunjucksPrecompiled = window.nunjucksPrecompiled || {})" + "[" + name + `] = (function() {
` + template + `
})();
`;
      if (opts.asFunction) {
        out += "return function(ctx, cb) { return nunjucks.render(" + name + `, ctx, cb); }
`;
      }
      out += `})();
`;
    }
    return out;
  }
  module.exports = precompileGlobal;
});

// node_modules/nunjucks/src/precompile.js
var require_precompile = __commonJS((exports, module) => {
  var fs = __require("fs");
  var path = __require("path");
  var _require = require_lib();
  var _prettifyError = _require._prettifyError;
  var compiler = require_compiler();
  var _require2 = require_environment();
  var Environment = _require2.Environment;
  var precompileGlobal = require_precompile_global();
  function match(filename, patterns) {
    if (!Array.isArray(patterns)) {
      return false;
    }
    return patterns.some(function(pattern) {
      return filename.match(pattern);
    });
  }
  function precompileString(str, opts) {
    opts = opts || {};
    opts.isString = true;
    var env = opts.env || new Environment([]);
    var wrapper = opts.wrapper || precompileGlobal;
    if (!opts.name) {
      throw new Error('the "name" option is required when compiling a string');
    }
    return wrapper([_precompile(str, opts.name, env)], opts);
  }
  function precompile(input, opts) {
    opts = opts || {};
    var env = opts.env || new Environment([]);
    var wrapper = opts.wrapper || precompileGlobal;
    if (opts.isString) {
      return precompileString(input, opts);
    }
    var pathStats = fs.existsSync(input) && fs.statSync(input);
    var precompiled = [];
    var templates = [];
    function addTemplates(dir) {
      fs.readdirSync(dir).forEach(function(file) {
        var filepath = path.join(dir, file);
        var subpath = filepath.substr(path.join(input, "/").length);
        var stat = fs.statSync(filepath);
        if (stat && stat.isDirectory()) {
          subpath += "/";
          if (!match(subpath, opts.exclude)) {
            addTemplates(filepath);
          }
        } else if (match(subpath, opts.include)) {
          templates.push(filepath);
        }
      });
    }
    if (pathStats.isFile()) {
      precompiled.push(_precompile(fs.readFileSync(input, "utf-8"), opts.name || input, env));
    } else if (pathStats.isDirectory()) {
      addTemplates(input);
      for (var i = 0;i < templates.length; i++) {
        var name = templates[i].replace(path.join(input, "/"), "");
        try {
          precompiled.push(_precompile(fs.readFileSync(templates[i], "utf-8"), name, env));
        } catch (e) {
          if (opts.force) {
            console.error(e);
          } else {
            throw e;
          }
        }
      }
    }
    return wrapper(precompiled, opts);
  }
  function _precompile(str, name, env) {
    env = env || new Environment([]);
    var asyncFilters = env.asyncFilters;
    var extensions = env.extensionsList;
    var template;
    name = name.replace(/\\/g, "/");
    try {
      template = compiler.compile(str, asyncFilters, extensions, name, env.opts);
    } catch (err) {
      throw _prettifyError(name, false, err);
    }
    return {
      name,
      template
    };
  }
  module.exports = {
    precompile,
    precompileString
  };
});

// node_modules/nunjucks/src/jinja-compat.js
var require_jinja_compat = __commonJS((exports, module) => {
  function installCompat() {
    var runtime = this.runtime;
    var lib = this.lib;
    var Compiler = this.compiler.Compiler;
    var Parser = this.parser.Parser;
    var nodes = this.nodes;
    var lexer = this.lexer;
    var orig_contextOrFrameLookup = runtime.contextOrFrameLookup;
    var orig_memberLookup = runtime.memberLookup;
    var orig_Compiler_assertType;
    var orig_Parser_parseAggregate;
    if (Compiler) {
      orig_Compiler_assertType = Compiler.prototype.assertType;
    }
    if (Parser) {
      orig_Parser_parseAggregate = Parser.prototype.parseAggregate;
    }
    function uninstall() {
      runtime.contextOrFrameLookup = orig_contextOrFrameLookup;
      runtime.memberLookup = orig_memberLookup;
      if (Compiler) {
        Compiler.prototype.assertType = orig_Compiler_assertType;
      }
      if (Parser) {
        Parser.prototype.parseAggregate = orig_Parser_parseAggregate;
      }
    }
    runtime.contextOrFrameLookup = function contextOrFrameLookup(context, frame, key) {
      var val = orig_contextOrFrameLookup.apply(this, arguments);
      if (val !== undefined) {
        return val;
      }
      switch (key) {
        case "True":
          return true;
        case "False":
          return false;
        case "None":
          return null;
        default:
          return;
      }
    };
    function getTokensState(tokens) {
      return {
        index: tokens.index,
        lineno: tokens.lineno,
        colno: tokens.colno
      };
    }
    if (process.env.BUILD_TYPE !== "SLIM" && nodes && Compiler && Parser) {
      var Slice = nodes.Node.extend("Slice", {
        fields: ["start", "stop", "step"],
        init: function init(lineno, colno, start, stop, step) {
          start = start || new nodes.Literal(lineno, colno, null);
          stop = stop || new nodes.Literal(lineno, colno, null);
          step = step || new nodes.Literal(lineno, colno, 1);
          this.parent(lineno, colno, start, stop, step);
        }
      });
      Compiler.prototype.assertType = function assertType(node) {
        if (node instanceof Slice) {
          return;
        }
        orig_Compiler_assertType.apply(this, arguments);
      };
      Compiler.prototype.compileSlice = function compileSlice(node, frame) {
        this._emit("(");
        this._compileExpression(node.start, frame);
        this._emit("),(");
        this._compileExpression(node.stop, frame);
        this._emit("),(");
        this._compileExpression(node.step, frame);
        this._emit(")");
      };
      Parser.prototype.parseAggregate = function parseAggregate() {
        var _this = this;
        var origState = getTokensState(this.tokens);
        origState.colno--;
        origState.index--;
        try {
          return orig_Parser_parseAggregate.apply(this);
        } catch (e) {
          var errState = getTokensState(this.tokens);
          var rethrow = function rethrow() {
            lib._assign(_this.tokens, errState);
            return e;
          };
          lib._assign(this.tokens, origState);
          this.peeked = false;
          var tok = this.peekToken();
          if (tok.type !== lexer.TOKEN_LEFT_BRACKET) {
            throw rethrow();
          } else {
            this.nextToken();
          }
          var node = new Slice(tok.lineno, tok.colno);
          var isSlice = false;
          for (var i = 0;i <= node.fields.length; i++) {
            if (this.skip(lexer.TOKEN_RIGHT_BRACKET)) {
              break;
            }
            if (i === node.fields.length) {
              if (isSlice) {
                this.fail("parseSlice: too many slice components", tok.lineno, tok.colno);
              } else {
                break;
              }
            }
            if (this.skip(lexer.TOKEN_COLON)) {
              isSlice = true;
            } else {
              var field = node.fields[i];
              node[field] = this.parseExpression();
              isSlice = this.skip(lexer.TOKEN_COLON) || isSlice;
            }
          }
          if (!isSlice) {
            throw rethrow();
          }
          return new nodes.Array(tok.lineno, tok.colno, [node]);
        }
      };
    }
    function sliceLookup(obj, start, stop, step) {
      obj = obj || [];
      if (start === null) {
        start = step < 0 ? obj.length - 1 : 0;
      }
      if (stop === null) {
        stop = step < 0 ? -1 : obj.length;
      } else if (stop < 0) {
        stop += obj.length;
      }
      if (start < 0) {
        start += obj.length;
      }
      var results = [];
      for (var i = start;; i += step) {
        if (i < 0 || i > obj.length) {
          break;
        }
        if (step > 0 && i >= stop) {
          break;
        }
        if (step < 0 && i <= stop) {
          break;
        }
        results.push(runtime.memberLookup(obj, i));
      }
      return results;
    }
    function hasOwnProp(obj, key) {
      return Object.prototype.hasOwnProperty.call(obj, key);
    }
    var ARRAY_MEMBERS = {
      pop: function pop(index) {
        if (index === undefined) {
          return this.pop();
        }
        if (index >= this.length || index < 0) {
          throw new Error("KeyError");
        }
        return this.splice(index, 1);
      },
      append: function append(element) {
        return this.push(element);
      },
      remove: function remove(element) {
        for (var i = 0;i < this.length; i++) {
          if (this[i] === element) {
            return this.splice(i, 1);
          }
        }
        throw new Error("ValueError");
      },
      count: function count(element) {
        var count = 0;
        for (var i = 0;i < this.length; i++) {
          if (this[i] === element) {
            count++;
          }
        }
        return count;
      },
      index: function index(element) {
        var i;
        if ((i = this.indexOf(element)) === -1) {
          throw new Error("ValueError");
        }
        return i;
      },
      find: function find(element) {
        return this.indexOf(element);
      },
      insert: function insert(index, elem) {
        return this.splice(index, 0, elem);
      }
    };
    var OBJECT_MEMBERS = {
      items: function items() {
        return lib._entries(this);
      },
      values: function values() {
        return lib._values(this);
      },
      keys: function keys() {
        return lib.keys(this);
      },
      get: function get(key, def) {
        var output = this[key];
        if (output === undefined) {
          output = def;
        }
        return output;
      },
      has_key: function has_key(key) {
        return hasOwnProp(this, key);
      },
      pop: function pop(key, def) {
        var output = this[key];
        if (output === undefined && def !== undefined) {
          output = def;
        } else if (output === undefined) {
          throw new Error("KeyError");
        } else {
          delete this[key];
        }
        return output;
      },
      popitem: function popitem() {
        var keys = lib.keys(this);
        if (!keys.length) {
          throw new Error("KeyError");
        }
        var k = keys[0];
        var val = this[k];
        delete this[k];
        return [k, val];
      },
      setdefault: function setdefault(key, def) {
        if (def === undefined) {
          def = null;
        }
        if (!(key in this)) {
          this[key] = def;
        }
        return this[key];
      },
      update: function update(kwargs) {
        lib._assign(this, kwargs);
        return null;
      }
    };
    OBJECT_MEMBERS.iteritems = OBJECT_MEMBERS.items;
    OBJECT_MEMBERS.itervalues = OBJECT_MEMBERS.values;
    OBJECT_MEMBERS.iterkeys = OBJECT_MEMBERS.keys;
    runtime.memberLookup = function memberLookup(obj, val, autoescape) {
      if (arguments.length === 4) {
        return sliceLookup.apply(this, arguments);
      }
      obj = obj || {};
      if (lib.isArray(obj) && hasOwnProp(ARRAY_MEMBERS, val)) {
        return ARRAY_MEMBERS[val].bind(obj);
      }
      if (lib.isObject(obj) && hasOwnProp(OBJECT_MEMBERS, val)) {
        return OBJECT_MEMBERS[val].bind(obj);
      }
      return orig_memberLookup.apply(this, arguments);
    };
    return uninstall;
  }
  module.exports = installCompat;
});

// node_modules/nunjucks/index.js
var require_nunjucks = __commonJS((exports, module) => {
  var lib = require_lib();
  var _require = require_environment();
  var Environment = _require.Environment;
  var Template = _require.Template;
  var Loader = require_loader();
  var loaders = require_node_loaders();
  var precompile = require_precompile();
  var compiler = require_compiler();
  var parser = require_parser();
  var lexer = require_lexer();
  var runtime = require_runtime();
  var nodes = require_nodes();
  var installJinjaCompat = require_jinja_compat();
  var e;
  function configure(templatesPath, opts) {
    opts = opts || {};
    if (lib.isObject(templatesPath)) {
      opts = templatesPath;
      templatesPath = null;
    }
    var TemplateLoader;
    if (loaders.FileSystemLoader) {
      TemplateLoader = new loaders.FileSystemLoader(templatesPath, {
        watch: opts.watch,
        noCache: opts.noCache
      });
    } else if (loaders.WebLoader) {
      TemplateLoader = new loaders.WebLoader(templatesPath, {
        useCache: opts.web && opts.web.useCache,
        async: opts.web && opts.web.async
      });
    }
    e = new Environment(TemplateLoader, opts);
    if (opts && opts.express) {
      e.express(opts.express);
    }
    return e;
  }
  module.exports = {
    Environment,
    Template,
    Loader,
    FileSystemLoader: loaders.FileSystemLoader,
    NodeResolveLoader: loaders.NodeResolveLoader,
    PrecompiledLoader: loaders.PrecompiledLoader,
    WebLoader: loaders.WebLoader,
    compiler,
    parser,
    lexer,
    runtime,
    lib,
    nodes,
    installJinjaCompat,
    configure,
    reset: function reset() {
      e = undefined;
    },
    compile: function compile(src, env, path, eagerCompile) {
      if (!e) {
        configure();
      }
      return new Template(src, env, path, eagerCompile);
    },
    render: function render(name, ctx, cb) {
      if (!e) {
        configure();
      }
      return e.render(name, ctx, cb);
    },
    renderString: function renderString(src, ctx, cb) {
      if (!e) {
        configure();
      }
      return e.renderString(src, ctx, cb);
    },
    precompile: precompile ? precompile.precompile : undefined,
    precompileString: precompile ? precompile.precompileString : undefined
  };
});

// node_modules/secure-json-parse/index.js
var require_secure_json_parse = __commonJS((exports, module) => {
  var hasBuffer = typeof Buffer !== "undefined";
  var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/;
  var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
  function _parse(text, reviver, options) {
    if (options == null) {
      if (reviver !== null && typeof reviver === "object") {
        options = reviver;
        reviver = undefined;
      }
    }
    if (hasBuffer && Buffer.isBuffer(text)) {
      text = text.toString();
    }
    if (text && text.charCodeAt(0) === 65279) {
      text = text.slice(1);
    }
    const obj = JSON.parse(text, reviver);
    if (obj === null || typeof obj !== "object") {
      return obj;
    }
    const protoAction = options && options.protoAction || "error";
    const constructorAction = options && options.constructorAction || "error";
    if (protoAction === "ignore" && constructorAction === "ignore") {
      return obj;
    }
    if (protoAction !== "ignore" && constructorAction !== "ignore") {
      if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) {
        return obj;
      }
    } else if (protoAction !== "ignore" && constructorAction === "ignore") {
      if (suspectProtoRx.test(text) === false) {
        return obj;
      }
    } else {
      if (suspectConstructorRx.test(text) === false) {
        return obj;
      }
    }
    return filter(obj, { protoAction, constructorAction, safe: options && options.safe });
  }
  function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) {
    let next = [obj];
    while (next.length) {
      const nodes = next;
      next = [];
      for (const node of nodes) {
        if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) {
          if (safe === true) {
            return null;
          } else if (protoAction === "error") {
            throw new SyntaxError("Object contains forbidden prototype property");
          }
          delete node.__proto__;
        }
        if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
          if (safe === true) {
            return null;
          } else if (constructorAction === "error") {
            throw new SyntaxError("Object contains forbidden prototype property");
          }
          delete node.constructor;
        }
        for (const key in node) {
          const value = node[key];
          if (value && typeof value === "object") {
            next.push(value);
          }
        }
      }
    }
    return obj;
  }
  function parse(text, reviver, options) {
    const stackTraceLimit = Error.stackTraceLimit;
    Error.stackTraceLimit = 0;
    try {
      return _parse(text, reviver, options);
    } finally {
      Error.stackTraceLimit = stackTraceLimit;
    }
  }
  function safeParse(text, reviver) {
    const stackTraceLimit = Error.stackTraceLimit;
    Error.stackTraceLimit = 0;
    try {
      return _parse(text, reviver, { safe: true });
    } catch (_e) {
      return null;
    } finally {
      Error.stackTraceLimit = stackTraceLimit;
    }
  }
  module.exports = parse;
  module.exports.default = parse;
  module.exports.parse = parse;
  module.exports.safeParse = safeParse;
  module.exports.scan = filter;
});

// node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js
var require_globalThis = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports._globalThis = undefined;
  exports._globalThis = typeof globalThis === "object" ? globalThis : global;
});

// node_modules/@opentelemetry/api/build/src/platform/node/index.js
var require_node = __commonJS((exports) => {
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() {
      return m[k];
    } });
  } : function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    o[k2] = m[k];
  });
  var __exportStar = exports && exports.__exportStar || function(m, exports2) {
    for (var p in m)
      if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
        __createBinding(exports2, m, p);
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  __exportStar(require_globalThis(), exports);
});

// node_modules/@opentelemetry/api/build/src/platform/index.js
var require_platform = __commonJS((exports) => {
  var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() {
      return m[k];
    } });
  } : function(o, m, k, k2) {
    if (k2 === undefined)
      k2 = k;
    o[k2] = m[k];
  });
  var __exportStar = exports && exports.__exportStar || function(m, exports2) {
    for (var p in m)
      if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p))
        __createBinding(exports2, m, p);
  };
  Object.defineProperty(exports, "__esModule", { value: true });
  __exportStar(require_node(), exports);
});

// node_modules/@opentelemetry/api/build/src/version.js
var require_version = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.VERSION = undefined;
  exports.VERSION = "1.9.0";
});

// node_modules/@opentelemetry/api/build/src/internal/semver.js
var require_semver = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.isCompatible = exports._makeCompatibilityCheck = undefined;
  var version_1 = require_version();
  var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
  function _makeCompatibilityCheck(ownVersion) {
    const acceptedVersions = new Set([ownVersion]);
    const rejectedVersions = new Set;
    const myVersionMatch = ownVersion.match(re);
    if (!myVersionMatch) {
      return () => false;
    }
    const ownVersionParsed = {
      major: +myVersionMatch[1],
      minor: +myVersionMatch[2],
      patch: +myVersionMatch[3],
      prerelease: myVersionMatch[4]
    };
    if (ownVersionParsed.prerelease != null) {
      return function isExactmatch(globalVersion) {
        return globalVersion === ownVersion;
      };
    }
    function _reject(v) {
      rejectedVersions.add(v);
      return false;
    }
    function _accept(v) {
      acceptedVersions.add(v);
      return true;
    }
    return function isCompatible(globalVersion) {
      if (acceptedVersions.has(globalVersion)) {
        return true;
      }
      if (rejectedVersions.has(globalVersion)) {
        return false;
      }
      const globalVersionMatch = globalVersion.match(re);
      if (!globalVersionMatch) {
        return _reject(globalVersion);
      }
      const globalVersionParsed = {
        major: +globalVersionMatch[1],
        minor: +globalVersionMatch[2],
        patch: +globalVersionMatch[3],
        prerelease: globalVersionMatch[4]
      };
      if (globalVersionParsed.prerelease != null) {
        return _reject(globalVersion);
      }
      if (ownVersionParsed.major !== globalVersionParsed.major) {
        return _reject(globalVersion);
      }
      if (ownVersionParsed.major === 0) {
        if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
          return _accept(globalVersion);
        }
        return _reject(globalVersion);
      }
      if (ownVersionParsed.minor <= globalVersionParsed.minor) {
        return _accept(globalVersion);
      }
      return _reject(globalVersion);
    };
  }
  exports._makeCompatibilityCheck = _makeCompatibilityCheck;
  exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION);
});

// node_modules/@opentelemetry/api/build/src/internal/global-utils.js
var require_global_utils = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = undefined;
  var platform_1 = require_platform();
  var version_1 = require_version();
  var semver_1 = require_semver();
  var major = version_1.VERSION.split(".")[0];
  var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`);
  var _global = platform_1._globalThis;
  function registerGlobal(type, instance, diag, allowOverride = false) {
    var _a15;
    const api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a15 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a15 !== undefined ? _a15 : {
      version: version_1.VERSION
    };
    if (!allowOverride && api[type]) {
      const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`);
      diag.error(err.stack || err.message);
      return false;
    }
    if (api.version !== version_1.VERSION) {
      const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`);
      diag.error(err.stack || err.message);
      return false;
    }
    api[type] = instance;
    diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`);
    return true;
  }
  exports.registerGlobal = registerGlobal;
  function getGlobal(type) {
    var _a15, _b;
    const globalVersion = (_a15 = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a15 === undefined ? undefined : _a15.version;
    if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) {
      return;
    }
    return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === undefined ? undefined : _b[type];
  }
  exports.getGlobal = getGlobal;
  function unregisterGlobal(type, diag) {
    diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`);
    const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
    if (api) {
      delete api[type];
    }
  }
  exports.unregisterGlobal = unregisterGlobal;
});

// node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js
var require_ComponentLogger = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.DiagComponentLogger = undefined;
  var global_utils_1 = require_global_utils();

  class DiagComponentLogger {
    constructor(props) {
      this._namespace = props.namespace || "DiagComponentLogger";
    }
    debug(...args) {
      return logProxy("debug", this._namespace, args);
    }
    error(...args) {
      return logProxy("error", this._namespace, args);
    }
    info(...args) {
      return logProxy("info", this._namespace, args);
    }
    warn(...args) {
      return logProxy("warn", this._namespace, args);
    }
    verbose(...args) {
      return logProxy("verbose", this._namespace, args);
    }
  }
  exports.DiagComponentLogger = DiagComponentLogger;
  function logProxy(funcName, namespace, args) {
    const logger = (0, global_utils_1.getGlobal)("diag");
    if (!logger) {
      return;
    }
    args.unshift(namespace);
    return logger[funcName](...args);
  }
});

// node_modules/@opentelemetry/api/build/src/diag/types.js
var require_types = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.DiagLogLevel = undefined;
  var DiagLogLevel;
  (function(DiagLogLevel2) {
    DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
    DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR";
    DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN";
    DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO";
    DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG";
    DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE";
    DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
  })(DiagLogLevel = exports.DiagLogLevel || (exports.DiagLogLevel = {}));
});

// node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js
var require_logLevelLogger = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.createLogLevelDiagLogger = undefined;
  var types_1 = require_types();
  function createLogLevelDiagLogger(maxLevel, logger) {
    if (maxLevel < types_1.DiagLogLevel.NONE) {
      maxLevel = types_1.DiagLogLevel.NONE;
    } else if (maxLevel > types_1.DiagLogLevel.ALL) {
      maxLevel = types_1.DiagLogLevel.ALL;
    }
    logger = logger || {};
    function _filterFunc(funcName, theLevel) {
      const theFunc = logger[funcName];
      if (typeof theFunc === "function" && maxLevel >= theLevel) {
        return theFunc.bind(logger);
      }
      return function() {
      };
    }
    return {
      error: _filterFunc("error", types_1.DiagLogLevel.ERROR),
      warn: _filterFunc("warn", types_1.DiagLogLevel.WARN),
      info: _filterFunc("info", types_1.DiagLogLevel.INFO),
      debug: _filterFunc("debug", types_1.DiagLogLevel.DEBUG),
      verbose: _filterFunc("verbose", types_1.DiagLogLevel.VERBOSE)
    };
  }
  exports.createLogLevelDiagLogger = createLogLevelDiagLogger;
});

// node_modules/@opentelemetry/api/build/src/api/diag.js
var require_diag = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.DiagAPI = undefined;
  var ComponentLogger_1 = require_ComponentLogger();
  var logLevelLogger_1 = require_logLevelLogger();
  var types_1 = require_types();
  var global_utils_1 = require_global_utils();
  var API_NAME = "diag";

  class DiagAPI {
    constructor() {
      function _logProxy(funcName) {
        return function(...args) {
          const logger = (0, global_utils_1.getGlobal)("diag");
          if (!logger)
            return;
          return logger[funcName](...args);
        };
      }
      const self = this;
      const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => {
        var _a15, _b, _c;
        if (logger === self) {
          const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
          self.error((_a15 = err.stack) !== null && _a15 !== undefined ? _a15 : err.message);
          return false;
        }
        if (typeof optionsOrLogLevel === "number") {
          optionsOrLogLevel = {
            logLevel: optionsOrLogLevel
          };
        }
        const oldLogger = (0, global_utils_1.getGlobal)("diag");
        const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== undefined ? _b : types_1.DiagLogLevel.INFO, logger);
        if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
          const stack = (_c = new Error().stack) !== null && _c !== undefined ? _c : "<failed to generate stacktrace>";
          oldLogger.warn(`Current logger will be overwritten from ${stack}`);
          newLogger.warn(`Current logger will overwrite one already registered from ${stack}`);
        }
        return (0, global_utils_1.registerGlobal)("diag", newLogger, self, true);
      };
      self.setLogger = setLogger;
      self.disable = () => {
        (0, global_utils_1.unregisterGlobal)(API_NAME, self);
      };
      self.createComponentLogger = (options) => {
        return new ComponentLogger_1.DiagComponentLogger(options);
      };
      self.verbose = _logProxy("verbose");
      self.debug = _logProxy("debug");
      self.info = _logProxy("info");
      self.warn = _logProxy("warn");
      self.error = _logProxy("error");
    }
    static instance() {
      if (!this._instance) {
        this._instance = new DiagAPI;
      }
      return this._instance;
    }
  }
  exports.DiagAPI = DiagAPI;
});

// node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js
var require_baggage_impl = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.BaggageImpl = undefined;

  class BaggageImpl {
    constructor(entries) {
      this._entries = entries ? new Map(entries) : new Map;
    }
    getEntry(key) {
      const entry = this._entries.get(key);
      if (!entry) {
        return;
      }
      return Object.assign({}, entry);
    }
    getAllEntries() {
      return Array.from(this._entries.entries()).map(([k, v]) => [k, v]);
    }
    setEntry(key, entry) {
      const newBaggage = new BaggageImpl(this._entries);
      newBaggage._entries.set(key, entry);
      return newBaggage;
    }
    removeEntry(key) {
      const newBaggage = new BaggageImpl(this._entries);
      newBaggage._entries.delete(key);
      return newBaggage;
    }
    removeEntries(...keys) {
      const newBaggage = new BaggageImpl(this._entries);
      for (const key of keys) {
        newBaggage._entries.delete(key);
      }
      return newBaggage;
    }
    clear() {
      return new BaggageImpl;
    }
  }
  exports.BaggageImpl = BaggageImpl;
});

// node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js
var require_symbol = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.baggageEntryMetadataSymbol = undefined;
  exports.baggageEntryMetadataSymbol = Symbol("BaggageEntryMetadata");
});

// node_modules/@opentelemetry/api/build/src/baggage/utils.js
var require_utils = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.baggageEntryMetadataFromString = exports.createBaggage = undefined;
  var diag_1 = require_diag();
  var baggage_impl_1 = require_baggage_impl();
  var symbol_1 = require_symbol();
  var diag = diag_1.DiagAPI.instance();
  function createBaggage(entries = {}) {
    return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries)));
  }
  exports.createBaggage = createBaggage;
  function baggageEntryMetadataFromString(str) {
    if (typeof str !== "string") {
      diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`);
      str = "";
    }
    return {
      __TYPE__: symbol_1.baggageEntryMetadataSymbol,
      toString() {
        return str;
      }
    };
  }
  exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString;
});

// node_modules/@opentelemetry/api/build/src/context/context.js
var require_context = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.ROOT_CONTEXT = exports.createContextKey = undefined;
  function createContextKey(description) {
    return Symbol.for(description);
  }
  exports.createContextKey = createContextKey;

  class BaseContext {
    constructor(parentContext) {
      const self = this;
      self._currentContext = parentContext ? new Map(parentContext) : new Map;
      self.getValue = (key) => self._currentContext.get(key);
      self.setValue = (key, value) => {
        const context = new BaseContext(self._currentContext);
        context._currentContext.set(key, value);
        return context;
      };
      self.deleteValue = (key) => {
        const context = new BaseContext(self._currentContext);
        context._currentContext.delete(key);
        return context;
      };
    }
  }
  exports.ROOT_CONTEXT = new BaseContext;
});

// node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js
var require_consoleLogger = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.DiagConsoleLogger = undefined;
  var consoleMap = [
    { n: "error", c: "error" },
    { n: "warn", c: "warn" },
    { n: "info", c: "info" },
    { n: "debug", c: "debug" },
    { n: "verbose", c: "trace" }
  ];

  class DiagConsoleLogger {
    constructor() {
      function _consoleFunc(funcName) {
        return function(...args) {
          if (console) {
            let theFunc = console[funcName];
            if (typeof theFunc !== "function") {
              theFunc = console.log;
            }
            if (typeof theFunc === "function") {
              return theFunc.apply(console, args);
            }
          }
        };
      }
      for (let i = 0;i < consoleMap.length; i++) {
        this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c);
      }
    }
  }
  exports.DiagConsoleLogger = DiagConsoleLogger;
});

// node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js
var require_NoopMeter = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_GAUGE_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopGaugeMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = undefined;

  class NoopMeter {
    constructor() {
    }
    createGauge(_name, _options) {
      return exports.NOOP_GAUGE_METRIC;
    }
    createHistogram(_name, _options) {
      return exports.NOOP_HISTOGRAM_METRIC;
    }
    createCounter(_name, _options) {
      return exports.NOOP_COUNTER_METRIC;
    }
    createUpDownCounter(_name, _options) {
      return exports.NOOP_UP_DOWN_COUNTER_METRIC;
    }
    createObservableGauge(_name, _options) {
      return exports.NOOP_OBSERVABLE_GAUGE_METRIC;
    }
    createObservableCounter(_name, _options) {
      return exports.NOOP_OBSERVABLE_COUNTER_METRIC;
    }
    createObservableUpDownCounter(_name, _options) {
      return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;
    }
    addBatchObservableCallback(_callback, _observables) {
    }
    removeBatchObservableCallback(_callback) {
    }
  }
  exports.NoopMeter = NoopMeter;

  class NoopMetric {
  }
  exports.NoopMetric = NoopMetric;

  class NoopCounterMetric extends NoopMetric {
    add(_value, _attributes) {
    }
  }
  exports.NoopCounterMetric = NoopCounterMetric;

  class NoopUpDownCounterMetric extends NoopMetric {
    add(_value, _attributes) {
    }
  }
  exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric;

  class NoopGaugeMetric extends NoopMetric {
    record(_value, _attributes) {
    }
  }
  exports.NoopGaugeMetric = NoopGaugeMetric;

  class NoopHistogramMetric extends NoopMetric {
    record(_value, _attributes) {
    }
  }
  exports.NoopHistogramMetric = NoopHistogramMetric;

  class NoopObservableMetric {
    addCallback(_callback) {
    }
    removeCallback(_callback) {
    }
  }
  exports.NoopObservableMetric = NoopObservableMetric;

  class NoopObservableCounterMetric extends NoopObservableMetric {
  }
  exports.NoopObservableCounterMetric = NoopObservableCounterMetric;

  class NoopObservableGaugeMetric extends NoopObservableMetric {
  }
  exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric;

  class NoopObservableUpDownCounterMetric extends NoopObservableMetric {
  }
  exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric;
  exports.NOOP_METER = new NoopMeter;
  exports.NOOP_COUNTER_METRIC = new NoopCounterMetric;
  exports.NOOP_GAUGE_METRIC = new NoopGaugeMetric;
  exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric;
  exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric;
  exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric;
  exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric;
  exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric;
  function createNoopMeter() {
    return exports.NOOP_METER;
  }
  exports.createNoopMeter = createNoopMeter;
});

// node_modules/@opentelemetry/api/build/src/metrics/Metric.js
var require_Metric = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.ValueType = undefined;
  var ValueType;
  (function(ValueType2) {
    ValueType2[ValueType2["INT"] = 0] = "INT";
    ValueType2[ValueType2["DOUBLE"] = 1] = "DOUBLE";
  })(ValueType = exports.ValueType || (exports.ValueType = {}));
});

// node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js
var require_TextMapPropagator = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.defaultTextMapSetter = exports.defaultTextMapGetter = undefined;
  exports.defaultTextMapGetter = {
    get(carrier, key) {
      if (carrier == null) {
        return;
      }
      return carrier[key];
    },
    keys(carrier) {
      if (carrier == null) {
        return [];
      }
      return Object.keys(carrier);
    }
  };
  exports.defaultTextMapSetter = {
    set(carrier, key, value) {
      if (carrier == null) {
        return;
      }
      carrier[key] = value;
    }
  };
});

// node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js
var require_NoopContextManager = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.NoopContextManager = undefined;
  var context_1 = require_context();

  class NoopContextManager {
    active() {
      return context_1.ROOT_CONTEXT;
    }
    with(_context, fn, thisArg, ...args) {
      return fn.call(thisArg, ...args);
    }
    bind(_context, target) {
      return target;
    }
    enable() {
      return this;
    }
    disable() {
      return this;
    }
  }
  exports.NoopContextManager = NoopContextManager;
});

// node_modules/@opentelemetry/api/build/src/api/context.js
var require_context2 = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.ContextAPI = undefined;
  var NoopContextManager_1 = require_NoopContextManager();
  var global_utils_1 = require_global_utils();
  var diag_1 = require_diag();
  var API_NAME = "context";
  var NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager;

  class ContextAPI {
    constructor() {
    }
    static getInstance() {
      if (!this._instance) {
        this._instance = new ContextAPI;
      }
      return this._instance;
    }
    setGlobalContextManager(contextManager) {
      return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance());
    }
    active() {
      return this._getContextManager().active();
    }
    with(context, fn, thisArg, ...args) {
      return this._getContextManager().with(context, fn, thisArg, ...args);
    }
    bind(context, target) {
      return this._getContextManager().bind(context, target);
    }
    _getContextManager() {
      return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER;
    }
    disable() {
      this._getContextManager().disable();
      (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
    }
  }
  exports.ContextAPI = ContextAPI;
});

// node_modules/@opentelemetry/api/build/src/trace/trace_flags.js
var require_trace_flags = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.TraceFlags = undefined;
  var TraceFlags;
  (function(TraceFlags2) {
    TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE";
    TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED";
  })(TraceFlags = exports.TraceFlags || (exports.TraceFlags = {}));
});

// node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js
var require_invalid_span_constants = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = undefined;
  var trace_flags_1 = require_trace_flags();
  exports.INVALID_SPANID = "0000000000000000";
  exports.INVALID_TRACEID = "00000000000000000000000000000000";
  exports.INVALID_SPAN_CONTEXT = {
    traceId: exports.INVALID_TRACEID,
    spanId: exports.INVALID_SPANID,
    traceFlags: trace_flags_1.TraceFlags.NONE
  };
});

// node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js
var require_NonRecordingSpan = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.NonRecordingSpan = undefined;
  var invalid_span_constants_1 = require_invalid_span_constants();

  class NonRecordingSpan {
    constructor(_spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) {
      this._spanContext = _spanContext;
    }
    spanContext() {
      return this._spanContext;
    }
    setAttribute(_key, _value) {
      return this;
    }
    setAttributes(_attributes) {
      return this;
    }
    addEvent(_name, _attributes) {
      return this;
    }
    addLink(_link) {
      return this;
    }
    addLinks(_links) {
      return this;
    }
    setStatus(_status) {
      return this;
    }
    updateName(_name) {
      return this;
    }
    end(_endTime) {
    }
    isRecording() {
      return false;
    }
    recordException(_exception, _time) {
    }
  }
  exports.NonRecordingSpan = NonRecordingSpan;
});

// node_modules/@opentelemetry/api/build/src/trace/context-utils.js
var require_context_utils = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = undefined;
  var context_1 = require_context();
  var NonRecordingSpan_1 = require_NonRecordingSpan();
  var context_2 = require_context2();
  var SPAN_KEY = (0, context_1.createContextKey)("OpenTelemetry Context Key SPAN");
  function getSpan(context) {
    return context.getValue(SPAN_KEY) || undefined;
  }
  exports.getSpan = getSpan;
  function getActiveSpan() {
    return getSpan(context_2.ContextAPI.getInstance().active());
  }
  exports.getActiveSpan = getActiveSpan;
  function setSpan(context, span) {
    return context.setValue(SPAN_KEY, span);
  }
  exports.setSpan = setSpan;
  function deleteSpan(context) {
    return context.deleteValue(SPAN_KEY);
  }
  exports.deleteSpan = deleteSpan;
  function setSpanContext(context, spanContext) {
    return setSpan(context, new NonRecordingSpan_1.NonRecordingSpan(spanContext));
  }
  exports.setSpanContext = setSpanContext;
  function getSpanContext(context) {
    var _a15;
    return (_a15 = getSpan(context)) === null || _a15 === undefined ? undefined : _a15.spanContext();
  }
  exports.getSpanContext = getSpanContext;
});

// node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js
var require_spancontext_utils = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = undefined;
  var invalid_span_constants_1 = require_invalid_span_constants();
  var NonRecordingSpan_1 = require_NonRecordingSpan();
  var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;
  var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
  function isValidTraceId(traceId) {
    return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID;
  }
  exports.isValidTraceId = isValidTraceId;
  function isValidSpanId(spanId) {
    return VALID_SPANID_REGEX.test(spanId) && spanId !== invalid_span_constants_1.INVALID_SPANID;
  }
  exports.isValidSpanId = isValidSpanId;
  function isSpanContextValid(spanContext) {
    return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);
  }
  exports.isSpanContextValid = isSpanContextValid;
  function wrapSpanContext(spanContext) {
    return new NonRecordingSpan_1.NonRecordingSpan(spanContext);
  }
  exports.wrapSpanContext = wrapSpanContext;
});

// node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js
var require_NoopTracer = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.NoopTracer = undefined;
  var context_1 = require_context2();
  var context_utils_1 = require_context_utils();
  var NonRecordingSpan_1 = require_NonRecordingSpan();
  var spancontext_utils_1 = require_spancontext_utils();
  var contextApi = context_1.ContextAPI.getInstance();

  class NoopTracer {
    startSpan(name14, options, context = contextApi.active()) {
      const root = Boolean(options === null || options === undefined ? undefined : options.root);
      if (root) {
        return new NonRecordingSpan_1.NonRecordingSpan;
      }
      const parentFromContext = context && (0, context_utils_1.getSpanContext)(context);
      if (isSpanContext(parentFromContext) && (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) {
        return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext);
      } else {
        return new NonRecordingSpan_1.NonRecordingSpan;
      }
    }
    startActiveSpan(name14, arg2, arg3, arg4) {
      let opts;
      let ctx;
      let fn;
      if (arguments.length < 2) {
        return;
      } else if (arguments.length === 2) {
        fn = arg2;
      } else if (arguments.length === 3) {
        opts = arg2;
        fn = arg3;
      } else {
        opts = arg2;
        ctx = arg3;
        fn = arg4;
      }
      const parentContext = ctx !== null && ctx !== undefined ? ctx : contextApi.active();
      const span = this.startSpan(name14, opts, parentContext);
      const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span);
      return contextApi.with(contextWithSpanSet, fn, undefined, span);
    }
  }
  exports.NoopTracer = NoopTracer;
  function isSpanContext(spanContext) {
    return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number";
  }
});

// node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js
var require_ProxyTracer = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.ProxyTracer = undefined;
  var NoopTracer_1 = require_NoopTracer();
  var NOOP_TRACER = new NoopTracer_1.NoopTracer;

  class ProxyTracer {
    constructor(_provider, name14, version, options) {
      this._provider = _provider;
      this.name = name14;
      this.version = version;
      this.options = options;
    }
    startSpan(name14, options, context) {
      return this._getTracer().startSpan(name14, options, context);
    }
    startActiveSpan(_name, _options, _context, _fn) {
      const tracer = this._getTracer();
      return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
    }
    _getTracer() {
      if (this._delegate) {
        return this._delegate;
      }
      const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
      if (!tracer) {
        return NOOP_TRACER;
      }
      this._delegate = tracer;
      return this._delegate;
    }
  }
  exports.ProxyTracer = ProxyTracer;
});

// node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js
var require_NoopTracerProvider = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.NoopTracerProvider = undefined;
  var NoopTracer_1 = require_NoopTracer();

  class NoopTracerProvider {
    getTracer(_name, _version, _options) {
      return new NoopTracer_1.NoopTracer;
    }
  }
  exports.NoopTracerProvider = NoopTracerProvider;
});

// node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js
var require_ProxyTracerProvider = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.ProxyTracerProvider = undefined;
  var ProxyTracer_1 = require_ProxyTracer();
  var NoopTracerProvider_1 = require_NoopTracerProvider();
  var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider;

  class ProxyTracerProvider {
    getTracer(name14, version, options) {
      var _a15;
      return (_a15 = this.getDelegateTracer(name14, version, options)) !== null && _a15 !== undefined ? _a15 : new ProxyTracer_1.ProxyTracer(this, name14, version, options);
    }
    getDelegate() {
      var _a15;
      return (_a15 = this._delegate) !== null && _a15 !== undefined ? _a15 : NOOP_TRACER_PROVIDER;
    }
    setDelegate(delegate) {
      this._delegate = delegate;
    }
    getDelegateTracer(name14, version, options) {
      var _a15;
      return (_a15 = this._delegate) === null || _a15 === undefined ? undefined : _a15.getTracer(name14, version, options);
    }
  }
  exports.ProxyTracerProvider = ProxyTracerProvider;
});

// node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js
var require_SamplingResult = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.SamplingDecision = undefined;
  var SamplingDecision;
  (function(SamplingDecision2) {
    SamplingDecision2[SamplingDecision2["NOT_RECORD"] = 0] = "NOT_RECORD";
    SamplingDecision2[SamplingDecision2["RECORD"] = 1] = "RECORD";
    SamplingDecision2[SamplingDecision2["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED";
  })(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {}));
});

// node_modules/@opentelemetry/api/build/src/trace/span_kind.js
var require_span_kind = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.SpanKind = undefined;
  var SpanKind;
  (function(SpanKind2) {
    SpanKind2[SpanKind2["INTERNAL"] = 0] = "INTERNAL";
    SpanKind2[SpanKind2["SERVER"] = 1] = "SERVER";
    SpanKind2[SpanKind2["CLIENT"] = 2] = "CLIENT";
    SpanKind2[SpanKind2["PRODUCER"] = 3] = "PRODUCER";
    SpanKind2[SpanKind2["CONSUMER"] = 4] = "CONSUMER";
  })(SpanKind = exports.SpanKind || (exports.SpanKind = {}));
});

// node_modules/@opentelemetry/api/build/src/trace/status.js
var require_status = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.SpanStatusCode = undefined;
  var SpanStatusCode;
  (function(SpanStatusCode2) {
    SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET";
    SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK";
    SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR";
  })(SpanStatusCode = exports.SpanStatusCode || (exports.SpanStatusCode = {}));
});

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

// node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js
var require_tracestate_impl = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.TraceStateImpl = undefined;
  var tracestate_validators_1 = require_tracestate_validators();
  var MAX_TRACE_STATE_ITEMS = 32;
  var MAX_TRACE_STATE_LEN = 512;
  var LIST_MEMBERS_SEPARATOR = ",";
  var LIST_MEMBER_KEY_VALUE_SPLITTER = "=";

  class TraceStateImpl {
    constructor(rawTraceState) {
      this._internalState = new Map;
      if (rawTraceState)
        this._parse(rawTraceState);
    }
    set(key, value) {
      const traceState = this._clone();
      if (traceState._internalState.has(key)) {
        traceState._internalState.delete(key);
      }
      traceState._internalState.set(key, value);
      return traceState;
    }
    unset(key) {
      const traceState = this._clone();
      traceState._internalState.delete(key);
      return traceState;
    }
    get(key) {
      return this._internalState.get(key);
    }
    serialize() {
      return this._keys().reduce((agg, key) => {
        agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));
        return agg;
      }, []).join(LIST_MEMBERS_SEPARATOR);
    }
    _parse(rawTraceState) {
      if (rawTraceState.length > MAX_TRACE_STATE_LEN)
        return;
      this._internalState = rawTraceState.split(LIST_MEMBERS_SEPARATOR).reverse().reduce((agg, part) => {
        const listMember = part.trim();
        const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);
        if (i !== -1) {
          const key = listMember.slice(0, i);
          const value = listMember.slice(i + 1, part.length);
          if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) {
            agg.set(key, value);
          } else {
          }
        }
        return agg;
      }, new Map);
      if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {
        this._internalState = new Map(Array.from(this._internalState.entries()).reverse().slice(0, MAX_TRACE_STATE_ITEMS));
      }
    }
    _keys() {
      return Array.from(this._internalState.keys()).reverse();
    }
    _clone() {
      const traceState = new TraceStateImpl;
      traceState._internalState = new Map(this._internalState);
      return traceState;
    }
  }
  exports.TraceStateImpl = TraceStateImpl;
});

// node_modules/@opentelemetry/api/build/src/trace/internal/utils.js
var require_utils2 = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.createTraceState = undefined;
  var tracestate_impl_1 = require_tracestate_impl();
  function createTraceState(rawTraceState) {
    return new tracestate_impl_1.TraceStateImpl(rawTraceState);
  }
  exports.createTraceState = createTraceState;
});

// node_modules/@opentelemetry/api/build/src/context-api.js
var require_context_api = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.context = undefined;
  var context_1 = require_context2();
  exports.context = context_1.ContextAPI.getInstance();
});

// node_modules/@opentelemetry/api/build/src/diag-api.js
var require_diag_api = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.diag = undefined;
  var diag_1 = require_diag();
  exports.diag = diag_1.DiagAPI.instance();
});

// node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js
var require_NoopMeterProvider = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = undefined;
  var NoopMeter_1 = require_NoopMeter();

  class NoopMeterProvider {
    getMeter(_name, _version, _options) {
      return NoopMeter_1.NOOP_METER;
    }
  }
  exports.NoopMeterProvider = NoopMeterProvider;
  exports.NOOP_METER_PROVIDER = new NoopMeterProvider;
});

// node_modules/@opentelemetry/api/build/src/api/metrics.js
var require_metrics = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.MetricsAPI = undefined;
  var NoopMeterProvider_1 = require_NoopMeterProvider();
  var global_utils_1 = require_global_utils();
  var diag_1 = require_diag();
  var API_NAME = "metrics";

  class MetricsAPI {
    constructor() {
    }
    static getInstance() {
      if (!this._instance) {
        this._instance = new MetricsAPI;
      }
      return this._instance;
    }
    setGlobalMeterProvider(provider) {
      return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance());
    }
    getMeterProvider() {
      return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER;
    }
    getMeter(name14, version, options) {
      return this.getMeterProvider().getMeter(name14, version, options);
    }
    disable() {
      (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
    }
  }
  exports.MetricsAPI = MetricsAPI;
});

// node_modules/@opentelemetry/api/build/src/metrics-api.js
var require_metrics_api = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.metrics = undefined;
  var metrics_1 = require_metrics();
  exports.metrics = metrics_1.MetricsAPI.getInstance();
});

// node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js
var require_NoopTextMapPropagator = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.NoopTextMapPropagator = undefined;

  class NoopTextMapPropagator {
    inject(_context, _carrier) {
    }
    extract(context, _carrier) {
      return context;
    }
    fields() {
      return [];
    }
  }
  exports.NoopTextMapPropagator = NoopTextMapPropagator;
});

// node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js
var require_context_helpers = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = undefined;
  var context_1 = require_context2();
  var context_2 = require_context();
  var BAGGAGE_KEY = (0, context_2.createContextKey)("OpenTelemetry Baggage Key");
  function getBaggage(context) {
    return context.getValue(BAGGAGE_KEY) || undefined;
  }
  exports.getBaggage = getBaggage;
  function getActiveBaggage() {
    return getBaggage(context_1.ContextAPI.getInstance().active());
  }
  exports.getActiveBaggage = getActiveBaggage;
  function setBaggage(context, baggage) {
    return context.setValue(BAGGAGE_KEY, baggage);
  }
  exports.setBaggage = setBaggage;
  function deleteBaggage(context) {
    return context.deleteValue(BAGGAGE_KEY);
  }
  exports.deleteBaggage = deleteBaggage;
});

// node_modules/@opentelemetry/api/build/src/api/propagation.js
var require_propagation = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.PropagationAPI = undefined;
  var global_utils_1 = require_global_utils();
  var NoopTextMapPropagator_1 = require_NoopTextMapPropagator();
  var TextMapPropagator_1 = require_TextMapPropagator();
  var context_helpers_1 = require_context_helpers();
  var utils_1 = require_utils();
  var diag_1 = require_diag();
  var API_NAME = "propagation";
  var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator;

  class PropagationAPI {
    constructor() {
      this.createBaggage = utils_1.createBaggage;
      this.getBaggage = context_helpers_1.getBaggage;
      this.getActiveBaggage = context_helpers_1.getActiveBaggage;
      this.setBaggage = context_helpers_1.setBaggage;
      this.deleteBaggage = context_helpers_1.deleteBaggage;
    }
    static getInstance() {
      if (!this._instance) {
        this._instance = new PropagationAPI;
      }
      return this._instance;
    }
    setGlobalPropagator(propagator) {
      return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance());
    }
    inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) {
      return this._getGlobalPropagator().inject(context, carrier, setter);
    }
    extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) {
      return this._getGlobalPropagator().extract(context, carrier, getter);
    }
    fields() {
      return this._getGlobalPropagator().fields();
    }
    disable() {
      (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
    }
    _getGlobalPropagator() {
      return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR;
    }
  }
  exports.PropagationAPI = PropagationAPI;
});

// node_modules/@opentelemetry/api/build/src/propagation-api.js
var require_propagation_api = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.propagation = undefined;
  var propagation_1 = require_propagation();
  exports.propagation = propagation_1.PropagationAPI.getInstance();
});

// node_modules/@opentelemetry/api/build/src/api/trace.js
var require_trace = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.TraceAPI = undefined;
  var global_utils_1 = require_global_utils();
  var ProxyTracerProvider_1 = require_ProxyTracerProvider();
  var spancontext_utils_1 = require_spancontext_utils();
  var context_utils_1 = require_context_utils();
  var diag_1 = require_diag();
  var API_NAME = "trace";

  class TraceAPI {
    constructor() {
      this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider;
      this.wrapSpanContext = spancontext_utils_1.wrapSpanContext;
      this.isSpanContextValid = spancontext_utils_1.isSpanContextValid;
      this.deleteSpan = context_utils_1.deleteSpan;
      this.getSpan = context_utils_1.getSpan;
      this.getActiveSpan = context_utils_1.getActiveSpan;
      this.getSpanContext = context_utils_1.getSpanContext;
      this.setSpan = context_utils_1.setSpan;
      this.setSpanContext = context_utils_1.setSpanContext;
    }
    static getInstance() {
      if (!this._instance) {
        this._instance = new TraceAPI;
      }
      return this._instance;
    }
    setGlobalTracerProvider(provider) {
      const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance());
      if (success) {
        this._proxyTracerProvider.setDelegate(provider);
      }
      return success;
    }
    getTracerProvider() {
      return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider;
    }
    getTracer(name14, version) {
      return this.getTracerProvider().getTracer(name14, version);
    }
    disable() {
      (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance());
      this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider;
    }
  }
  exports.TraceAPI = TraceAPI;
});

// node_modules/@opentelemetry/api/build/src/trace-api.js
var require_trace_api = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.trace = undefined;
  var trace_1 = require_trace();
  exports.trace = trace_1.TraceAPI.getInstance();
});

// node_modules/@opentelemetry/api/build/src/index.js
var require_src = __commonJS((exports) => {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = undefined;
  var utils_1 = require_utils();
  Object.defineProperty(exports, "baggageEntryMetadataFromString", { enumerable: true, get: function() {
    return utils_1.baggageEntryMetadataFromString;
  } });
  var context_1 = require_context();
  Object.defineProperty(exports, "createContextKey", { enumerable: true, get: function() {
    return context_1.createContextKey;
  } });
  Object.defineProperty(exports, "ROOT_CONTEXT", { enumerable: true, get: function() {
    return context_1.ROOT_CONTEXT;
  } });
  var consoleLogger_1 = require_consoleLogger();
  Object.defineProperty(exports, "DiagConsoleLogger", { enumerable: true, get: function() {
    return consoleLogger_1.DiagConsoleLogger;
  } });
  var types_1 = require_types();
  Object.defineProperty(exports, "DiagLogLevel", { enumerable: true, get: function() {
    return types_1.DiagLogLevel;
  } });
  var NoopMeter_1 = require_NoopMeter();
  Object.defineProperty(exports, "createNoopMeter", { enumerable: true, get: function() {
    return NoopMeter_1.createNoopMeter;
  } });
  var Metric_1 = require_Metric();
  Object.defineProperty(exports, "ValueType", { enumerable: true, get: function() {
    return Metric_1.ValueType;
  } });
  var TextMapPropagator_1 = require_TextMapPropagator();
  Object.defineProperty(exports, "defaultTextMapGetter", { enumerable: true, get: function() {
    return TextMapPropagator_1.defaultTextMapGetter;
  } });
  Object.defineProperty(exports, "defaultTextMapSetter", { enumerable: true, get: function() {
    return TextMapPropagator_1.defaultTextMapSetter;
  } });
  var ProxyTracer_1 = require_ProxyTracer();
  Object.defineProperty(exports, "ProxyTracer", { enumerable: true, get: function() {
    return ProxyTracer_1.ProxyTracer;
  } });
  var ProxyTracerProvider_1 = require_ProxyTracerProvider();
  Object.defineProperty(exports, "ProxyTracerProvider", { enumerable: true, get: function() {
    return ProxyTracerProvider_1.ProxyTracerProvider;
  } });
  var SamplingResult_1 = require_SamplingResult();
  Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function() {
    return SamplingResult_1.SamplingDecision;
  } });
  var span_kind_1 = require_span_kind();
  Object.defineProperty(exports, "SpanKind", { enumerable: true, get: function() {
    return span_kind_1.SpanKind;
  } });
  var status_1 = require_status();
  Object.defineProperty(exports, "SpanStatusCode", { enumerable: true, get: function() {
    return status_1.SpanStatusCode;
  } });
  var trace_flags_1 = require_trace_flags();
  Object.defineProperty(exports, "TraceFlags", { enumerable: true, get: function() {
    return trace_flags_1.TraceFlags;
  } });
  var utils_2 = require_utils2();
  Object.defineProperty(exports, "createTraceState", { enumerable: true, get: function() {
    return utils_2.createTraceState;
  } });
  var spancontext_utils_1 = require_spancontext_utils();
  Object.defineProperty(exports, "isSpanContextValid", { enumerable: true, get: function() {
    return spancontext_utils_1.isSpanContextValid;
  } });
  Object.defineProperty(exports, "isValidTraceId", { enumerable: true, get: function() {
    return spancontext_utils_1.isValidTraceId;
  } });
  Object.defineProperty(exports, "isValidSpanId", { enumerable: true, get: function() {
    return spancontext_utils_1.isValidSpanId;
  } });
  var invalid_span_constants_1 = require_invalid_span_constants();
  Object.defineProperty(exports, "INVALID_SPANID", { enumerable: true, get: function() {
    return invalid_span_constants_1.INVALID_SPANID;
  } });
  Object.defineProperty(exports, "INVALID_TRACEID", { enumerable: true, get: function() {
    return invalid_span_constants_1.INVALID_TRACEID;
  } });
  Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", { enumerable: true, get: function() {
    return invalid_span_constants_1.INVALID_SPAN_CONTEXT;
  } });
  var context_api_1 = require_context_api();
  Object.defineProperty(exports, "context", { enumerable: true, get: function() {
    return context_api_1.context;
  } });
  var diag_api_1 = require_diag_api();
  Object.defineProperty(exports, "diag", { enumerable: true, get: function() {
    return diag_api_1.diag;
  } });
  var metrics_api_1 = require_metrics_api();
  Object.defineProperty(exports, "metrics", { enumerable: true, get: function() {
    return metrics_api_1.metrics;
  } });
  var propagation_api_1 = require_propagation_api();
  Object.defineProperty(exports, "propagation", { enumerable: true, get: function() {
    return propagation_api_1.propagation;
  } });
  var trace_api_1 = require_trace_api();
  Object.defineProperty(exports, "trace", { enumerable: true, get: function() {
    return trace_api_1.trace;
  } });
  exports.default = {
    context: context_api_1.context,
    diag: diag_api_1.diag,
    metrics: metrics_api_1.metrics,
    propagation: propagation_api_1.propagation,
    trace: trace_api_1.trace
  };
});

// src/agent.ts
var import_nunjucks = __toESM(require_nunjucks(), 1);
import { randomUUID } from "node:crypto";

class Agent {
  config;
  name;
  description;
  tools;
  uuid;
  constructor(options) {
    const { name, description, tools, ...config } = options;
    this.config = config;
    this.name = name;
    this.description = description;
    this.tools = tools;
    this.uuid = randomUUID();
  }
  getInstructions(context) {
    if (typeof this.config.instructions === "string") {
      return import_nunjucks.default.renderString(this.config.instructions, context);
    } else
      return this.config.instructions(context);
  }
}
var a = 1;
// node_modules/@ai-sdk/provider/dist/index.mjs
var marker = "vercel.ai.error";
var symbol = Symbol.for(marker);
var _a;
var _AISDKError = class _AISDKError2 extends Error {
  constructor({
    name: name14,
    message,
    cause
  }) {
    super(message);
    this[_a] = true;
    this.name = name14;
    this.cause = cause;
  }
  static isInstance(error) {
    return _AISDKError2.hasMarker(error, marker);
  }
  static hasMarker(error, marker15) {
    const markerSymbol = Symbol.for(marker15);
    return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
  }
};
_a = symbol;
var AISDKError = _AISDKError;
var name = "AI_APICallError";
var marker2 = `vercel.ai.error.${name}`;
var symbol2 = Symbol.for(marker2);
var _a2;
var APICallError = class extends AISDKError {
  constructor({
    message,
    url,
    requestBodyValues,
    statusCode,
    responseHeaders,
    responseBody,
    cause,
    isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500),
    data
  }) {
    super({ name, message, cause });
    this[_a2] = true;
    this.url = url;
    this.requestBodyValues = requestBodyValues;
    this.statusCode = statusCode;
    this.responseHeaders = responseHeaders;
    this.responseBody = responseBody;
    this.isRetryable = isRetryable;
    this.data = data;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker2);
  }
};
_a2 = symbol2;
var name2 = "AI_EmptyResponseBodyError";
var marker3 = `vercel.ai.error.${name2}`;
var symbol3 = Symbol.for(marker3);
var _a3;
var EmptyResponseBodyError = class extends AISDKError {
  constructor({ message = "Empty response body" } = {}) {
    super({ name: name2, message });
    this[_a3] = true;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker3);
  }
};
_a3 = symbol3;
function getErrorMessage(error) {
  if (error == null) {
    return "unknown error";
  }
  if (typeof error === "string") {
    return error;
  }
  if (error instanceof Error) {
    return error.message;
  }
  return JSON.stringify(error);
}
var name3 = "AI_InvalidArgumentError";
var marker4 = `vercel.ai.error.${name3}`;
var symbol4 = Symbol.for(marker4);
var _a4;
var InvalidArgumentError = class extends AISDKError {
  constructor({
    message,
    cause,
    argument
  }) {
    super({ name: name3, message, cause });
    this[_a4] = true;
    this.argument = argument;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker4);
  }
};
_a4 = symbol4;
var name4 = "AI_InvalidPromptError";
var marker5 = `vercel.ai.error.${name4}`;
var symbol5 = Symbol.for(marker5);
var _a5;
var InvalidPromptError = class extends AISDKError {
  constructor({
    prompt,
    message,
    cause
  }) {
    super({ name: name4, message: `Invalid prompt: ${message}`, cause });
    this[_a5] = true;
    this.prompt = prompt;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker5);
  }
};
_a5 = symbol5;
var name5 = "AI_InvalidResponseDataError";
var marker6 = `vercel.ai.error.${name5}`;
var symbol6 = Symbol.for(marker6);
var _a6;
var InvalidResponseDataError = class extends AISDKError {
  constructor({
    data,
    message = `Invalid response data: ${JSON.stringify(data)}.`
  }) {
    super({ name: name5, message });
    this[_a6] = true;
    this.data = data;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker6);
  }
};
_a6 = symbol6;
var name6 = "AI_JSONParseError";
var marker7 = `vercel.ai.error.${name6}`;
var symbol7 = Symbol.for(marker7);
var _a7;
var JSONParseError = class extends AISDKError {
  constructor({ text, cause }) {
    super({
      name: name6,
      message: `JSON parsing failed: Text: ${text}.
Error message: ${getErrorMessage(cause)}`,
      cause
    });
    this[_a7] = true;
    this.text = text;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker7);
  }
};
_a7 = symbol7;
var name7 = "AI_LoadAPIKeyError";
var marker8 = `vercel.ai.error.${name7}`;
var symbol8 = Symbol.for(marker8);
var _a8;
var LoadAPIKeyError = class extends AISDKError {
  constructor({ message }) {
    super({ name: name7, message });
    this[_a8] = true;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker8);
  }
};
_a8 = symbol8;
var name8 = "AI_LoadSettingError";
var marker9 = `vercel.ai.error.${name8}`;
var symbol9 = Symbol.for(marker9);
var _a9;
_a9 = symbol9;
var name9 = "AI_NoContentGeneratedError";
var marker10 = `vercel.ai.error.${name9}`;
var symbol10 = Symbol.for(marker10);
var _a10;
_a10 = symbol10;
var name10 = "AI_NoSuchModelError";
var marker11 = `vercel.ai.error.${name10}`;
var symbol11 = Symbol.for(marker11);
var _a11;
_a11 = symbol11;
var name11 = "AI_TooManyEmbeddingValuesForCallError";
var marker12 = `vercel.ai.error.${name11}`;
var symbol12 = Symbol.for(marker12);
var _a12;
var TooManyEmbeddingValuesForCallError = class extends AISDKError {
  constructor(options) {
    super({
      name: name11,
      message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.`
    });
    this[_a12] = true;
    this.provider = options.provider;
    this.modelId = options.modelId;
    this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall;
    this.values = options.values;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker12);
  }
};
_a12 = symbol12;
var name12 = "AI_TypeValidationError";
var marker13 = `vercel.ai.error.${name12}`;
var symbol13 = Symbol.for(marker13);
var _a13;
var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
  constructor({ value, cause }) {
    super({
      name: name12,
      message: `Type validation failed: Value: ${JSON.stringify(value)}.
Error message: ${getErrorMessage(cause)}`,
      cause
    });
    this[_a13] = true;
    this.value = value;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker13);
  }
  static wrap({
    value,
    cause
  }) {
    return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
  }
};
_a13 = symbol13;
var TypeValidationError = _TypeValidationError;
var name13 = "AI_UnsupportedFunctionalityError";
var marker14 = `vercel.ai.error.${name13}`;
var symbol14 = Symbol.for(marker14);
var _a14;
var UnsupportedFunctionalityError = class extends AISDKError {
  constructor({ functionality }) {
    super({
      name: name13,
      message: `'${functionality}' functionality not supported.`
    });
    this[_a14] = true;
    this.functionality = functionality;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker14);
  }
};
_a14 = symbol14;

// node_modules/nanoid/non-secure/index.js
var customAlphabet = (alphabet, defaultSize = 21) => {
  return (size = defaultSize) => {
    let id = "";
    let i = size | 0;
    while (i--) {
      id += alphabet[Math.random() * alphabet.length | 0];
    }
    return id;
  };
};

// node_modules/@ai-sdk/provider-utils/dist/index.mjs
var import_secure_json_parse = __toESM(require_secure_json_parse(), 1);

// node_modules/eventsource-parser/dist/index.js
var __defProp2 = Object.defineProperty;
var __defNormalProp = (obj, key, value) => (key in obj) ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key != "symbol" ? key + "" : key, value);

class ParseError extends Error {
  constructor(message, options) {
    super(message), __publicField(this, "type"), __publicField(this, "field"), __publicField(this, "value"), __publicField(this, "line"), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
  }
}
function noop(_arg) {
}
function createParser(callbacks) {
  const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
  let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
  function feed(newChunk) {
    const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
    for (const line of complete)
      parseLine(line);
    incompleteLine = incomplete, isFirstChunk = false;
  }
  function parseLine(line) {
    if (line === "") {
      dispatchEvent();
      return;
    }
    if (line.startsWith(":")) {
      onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
      return;
    }
    const fieldSeparatorIndex = line.indexOf(":");
    if (fieldSeparatorIndex !== -1) {
      const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
      processField(field, value, line);
      return;
    }
    processField(line, "", line);
  }
  function processField(field, value, line) {
    switch (field) {
      case "event":
        eventType = value;
        break;
      case "data":
        data = `${data}${value}
`;
        break;
      case "id":
        id = value.includes("\x00") ? undefined : value;
        break;
      case "retry":
        /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(new ParseError(`Invalid \`retry\` value: "${value}"`, {
          type: "invalid-retry",
          value,
          line
        }));
        break;
      default:
        onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}…` : field}"`, { type: "unknown-field", field, value, line }));
        break;
    }
  }
  function dispatchEvent() {
    data.length > 0 && onEvent({
      id,
      event: eventType || undefined,
      data: data.endsWith(`
`) ? data.slice(0, -1) : data
    }), id = undefined, data = "", eventType = "";
  }
  function reset(options = {}) {
    incompleteLine && options.consume && parseLine(incompleteLine), id = undefined, data = "", eventType = "", incompleteLine = "";
  }
  return { feed, reset };
}
function splitLines(chunk) {
  const lines = [];
  let incompleteLine = "";
  const totalLength = chunk.length;
  for (let i = 0;i < totalLength; i++) {
    const char = chunk[i];
    char === "\r" && chunk[i + 1] === `
` ? (lines.push(incompleteLine), incompleteLine = "", i++) : char === "\r" || char === `
` ? (lines.push(incompleteLine), incompleteLine = "") : incompleteLine += char;
  }
  return [lines, incompleteLine];
}

// node_modules/eventsource-parser/dist/stream.js
class EventSourceParserStream extends TransformStream {
  constructor({ onError, onRetry, onComment } = {}) {
    let parser;
    super({
      start(controller) {
        parser = createParser({
          onEvent: (event) => {
            controller.enqueue(event);
          },
          onError(error) {
            onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error);
          },
          onRetry,
          onComment
        });
      },
      transform(chunk) {
        parser.feed(chunk);
      }
    });
  }
}

// node_modules/@ai-sdk/provider-utils/dist/index.mjs
function combineHeaders(...headers) {
  return headers.reduce((combinedHeaders, currentHeaders) => ({
    ...combinedHeaders,
    ...currentHeaders != null ? currentHeaders : {}
  }), {});
}
function convertAsyncIteratorToReadableStream(iterator) {
  return new ReadableStream({
    async pull(controller) {
      try {
        const { value, done } = await iterator.next();
        if (done) {
          controller.close();
        } else {
          controller.enqueue(value);
        }
      } catch (error) {
        controller.error(error);
      }
    },
    cancel() {
    }
  });
}
function extractResponseHeaders(response) {
  const headers = {};
  response.headers.forEach((value, key) => {
    headers[key] = value;
  });
  return headers;
}
var createIdGenerator = ({
  prefix,
  size: defaultSize = 16,
  alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
  separator = "-"
} = {}) => {
  const generator = customAlphabet(alphabet, defaultSize);
  if (prefix == null) {
    return generator;
  }
  if (alphabet.includes(separator)) {
    throw new InvalidArgumentError({
      argument: "separator",
      message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
    });
  }
  return (size) => `${prefix}${separator}${generator(size)}`;
};
var generateId = createIdGenerator();
function getErrorMessage2(error) {
  if (error == null) {
    return "unknown error";
  }
  if (typeof error === "string") {
    return error;
  }
  if (error instanceof Error) {
    return error.message;
  }
  return JSON.stringify(error);
}
function isAbortError(error) {
  return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
}
function loadApiKey({
  apiKey,
  environmentVariableName,
  apiKeyParameterName = "apiKey",
  description
}) {
  if (typeof apiKey === "string") {
    return apiKey;
  }
  if (apiKey != null) {
    throw new LoadAPIKeyError({
      message: `${description} API key must be a string.`
    });
  }
  if (typeof process === "undefined") {
    throw new LoadAPIKeyError({
      message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.`
    });
  }
  apiKey = process.env[environmentVariableName];
  if (apiKey == null) {
    throw new LoadAPIKeyError({
      message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.`
    });
  }
  if (typeof apiKey !== "string") {
    throw new LoadAPIKeyError({
      message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.`
    });
  }
  return apiKey;
}
var validatorSymbol = Symbol.for("vercel.ai.validator");
function validator(validate) {
  return { [validatorSymbol]: true, validate };
}
function isValidator(value) {
  return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
}
function asValidator(value) {
  return isValidator(value) ? value : zodValidator(value);
}
function zodValidator(zodSchema) {
  return validator((value) => {
    const result = zodSchema.safeParse(value);
    return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
  });
}
function validateTypes({
  value,
  schema: inputSchema
}) {
  const result = safeValidateTypes({ value, schema: inputSchema });
  if (!result.success) {
    throw TypeValidationError.wrap({ value, cause: result.error });
  }
  return result.value;
}
function safeValidateTypes({
  value,
  schema
}) {
  const validator2 = asValidator(schema);
  try {
    if (validator2.validate == null) {
      return { success: true, value };
    }
    const result = validator2.validate(value);
    if (result.success) {
      return result;
    }
    return {
      success: false,
      error: TypeValidationError.wrap({ value, cause: result.error })
    };
  } catch (error) {
    return {
      success: false,
      error: TypeValidationError.wrap({ value, cause: error })
    };
  }
}
function parseJSON({
  text,
  schema
}) {
  try {
    const value = import_secure_json_parse.default.parse(text);
    if (schema == null) {
      return value;
    }
    return validateTypes({ value, schema });
  } catch (error) {
    if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) {
      throw error;
    }
    throw new JSONParseError({ text, cause: error });
  }
}
function safeParseJSON({
  text,
  schema
}) {
  try {
    const value = import_secure_json_parse.default.parse(text);
    if (schema == null) {
      return {
        success: true,
        value
      };
    }
    return safeValidateTypes({ value, schema });
  } catch (error) {
    return {
      success: false,
      error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error })
    };
  }
}
function isParsableJson(input) {
  try {
    import_secure_json_parse.default.parse(input);
    return true;
  } catch (e) {
    return false;
  }
}
function removeUndefinedEntries(record) {
  return Object.fromEntries(Object.entries(record).filter(([_key, value]) => value != null));
}
var getOriginalFetch = () => globalThis.fetch;
var postJsonToApi = async ({
  url,
  headers,
  body,
  failedResponseHandler,
  successfulResponseHandler,
  abortSignal,
  fetch: fetch2
}) => postToApi({
  url,
  headers: {
    "Content-Type": "application/json",
    ...headers
  },
  body: {
    content: JSON.stringify(body),
    values: body
  },
  failedResponseHandler,
  successfulResponseHandler,
  abortSignal,
  fetch: fetch2
});
var postToApi = async ({
  url,
  headers = {},
  body,
  successfulResponseHandler,
  failedResponseHandler,
  abortSignal,
  fetch: fetch2 = getOriginalFetch()
}) => {
  try {
    const response = await fetch2(url, {
      method: "POST",
      headers: removeUndefinedEntries(headers),
      body: body.content,
      signal: abortSignal
    });
    const responseHeaders = extractResponseHeaders(response);
    if (!response.ok) {
      let errorInformation;
      try {
        errorInformation = await failedResponseHandler({
          response,
          url,
          requestBodyValues: body.values
        });
      } catch (error) {
        if (isAbortError(error) || APICallError.isInstance(error)) {
          throw error;
        }
        throw new APICallError({
          message: "Failed to process error response",
          cause: error,
          statusCode: response.status,
          url,
          responseHeaders,
          requestBodyValues: body.values
        });
      }
      throw errorInformation.value;
    }
    try {
      return await successfulResponseHandler({
        response,
        url,
        requestBodyValues: body.values
      });
    } catch (error) {
      if (error instanceof Error) {
        if (isAbortError(error) || APICallError.isInstance(error)) {
          throw error;
        }
      }
      throw new APICallError({
        message: "Failed to process successful response",
        cause: error,
        statusCode: response.status,
        url,
        responseHeaders,
        requestBodyValues: body.values
      });
    }
  } catch (error) {
    if (isAbortError(error)) {
      throw error;
    }
    if (error instanceof TypeError && error.message === "fetch failed") {
      const cause = error.cause;
      if (cause != null) {
        throw new APICallError({
          message: `Cannot connect to API: ${cause.message}`,
          cause,
          url,
          requestBodyValues: body.values,
          isRetryable: true
        });
      }
    }
    throw error;
  }
};
var createJsonErrorResponseHandler = ({
  errorSchema,
  errorToMessage,
  isRetryable
}) => async ({ response, url, requestBodyValues }) => {
  const responseBody = await response.text();
  const responseHeaders = extractResponseHeaders(response);
  if (responseBody.trim() === "") {
    return {
      responseHeaders,
      value: new APICallError({
        message: response.statusText,
        url,
        requestBodyValues,
        statusCode: response.status,
        responseHeaders,
        responseBody,
        isRetryable: isRetryable == null ? undefined : isRetryable(response)
      })
    };
  }
  try {
    const parsedError = parseJSON({
      text: responseBody,
      schema: errorSchema
    });
    return {
      responseHeaders,
      value: new APICallError({
        message: errorToMessage(parsedError),
        url,
        requestBodyValues,
        statusCode: response.status,
        responseHeaders,
        responseBody,
        data: parsedError,
        isRetryable: isRetryable == null ? undefined : isRetryable(response, parsedError)
      })
    };
  } catch (parseError) {
    return {
      responseHeaders,
      value: new APICallError({
        message: response.statusText,
        url,
        requestBodyValues,
        statusCode: response.status,
        responseHeaders,
        responseBody,
        isRetryable: isRetryable == null ? undefined : isRetryable(response)
      })
    };
  }
};
var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => {
  const responseHeaders = extractResponseHeaders(response);
  if (response.body == null) {
    throw new EmptyResponseBodyError({});
  }
  return {
    responseHeaders,
    value: response.body.pipeThrough(new TextDecoderStream).pipeThrough(new EventSourceParserStream).pipeThrough(new TransformStream({
      transform({ data }, controller) {
        if (data === "[DONE]") {
          return;
        }
        controller.enqueue(safeParseJSON({
          text: data,
          schema: chunkSchema
        }));
      }
    }))
  };
};
var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => {
  const responseBody = await response.text();
  const parsedResult = safeParseJSON({
    text: responseBody,
    schema: responseSchema
  });
  const responseHeaders = extractResponseHeaders(response);
  if (!parsedResult.success) {
    throw new APICallError({
      message: "Invalid JSON response",
      cause: parsedResult.error,
      statusCode: response.status,
      responseHeaders,
      responseBody,
      url,
      requestBodyValues
    });
  }
  return {
    responseHeaders,
    value: parsedResult.value
  };
};
var { btoa, atob: atob2 } = globalThis;
function convertBase64ToUint8Array(base64String) {
  const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
  const latin1string = atob2(base64Url);
  return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
}
function convertUint8ArrayToBase64(array) {
  let latin1string = "";
  for (let i = 0;i < array.length; i++) {
    latin1string += String.fromCodePoint(array[i]);
  }
  return btoa(latin1string);
}
function withoutTrailingSlash(url) {
  return url == null ? undefined : url.replace(/\/$/, "");
}

// node_modules/zod-to-json-schema/dist/esm/Options.js
var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
var defaultOptions = {
  name: undefined,
  $refStrategy: "root",
  basePath: ["#"],
  effectStrategy: "input",
  pipeStrategy: "all",
  dateStrategy: "format:date-time",
  mapStrategy: "entries",
  removeAdditionalStrategy: "passthrough",
  definitionPath: "definitions",
  target: "jsonSchema7",
  strictUnions: false,
  definitions: {},
  errorMessages: false,
  markdownDescription: false,
  patternStrategy: "escape",
  applyRegexFlags: false,
  emailStrategy: "format:email",
  base64Strategy: "contentEncoding:base64",
  nameStrategy: "ref"
};
var getDefaultOptions = (options) => typeof options === "string" ? {
  ...defaultOptions,
  name: options
} : {
  ...defaultOptions,
  ...options
};
// node_modules/zod-to-json-schema/dist/esm/Refs.js
var getRefs = (options) => {
  const _options = getDefaultOptions(options);
  const currentPath = _options.name !== undefined ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
  return {
    ..._options,
    currentPath,
    propertyPath: undefined,
    seen: new Map(Object.entries(_options.definitions).map(([name14, def]) => [
      def._def,
      {
        def: def._def,
        path: [..._options.basePath, _options.definitionPath, name14],
        jsonSchema: undefined
      }
    ]))
  };
};
// node_modules/zod-to-json-schema/dist/esm/errorMessages.js
function addErrorMessage(res, key, errorMessage, refs) {
  if (!refs?.errorMessages)
    return;
  if (errorMessage) {
    res.errorMessage = {
      ...res.errorMessage,
      [key]: errorMessage
    };
  }
}
function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
  res[key] = value;
  addErrorMessage(res, key, errorMessage, refs);
}
// node_modules/zod/lib/index.mjs
var util;
(function(util2) {
  util2.assertEqual = (val) => val;
  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(e) {
      return obj[e];
    });
  };
  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;
  };
  util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "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 = {}));
var objectUtil;
(function(objectUtil2) {
  objectUtil2.mergeShapes = (first, second) => {
    return {
      ...first,
      ...second
    };
  };
})(objectUtil || (objectUtil = {}));
var ZodParsedType = util.arrayToEnum([
  "string",
  "nan",
  "number",
  "integer",
  "float",
  "boolean",
  "date",
  "bigint",
  "symbol",
  "function",
  "undefined",
  "null",
  "array",
  "object",
  "unknown",
  "promise",
  "void",
  "never",
  "map",
  "set"
]);
var getParsedType = (data) => {
  const t = typeof data;
  switch (t) {
    case "undefined":
      return ZodParsedType.undefined;
    case "string":
      return ZodParsedType.string;
    case "number":
      return 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;
  }
};
var 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"
]);
var quotelessJson = (obj) => {
  const json = JSON.stringify(obj, null, 2);
  return json.replace(/"([^"]+)":/g, "$1:");
};

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) {
        fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
        fieldErrors[sub.path[0]].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;
};
var 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 === "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 };
};
var overrideErrorMap = errorMap;
function setErrorMap(map) {
  overrideErrorMap = map;
}
function getErrorMap() {
  return overrideErrorMap;
}
var makeIssue = (params) => {
  const { data, path, errorMaps, issueData } = params;
  const fullPath = [...path, ...issueData.path || []];
  const fullIssue = {
    ...issueData,
    path: fullPath
  };
  if (issueData.message !== undefined) {
    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
  };
};
var EMPTY_PATH = [];
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      ctx.schemaErrorMap,
      overrideMap,
      overrideMap === errorMap ? undefined : errorMap
    ].filter((x) => !!x)
  });
  ctx.common.issues.push(issue);
}

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 s of results) {
      if (s.status === "aborted")
        return INVALID;
      if (s.status === "dirty")
        status.dirty();
      arrayValue.push(s.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 };
  }
}
var INVALID = Object.freeze({
  status: "aborted"
});
var DIRTY = (value) => ({ status: "dirty", value });
var OK = (value) => ({ status: "valid", value });
var isAborted = (x) => x.status === "aborted";
var isDirty = (x) => x.status === "dirty";
var isValid = (x) => x.status === "valid";
var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
function __classPrivateFieldGet(receiver, state, kind, f) {
  if (kind === "a" && !f)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
  if (kind === "m")
    throw new TypeError("Private method is not writable");
  if (kind === "a" && !f)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
}
var errorUtil;
(function(errorUtil2) {
  errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === undefined ? undefined : message.message;
})(errorUtil || (errorUtil = {}));
var _ZodEnum_cache;
var _ZodNativeEnum_cache;

class ParseInputLazyPath {
  constructor(parent, value, path, key) {
    this._cachedPath = [];
    this.parent = parent;
    this.data = value;
    this._path = path;
    this._key = key;
  }
  get path() {
    if (!this._cachedPath.length) {
      if (this._key instanceof Array) {
        this._cachedPath.push(...this._path, ...this._key);
      } else {
        this._cachedPath.push(...this._path, this._key);
      }
    }
    return this._cachedPath;
  }
}
var 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;
      }
    };
  }
};
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) => {
    var _a15, _b;
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message !== null && message !== undefined ? message : ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: (_a15 = message !== null && message !== undefined ? message : required_error) !== null && _a15 !== undefined ? _a15 : ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: (_b = message !== null && message !== undefined ? message : invalid_type_error) !== null && _b !== undefined ? _b : ctx.defaultError };
  };
  return { errorMap: customMap, description };
}

class ZodType {
  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) {
    var _a15;
    const ctx = {
      common: {
        issues: [],
        async: (_a15 = params === null || params === undefined ? undefined : params.async) !== null && _a15 !== undefined ? _a15 : false,
        contextualErrorMap: params === null || params === undefined ? undefined : params.errorMap
      },
      path: (params === null || params === undefined ? undefined : 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) {
    var _a15, _b;
    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 ((_b = (_a15 = err === null || err === undefined ? undefined : err.message) === null || _a15 === undefined ? undefined : _a15.toLowerCase()) === null || _b === undefined ? undefined : _b.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 === null || params === undefined ? undefined : params.errorMap,
        async: true
      },
      path: (params === null || params === undefined ? undefined : 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(transform) {
    return new ZodEffects({
      ...processCreateParams(this._def),
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: { type: "transform", transform }
    });
  }
  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(undefined).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
}
var cuidRegex = /^c[^\s-]{8,}$/i;
var cuid2Regex = /^[0-9a-z]+$/;
var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
var 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;
var nanoidRegex = /^[a-z0-9_-]{21}$/i;
var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
var 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)?)??$/;
var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
var emojiRegex;
var 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])$/;
var 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])$/;
var 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]))$/;
var 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])$/;
var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
var 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])))`;
var dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
  let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
  if (args.precision) {
    regex = `${regex}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    regex = `${regex}(\\.\\d+)?`;
  }
  return regex;
}
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, version) {
  if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt, alg) {
  if (!jwtRegex.test(jwt))
    return false;
  try {
    const [header] = jwt.split(".");
    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 (!decoded.typ || !decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch (_a15) {
    return false;
  }
}
function isValidCidr(ip, version) {
  if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}

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 = undefined;
    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 (_a15) {
          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 (!base64Regex.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) {
    var _a15, _b;
    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 === null || options === undefined ? undefined : options.precision) === "undefined" ? null : options === null || options === undefined ? undefined : options.precision,
      offset: (_a15 = options === null || options === undefined ? undefined : options.offset) !== null && _a15 !== undefined ? _a15 : false,
      local: (_b = options === null || options === undefined ? undefined : options.local) !== null && _b !== undefined ? _b : false,
      ...errorUtil.errToObj(options === null || options === undefined ? undefined : 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 === null || options === undefined ? undefined : options.precision) === "undefined" ? null : options === null || options === undefined ? undefined : options.precision,
      ...errorUtil.errToObj(options === null || options === undefined ? undefined : 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 === null || options === undefined ? undefined : options.position,
      ...errorUtil.errToObj(options === null || options === undefined ? undefined : 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)
    });
  }
  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) => {
  var _a15;
  return new ZodString({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodString,
    coerce: (_a15 = params === null || params === undefined ? undefined : params.coerce) !== null && _a15 !== undefined ? _a15 : false,
    ...processCreateParams(params)
  });
};
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 = parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / Math.pow(10, decCount);
}

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 = undefined;
    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, 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 === null || params === undefined ? undefined : params.coerce) || false,
    ...processCreateParams(params)
  });
};

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 (_a15) {
        return this._getInvalidInput(input);
      }
    }
    const parsedType = this._getType(input);
    if (parsedType !== ZodParsedType.bigint) {
      return this._getInvalidInput(input);
    }
    let ctx = undefined;
    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) => {
  var _a15;
  return new ZodBigInt({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodBigInt,
    coerce: (_a15 = params === null || params === undefined ? undefined : params.coerce) !== null && _a15 !== undefined ? _a15 : false,
    ...processCreateParams(params)
  });
};

class ZodBoolean 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 === null || params === undefined ? undefined : params.coerce) || false,
    ...processCreateParams(params)
  });
};

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 (isNaN(input.data.getTime())) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_date
      });
      return INVALID;
    }
    const status = new ParseStatus;
    let ctx = undefined;
    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 === null || params === undefined ? undefined : params.coerce) || false,
    typeName: ZodFirstPartyTypeKind.ZodDate,
    ...processCreateParams(params)
  });
};

class ZodSymbol 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)
  });
};

class ZodUndefined 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)
  });
};

class ZodNull 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)
  });
};

class ZodAny 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)
  });
};

class ZodUnknown 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)
  });
};

class ZodNever 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)
  });
};

class ZodVoid 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)
  });
};

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 : undefined,
          maximum: tooBig ? def.exactLength.value : undefined,
          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)
  });
};
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;
  }
}

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);
    return this._cached = { shape, keys };
  }
  _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)),
          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 !== undefined ? {
        errorMap: (issue, ctx) => {
          var _a15, _b, _c, _d;
          const defaultError = (_c = (_b = (_a15 = this._def).errorMap) === null || _b === undefined ? undefined : _b.call(_a15, issue, ctx).message) !== null && _c !== undefined ? _c : ctx.defaultError;
          if (issue.code === "unrecognized_keys")
            return {
              message: (_d = errorUtil.errToObj(message).message) !== null && _d !== undefined ? _d : defaultError
            };
          return {
            message: defaultError
          };
        }
      } : {}
    });
  }
  strip() {
    return new ZodObject({
      ...this._def,
      unknownKeys: "strip"
    });
  }
  passthrough() {
    return new ZodObject({
      ...this._def,
      unknownKeys: "passthrough"
    });
  }
  extend(augmentation) {
    return new ZodObject({
      ...this._def,
      shape: () => ({
        ...this._def.shape(),
        ...augmentation
      })
    });
  }
  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;
  }
  setKey(key, schema) {
    return this.augment({ [key]: schema });
  }
  catchall(index) {
    return new ZodObject({
      ...this._def,
      catchall: index
    });
  }
  pick(mask) {
    const shape = {};
    util.objectKeys(mask).forEach((key) => {
      if (mask[key] && this.shape[key]) {
        shape[key] = this.shape[key];
      }
    });
    return new ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  omit(mask) {
    const shape = {};
    util.objectKeys(this.shape).forEach((key) => {
      if (!mask[key]) {
        shape[key] = this.shape[key];
      }
    });
    return new ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  deepPartial() {
    return deepPartialify(this);
  }
  partial(mask) {
    const newShape = {};
    util.objectKeys(this.shape).forEach((key) => {
      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 = {};
    util.objectKeys(this.shape).forEach((key) => {
      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)
  });
};

class ZodUnion 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 = undefined;
      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)
  });
};
var 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 [undefined];
  } else if (type instanceof ZodNull) {
    return [null];
  } else if (type instanceof ZodOptional) {
    return [undefined, ...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 [];
  }
};

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;
  }
  static create(discriminator, options, params) {
    const optionsMap = 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)
    });
  }
}
function mergeValues(a2, b) {
  const aType = getParsedType(a2);
  const bType = getParsedType(b);
  if (a2 === b) {
    return { valid: true, data: a2 };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b);
    const sharedKeys = util.objectKeys(a2).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a2, ...b };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a2[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 (a2.length !== b.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index = 0;index < a2.length; index++) {
      const itemA = a2[index];
      const itemB = b[index];
      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 && +a2 === +b) {
    return { valid: true, data: a2 };
  } else {
    return { valid: false };
  }
}

class ZodIntersection 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)
  });
};

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)
  });
};

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)
    });
  }
}

class ZodMap 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], index) => {
      return {
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
        value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
      };
    });
    if (ctx.common.async) {
      const finalMap = 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 = 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)
  });
};

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 = 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(size, message) {
    return this.min(size, message).max(size, 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)
  });
};

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(),
          errorMap
        ].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(),
          errorMap
        ].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((e) => {
          error.addIssue(makeArgsIssue(args, e));
          throw error;
        });
        const result = await Reflect.apply(fn, this, parsedArgs);
        const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
          error.addIssue(makeReturnsIssue(result, e));
          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)
    });
  }
}

class ZodLazy 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)
  });
};

class ZodLiteral 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)
  });
};
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}

class ZodEnum extends ZodType {
  constructor() {
    super(...arguments);
    _ZodEnum_cache.set(this, undefined);
  }
  _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 (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
      __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
    }
    if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").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_cache = new WeakMap;
ZodEnum.create = createZodEnum;

class ZodNativeEnum extends ZodType {
  constructor() {
    super(...arguments);
    _ZodNativeEnum_cache.set(this, undefined);
  }
  _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 (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
      __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
    }
    if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").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_cache = new WeakMap;
ZodNativeEnum.create = (values, params) => {
  return new ZodNativeEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
    ...processCreateParams(params)
  });
};

class ZodPromise 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)
  });
};

class ZodEffects 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 base = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (!isValid(base))
          return base;
        const result = effect.transform(base.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((base) => {
          if (!isValid(base))
            return base;
          return Promise.resolve(effect.transform(base.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)
  });
};

class ZodOptional extends ZodType {
  _parse(input) {
    const parsedType = this._getType(input);
    if (parsedType === ZodParsedType.undefined) {
      return OK(undefined);
    }
    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)
  });
};

class ZodNullable 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)
  });
};

class ZodDefault 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)
  });
};

class ZodCatch 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)
  });
};

class ZodNaN 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)
  });
};
var BRAND = Symbol("zod_brand");

class ZodBranded 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;
  }
}

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(a2, b) {
    return new ZodPipeline({
      in: a2,
      out: b,
      typeName: ZodFirstPartyTypeKind.ZodPipeline
    });
  }
}

class ZodReadonly 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)
  });
};
function custom(check, params = {}, fatal) {
  if (check)
    return ZodAny.create().superRefine((data, ctx) => {
      var _a15, _b;
      if (!check(data)) {
        const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params;
        const _fatal = (_b = (_a15 = p.fatal) !== null && _a15 !== undefined ? _a15 : fatal) !== null && _b !== undefined ? _b : true;
        const p2 = typeof p === "string" ? { message: p } : p;
        ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
      }
    });
  return ZodAny.create();
}
var late = {
  object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(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 = {}));
var instanceOfType = (cls, params = {
  message: `Input not instance of ${cls.name}`
}) => custom((data) => data instanceof cls, params);
var stringType = ZodString.create;
var numberType = ZodNumber.create;
var nanType = ZodNaN.create;
var bigIntType = ZodBigInt.create;
var booleanType = ZodBoolean.create;
var dateType = ZodDate.create;
var symbolType = ZodSymbol.create;
var undefinedType = ZodUndefined.create;
var nullType = ZodNull.create;
var anyType = ZodAny.create;
var unknownType = ZodUnknown.create;
var neverType = ZodNever.create;
var voidType = ZodVoid.create;
var arrayType = ZodArray.create;
var objectType = ZodObject.create;
var strictObjectType = ZodObject.strictCreate;
var unionType = ZodUnion.create;
var discriminatedUnionType = ZodDiscriminatedUnion.create;
var intersectionType = ZodIntersection.create;
var tupleType = ZodTuple.create;
var recordType = ZodRecord.create;
var mapType = ZodMap.create;
var setType = ZodSet.create;
var functionType = ZodFunction.create;
var lazyType = ZodLazy.create;
var literalType = ZodLiteral.create;
var enumType = ZodEnum.create;
var nativeEnumType = ZodNativeEnum.create;
var promiseType = ZodPromise.create;
var effectsType = ZodEffects.create;
var optionalType = ZodOptional.create;
var nullableType = ZodNullable.create;
var preprocessType = ZodEffects.createWithPreprocess;
var pipelineType = ZodPipeline.create;
var ostring = () => stringType().optional();
var onumber = () => numberType().optional();
var oboolean = () => booleanType().optional();
var 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 })
};
var NEVER = INVALID;
var z = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  defaultErrorMap: errorMap,
  setErrorMap,
  getErrorMap,
  makeIssue,
  EMPTY_PATH,
  addIssueToContext,
  ParseStatus,
  INVALID,
  DIRTY,
  OK,
  isAborted,
  isDirty,
  isValid,
  isAsync,
  get util() {
    return util;
  },
  get objectUtil() {
    return objectUtil;
  },
  ZodParsedType,
  getParsedType,
  ZodType,
  datetimeRegex,
  ZodString,
  ZodNumber,
  ZodBigInt,
  ZodBoolean,
  ZodDate,
  ZodSymbol,
  ZodUndefined,
  ZodNull,
  ZodAny,
  ZodUnknown,
  ZodNever,
  ZodVoid,
  ZodArray,
  ZodObject,
  ZodUnion,
  ZodDiscriminatedUnion,
  ZodIntersection,
  ZodTuple,
  ZodRecord,
  ZodMap,
  ZodSet,
  ZodFunction,
  ZodLazy,
  ZodLiteral,
  ZodEnum,
  ZodNativeEnum,
  ZodPromise,
  ZodEffects,
  ZodTransformer: ZodEffects,
  ZodOptional,
  ZodNullable,
  ZodDefault,
  ZodCatch,
  ZodNaN,
  BRAND,
  ZodBranded,
  ZodPipeline,
  ZodReadonly,
  custom,
  Schema: ZodType,
  ZodSchema: ZodType,
  late,
  get ZodFirstPartyTypeKind() {
    return ZodFirstPartyTypeKind;
  },
  coerce,
  any: anyType,
  array: arrayType,
  bigint: bigIntType,
  boolean: booleanType,
  date: dateType,
  discriminatedUnion: discriminatedUnionType,
  effect: effectsType,
  enum: enumType,
  function: functionType,
  instanceof: instanceOfType,
  intersection: intersectionType,
  lazy: lazyType,
  literal: literalType,
  map: mapType,
  nan: nanType,
  nativeEnum: nativeEnumType,
  never: neverType,
  null: nullType,
  nullable: nullableType,
  number: numberType,
  object: objectType,
  oboolean,
  onumber,
  optional: optionalType,
  ostring,
  pipeline: pipelineType,
  preprocess: preprocessType,
  promise: promiseType,
  record: recordType,
  set: setType,
  strictObject: strictObjectType,
  string: stringType,
  symbol: symbolType,
  transformer: effectsType,
  tuple: tupleType,
  undefined: undefinedType,
  union: unionType,
  unknown: unknownType,
  void: voidType,
  NEVER,
  ZodIssueCode,
  quotelessJson,
  ZodError
});

// node_modules/zod-to-json-schema/dist/esm/parsers/any.js
function parseAnyDef() {
  return {};
}

// node_modules/zod-to-json-schema/dist/esm/parsers/array.js
function parseArrayDef(def, refs) {
  const res = {
    type: "array"
  };
  if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {
    res.items = parseDef(def.type._def, {
      ...refs,
      currentPath: [...refs.currentPath, "items"]
    });
  }
  if (def.minLength) {
    setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
  }
  if (def.maxLength) {
    setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
  }
  if (def.exactLength) {
    setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
    setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
  }
  return res;
}

// node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
function parseBigintDef(def, refs) {
  const res = {
    type: "integer",
    format: "int64"
  };
  if (!def.checks)
    return res;
  for (const check of def.checks) {
    switch (check.kind) {
      case "min":
        if (refs.target === "jsonSchema7") {
          if (check.inclusive) {
            setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
          } else {
            setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
          }
        } else {
          if (!check.inclusive) {
            res.exclusiveMinimum = true;
          }
          setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
        }
        break;
      case "max":
        if (refs.target === "jsonSchema7") {
          if (check.inclusive) {
            setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
          } else {
            setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
          }
        } else {
          if (!check.inclusive) {
            res.exclusiveMaximum = true;
          }
          setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
        }
        break;
      case "multipleOf":
        setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
        break;
    }
  }
  return res;
}

// node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
function parseBooleanDef() {
  return {
    type: "boolean"
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
function parseBrandedDef(_def, refs) {
  return parseDef(_def.type._def, refs);
}

// node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
var parseCatchDef = (def, refs) => {
  return parseDef(def.innerType._def, refs);
};

// node_modules/zod-to-json-schema/dist/esm/parsers/date.js
function parseDateDef(def, refs, overrideDateStrategy) {
  const strategy = overrideDateStrategy ?? refs.dateStrategy;
  if (Array.isArray(strategy)) {
    return {
      anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
    };
  }
  switch (strategy) {
    case "string":
    case "format:date-time":
      return {
        type: "string",
        format: "date-time"
      };
    case "format:date":
      return {
        type: "string",
        format: "date"
      };
    case "integer":
      return integerDateParser(def, refs);
  }
}
var integerDateParser = (def, refs) => {
  const res = {
    type: "integer",
    format: "unix-time"
  };
  if (refs.target === "openApi3") {
    return res;
  }
  for (const check of def.checks) {
    switch (check.kind) {
      case "min":
        setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
        break;
      case "max":
        setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
        break;
    }
  }
  return res;
};

// node_modules/zod-to-json-schema/dist/esm/parsers/default.js
function parseDefaultDef(_def, refs) {
  return {
    ...parseDef(_def.innerType._def, refs),
    default: _def.defaultValue()
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
function parseEffectsDef(_def, refs) {
  return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : {};
}

// node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
function parseEnumDef(def) {
  return {
    type: "string",
    enum: Array.from(def.values)
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
var isJsonSchema7AllOfType = (type) => {
  if ("type" in type && type.type === "string")
    return false;
  return "allOf" in type;
};
function parseIntersectionDef(def, refs) {
  const allOf = [
    parseDef(def.left._def, {
      ...refs,
      currentPath: [...refs.currentPath, "allOf", "0"]
    }),
    parseDef(def.right._def, {
      ...refs,
      currentPath: [...refs.currentPath, "allOf", "1"]
    })
  ].filter((x) => !!x);
  let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : undefined;
  const mergedAllOf = [];
  allOf.forEach((schema) => {
    if (isJsonSchema7AllOfType(schema)) {
      mergedAllOf.push(...schema.allOf);
      if (schema.unevaluatedProperties === undefined) {
        unevaluatedProperties = undefined;
      }
    } else {
      let nestedSchema = schema;
      if ("additionalProperties" in schema && schema.additionalProperties === false) {
        const { additionalProperties, ...rest } = schema;
        nestedSchema = rest;
      } else {
        unevaluatedProperties = undefined;
      }
      mergedAllOf.push(nestedSchema);
    }
  });
  return mergedAllOf.length ? {
    allOf: mergedAllOf,
    ...unevaluatedProperties
  } : undefined;
}

// node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
function parseLiteralDef(def, refs) {
  const parsedType = typeof def.value;
  if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
    return {
      type: Array.isArray(def.value) ? "array" : "object"
    };
  }
  if (refs.target === "openApi3") {
    return {
      type: parsedType === "bigint" ? "integer" : parsedType,
      enum: [def.value]
    };
  }
  return {
    type: parsedType === "bigint" ? "integer" : parsedType,
    const: def.value
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/string.js
var emojiRegex2 = undefined;
var zodPatterns = {
  cuid: /^[cC][^\s-]{8,}$/,
  cuid2: /^[0-9a-z]+$/,
  ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
  email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
  emoji: () => {
    if (emojiRegex2 === undefined) {
      emojiRegex2 = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
    }
    return emojiRegex2;
  },
  uuid: /^[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}$/,
  ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
  ipv4Cidr: /^(?:(?: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])$/,
  ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
  ipv6Cidr: /^(([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])$/,
  base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
  base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
  nanoid: /^[a-zA-Z0-9_-]{21}$/,
  jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
};
function parseStringDef(def, refs) {
  const res = {
    type: "string"
  };
  if (def.checks) {
    for (const check of def.checks) {
      switch (check.kind) {
        case "min":
          setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
          break;
        case "max":
          setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
          break;
        case "email":
          switch (refs.emailStrategy) {
            case "format:email":
              addFormat(res, "email", check.message, refs);
              break;
            case "format:idn-email":
              addFormat(res, "idn-email", check.message, refs);
              break;
            case "pattern:zod":
              addPattern(res, zodPatterns.email, check.message, refs);
              break;
          }
          break;
        case "url":
          addFormat(res, "uri", check.message, refs);
          break;
        case "uuid":
          addFormat(res, "uuid", check.message, refs);
          break;
        case "regex":
          addPattern(res, check.regex, check.message, refs);
          break;
        case "cuid":
          addPattern(res, zodPatterns.cuid, check.message, refs);
          break;
        case "cuid2":
          addPattern(res, zodPatterns.cuid2, check.message, refs);
          break;
        case "startsWith":
          addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
          break;
        case "endsWith":
          addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
          break;
        case "datetime":
          addFormat(res, "date-time", check.message, refs);
          break;
        case "date":
          addFormat(res, "date", check.message, refs);
          break;
        case "time":
          addFormat(res, "time", check.message, refs);
          break;
        case "duration":
          addFormat(res, "duration", check.message, refs);
          break;
        case "length":
          setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
          setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
          break;
        case "includes": {
          addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
          break;
        }
        case "ip": {
          if (check.version !== "v6") {
            addFormat(res, "ipv4", check.message, refs);
          }
          if (check.version !== "v4") {
            addFormat(res, "ipv6", check.message, refs);
          }
          break;
        }
        case "base64url":
          addPattern(res, zodPatterns.base64url, check.message, refs);
          break;
        case "jwt":
          addPattern(res, zodPatterns.jwt, check.message, refs);
          break;
        case "cidr": {
          if (check.version !== "v6") {
            addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
          }
          if (check.version !== "v4") {
            addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
          }
          break;
        }
        case "emoji":
          addPattern(res, zodPatterns.emoji(), check.message, refs);
          break;
        case "ulid": {
          addPattern(res, zodPatterns.ulid, check.message, refs);
          break;
        }
        case "base64": {
          switch (refs.base64Strategy) {
            case "format:binary": {
              addFormat(res, "binary", check.message, refs);
              break;
            }
            case "contentEncoding:base64": {
              setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
              break;
            }
            case "pattern:zod": {
              addPattern(res, zodPatterns.base64, check.message, refs);
              break;
            }
          }
          break;
        }
        case "nanoid": {
          addPattern(res, zodPatterns.nanoid, check.message, refs);
        }
        case "toLowerCase":
        case "toUpperCase":
        case "trim":
          break;
        default:
          ((_) => {
          })(check);
      }
    }
  }
  return res;
}
function escapeLiteralCheckValue(literal, refs) {
  return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
}
var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
function escapeNonAlphaNumeric(source) {
  let result = "";
  for (let i = 0;i < source.length; i++) {
    if (!ALPHA_NUMERIC.has(source[i])) {
      result += "\\";
    }
    result += source[i];
  }
  return result;
}
function addFormat(schema, value, message, refs) {
  if (schema.format || schema.anyOf?.some((x) => x.format)) {
    if (!schema.anyOf) {
      schema.anyOf = [];
    }
    if (schema.format) {
      schema.anyOf.push({
        format: schema.format,
        ...schema.errorMessage && refs.errorMessages && {
          errorMessage: { format: schema.errorMessage.format }
        }
      });
      delete schema.format;
      if (schema.errorMessage) {
        delete schema.errorMessage.format;
        if (Object.keys(schema.errorMessage).length === 0) {
          delete schema.errorMessage;
        }
      }
    }
    schema.anyOf.push({
      format: value,
      ...message && refs.errorMessages && { errorMessage: { format: message } }
    });
  } else {
    setResponseValueAndErrors(schema, "format", value, message, refs);
  }
}
function addPattern(schema, regex, message, refs) {
  if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
    if (!schema.allOf) {
      schema.allOf = [];
    }
    if (schema.pattern) {
      schema.allOf.push({
        pattern: schema.pattern,
        ...schema.errorMessage && refs.errorMessages && {
          errorMessage: { pattern: schema.errorMessage.pattern }
        }
      });
      delete schema.pattern;
      if (schema.errorMessage) {
        delete schema.errorMessage.pattern;
        if (Object.keys(schema.errorMessage).length === 0) {
          delete schema.errorMessage;
        }
      }
    }
    schema.allOf.push({
      pattern: stringifyRegExpWithFlags(regex, refs),
      ...message && refs.errorMessages && { errorMessage: { pattern: message } }
    });
  } else {
    setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
  }
}
function stringifyRegExpWithFlags(regex, refs) {
  if (!refs.applyRegexFlags || !regex.flags) {
    return regex.source;
  }
  const flags = {
    i: regex.flags.includes("i"),
    m: regex.flags.includes("m"),
    s: regex.flags.includes("s")
  };
  const source = flags.i ? regex.source.toLowerCase() : regex.source;
  let pattern = "";
  let isEscaped = false;
  let inCharGroup = false;
  let inCharRange = false;
  for (let i = 0;i < source.length; i++) {
    if (isEscaped) {
      pattern += source[i];
      isEscaped = false;
      continue;
    }
    if (flags.i) {
      if (inCharGroup) {
        if (source[i].match(/[a-z]/)) {
          if (inCharRange) {
            pattern += source[i];
            pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
            inCharRange = false;
          } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {
            pattern += source[i];
            inCharRange = true;
          } else {
            pattern += `${source[i]}${source[i].toUpperCase()}`;
          }
          continue;
        }
      } else if (source[i].match(/[a-z]/)) {
        pattern += `[${source[i]}${source[i].toUpperCase()}]`;
        continue;
      }
    }
    if (flags.m) {
      if (source[i] === "^") {
        pattern += `(^|(?<=[\r
]))`;
        continue;
      } else if (source[i] === "$") {
        pattern += `($|(?=[\r
]))`;
        continue;
      }
    }
    if (flags.s && source[i] === ".") {
      pattern += inCharGroup ? `${source[i]}\r
` : `[${source[i]}\r
]`;
      continue;
    }
    pattern += source[i];
    if (source[i] === "\\") {
      isEscaped = true;
    } else if (inCharGroup && source[i] === "]") {
      inCharGroup = false;
    } else if (!inCharGroup && source[i] === "[") {
      inCharGroup = true;
    }
  }
  try {
    new RegExp(pattern);
  } catch {
    console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
    return regex.source;
  }
  return pattern;
}

// node_modules/zod-to-json-schema/dist/esm/parsers/record.js
function parseRecordDef(def, refs) {
  if (refs.target === "openAi") {
    console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
  }
  if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
    return {
      type: "object",
      required: def.keyType._def.values,
      properties: def.keyType._def.values.reduce((acc, key) => ({
        ...acc,
        [key]: parseDef(def.valueType._def, {
          ...refs,
          currentPath: [...refs.currentPath, "properties", key]
        }) ?? {}
      }), {}),
      additionalProperties: false
    };
  }
  const schema = {
    type: "object",
    additionalProperties: parseDef(def.valueType._def, {
      ...refs,
      currentPath: [...refs.currentPath, "additionalProperties"]
    }) ?? {}
  };
  if (refs.target === "openApi3") {
    return schema;
  }
  if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
    const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
    return {
      ...schema,
      propertyNames: keyType
    };
  } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {
    return {
      ...schema,
      propertyNames: {
        enum: def.keyType._def.values
      }
    };
  } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {
    const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
    return {
      ...schema,
      propertyNames: keyType
    };
  }
  return schema;
}

// node_modules/zod-to-json-schema/dist/esm/parsers/map.js
function parseMapDef(def, refs) {
  if (refs.mapStrategy === "record") {
    return parseRecordDef(def, refs);
  }
  const keys = parseDef(def.keyType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "items", "items", "0"]
  }) || {};
  const values = parseDef(def.valueType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "items", "items", "1"]
  }) || {};
  return {
    type: "array",
    maxItems: 125,
    items: {
      type: "array",
      items: [keys, values],
      minItems: 2,
      maxItems: 2
    }
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
function parseNativeEnumDef(def) {
  const object = def.values;
  const actualKeys = Object.keys(def.values).filter((key) => {
    return typeof object[object[key]] !== "number";
  });
  const actualValues = actualKeys.map((key) => object[key]);
  const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
  return {
    type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
    enum: actualValues
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/never.js
function parseNeverDef() {
  return {
    not: {}
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/null.js
function parseNullDef(refs) {
  return refs.target === "openApi3" ? {
    enum: ["null"],
    nullable: true
  } : {
    type: "null"
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/union.js
var primitiveMappings = {
  ZodString: "string",
  ZodNumber: "number",
  ZodBigInt: "integer",
  ZodBoolean: "boolean",
  ZodNull: "null"
};
function parseUnionDef(def, refs) {
  if (refs.target === "openApi3")
    return asAnyOf(def, refs);
  const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
  if (options.every((x) => (x._def.typeName in primitiveMappings) && (!x._def.checks || !x._def.checks.length))) {
    const types = options.reduce((types2, x) => {
      const type = primitiveMappings[x._def.typeName];
      return type && !types2.includes(type) ? [...types2, type] : types2;
    }, []);
    return {
      type: types.length > 1 ? types : types[0]
    };
  } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
    const types = options.reduce((acc, x) => {
      const type = typeof x._def.value;
      switch (type) {
        case "string":
        case "number":
        case "boolean":
          return [...acc, type];
        case "bigint":
          return [...acc, "integer"];
        case "object":
          if (x._def.value === null)
            return [...acc, "null"];
        case "symbol":
        case "undefined":
        case "function":
        default:
          return acc;
      }
    }, []);
    if (types.length === options.length) {
      const uniqueTypes = types.filter((x, i, a2) => a2.indexOf(x) === i);
      return {
        type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
        enum: options.reduce((acc, x) => {
          return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
        }, [])
      };
    }
  } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
    return {
      type: "string",
      enum: options.reduce((acc, x) => [
        ...acc,
        ...x._def.values.filter((x2) => !acc.includes(x2))
      ], [])
    };
  }
  return asAnyOf(def, refs);
}
var asAnyOf = (def, refs) => {
  const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {
    ...refs,
    currentPath: [...refs.currentPath, "anyOf", `${i}`]
  })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
  return anyOf.length ? { anyOf } : undefined;
};

// node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
function parseNullableDef(def, refs) {
  if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
    if (refs.target === "openApi3") {
      return {
        type: primitiveMappings[def.innerType._def.typeName],
        nullable: true
      };
    }
    return {
      type: [
        primitiveMappings[def.innerType._def.typeName],
        "null"
      ]
    };
  }
  if (refs.target === "openApi3") {
    const base2 = parseDef(def.innerType._def, {
      ...refs,
      currentPath: [...refs.currentPath]
    });
    if (base2 && "$ref" in base2)
      return { allOf: [base2], nullable: true };
    return base2 && { ...base2, nullable: true };
  }
  const base = parseDef(def.innerType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "anyOf", "0"]
  });
  return base && { anyOf: [base, { type: "null" }] };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/number.js
function parseNumberDef(def, refs) {
  const res = {
    type: "number"
  };
  if (!def.checks)
    return res;
  for (const check of def.checks) {
    switch (check.kind) {
      case "int":
        res.type = "integer";
        addErrorMessage(res, "type", check.message, refs);
        break;
      case "min":
        if (refs.target === "jsonSchema7") {
          if (check.inclusive) {
            setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
          } else {
            setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
          }
        } else {
          if (!check.inclusive) {
            res.exclusiveMinimum = true;
          }
          setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
        }
        break;
      case "max":
        if (refs.target === "jsonSchema7") {
          if (check.inclusive) {
            setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
          } else {
            setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
          }
        } else {
          if (!check.inclusive) {
            res.exclusiveMaximum = true;
          }
          setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
        }
        break;
      case "multipleOf":
        setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
        break;
    }
  }
  return res;
}

// node_modules/zod-to-json-schema/dist/esm/parsers/object.js
function decideAdditionalProperties(def, refs) {
  if (refs.removeAdditionalStrategy === "strict") {
    return def.catchall._def.typeName === "ZodNever" ? def.unknownKeys !== "strict" : parseDef(def.catchall._def, {
      ...refs,
      currentPath: [...refs.currentPath, "additionalProperties"]
    }) ?? true;
  } else {
    return def.catchall._def.typeName === "ZodNever" ? def.unknownKeys === "passthrough" : parseDef(def.catchall._def, {
      ...refs,
      currentPath: [...refs.currentPath, "additionalProperties"]
    }) ?? true;
  }
}
function parseObjectDef(def, refs) {
  const forceOptionalIntoNullable = refs.target === "openAi";
  const result = {
    type: "object",
    ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => {
      if (propDef === undefined || propDef._def === undefined)
        return acc;
      let propOptional = propDef.isOptional();
      if (propOptional && forceOptionalIntoNullable) {
        if (propDef instanceof ZodOptional) {
          propDef = propDef._def.innerType;
        }
        if (!propDef.isNullable()) {
          propDef = propDef.nullable();
        }
        propOptional = false;
      }
      const parsedDef = parseDef(propDef._def, {
        ...refs,
        currentPath: [...refs.currentPath, "properties", propName],
        propertyPath: [...refs.currentPath, "properties", propName]
      });
      if (parsedDef === undefined)
        return acc;
      return {
        properties: { ...acc.properties, [propName]: parsedDef },
        required: propOptional ? acc.required : [...acc.required, propName]
      };
    }, { properties: {}, required: [] }),
    additionalProperties: decideAdditionalProperties(def, refs)
  };
  if (!result.required.length)
    delete result.required;
  return result;
}

// node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
var parseOptionalDef = (def, refs) => {
  if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
    return parseDef(def.innerType._def, refs);
  }
  const innerSchema = parseDef(def.innerType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "anyOf", "1"]
  });
  return innerSchema ? {
    anyOf: [
      {
        not: {}
      },
      innerSchema
    ]
  } : {};
};

// node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
var parsePipelineDef = (def, refs) => {
  if (refs.pipeStrategy === "input") {
    return parseDef(def.in._def, refs);
  } else if (refs.pipeStrategy === "output") {
    return parseDef(def.out._def, refs);
  }
  const a2 = parseDef(def.in._def, {
    ...refs,
    currentPath: [...refs.currentPath, "allOf", "0"]
  });
  const b = parseDef(def.out._def, {
    ...refs,
    currentPath: [...refs.currentPath, "allOf", a2 ? "1" : "0"]
  });
  return {
    allOf: [a2, b].filter((x) => x !== undefined)
  };
};

// node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
function parsePromiseDef(def, refs) {
  return parseDef(def.type._def, refs);
}

// node_modules/zod-to-json-schema/dist/esm/parsers/set.js
function parseSetDef(def, refs) {
  const items = parseDef(def.valueType._def, {
    ...refs,
    currentPath: [...refs.currentPath, "items"]
  });
  const schema = {
    type: "array",
    uniqueItems: true,
    items
  };
  if (def.minSize) {
    setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
  }
  if (def.maxSize) {
    setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
  }
  return schema;
}

// node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
function parseTupleDef(def, refs) {
  if (def.rest) {
    return {
      type: "array",
      minItems: def.items.length,
      items: def.items.map((x, i) => parseDef(x._def, {
        ...refs,
        currentPath: [...refs.currentPath, "items", `${i}`]
      })).reduce((acc, x) => x === undefined ? acc : [...acc, x], []),
      additionalItems: parseDef(def.rest._def, {
        ...refs,
        currentPath: [...refs.currentPath, "additionalItems"]
      })
    };
  } else {
    return {
      type: "array",
      minItems: def.items.length,
      maxItems: def.items.length,
      items: def.items.map((x, i) => parseDef(x._def, {
        ...refs,
        currentPath: [...refs.currentPath, "items", `${i}`]
      })).reduce((acc, x) => x === undefined ? acc : [...acc, x], [])
    };
  }
}

// node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
function parseUndefinedDef() {
  return {
    not: {}
  };
}

// node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
function parseUnknownDef() {
  return {};
}

// node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
var parseReadonlyDef = (def, refs) => {
  return parseDef(def.innerType._def, refs);
};

// node_modules/zod-to-json-schema/dist/esm/parseDef.js
function parseDef(def, refs, forceResolution = false) {
  const seenItem = refs.seen.get(def);
  if (refs.override) {
    const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
    if (overrideResult !== ignoreOverride) {
      return overrideResult;
    }
  }
  if (seenItem && !forceResolution) {
    const seenSchema = get$ref(seenItem, refs);
    if (seenSchema !== undefined) {
      return seenSchema;
    }
  }
  const newItem = { def, path: refs.currentPath, jsonSchema: undefined };
  refs.seen.set(def, newItem);
  const jsonSchema = selectParser(def, def.typeName, refs);
  if (jsonSchema) {
    addMeta(def, refs, jsonSchema);
  }
  newItem.jsonSchema = jsonSchema;
  return jsonSchema;
}
var get$ref = (item, refs) => {
  switch (refs.$refStrategy) {
    case "root":
      return { $ref: item.path.join("/") };
    case "relative":
      return { $ref: getRelativePath(refs.currentPath, item.path) };
    case "none":
    case "seen": {
      if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
        console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
        return {};
      }
      return refs.$refStrategy === "seen" ? {} : undefined;
    }
  }
};
var getRelativePath = (pathA, pathB) => {
  let i = 0;
  for (;i < pathA.length && i < pathB.length; i++) {
    if (pathA[i] !== pathB[i])
      break;
  }
  return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
};
var selectParser = (def, typeName, refs) => {
  switch (typeName) {
    case ZodFirstPartyTypeKind.ZodString:
      return parseStringDef(def, refs);
    case ZodFirstPartyTypeKind.ZodNumber:
      return parseNumberDef(def, refs);
    case ZodFirstPartyTypeKind.ZodObject:
      return parseObjectDef(def, refs);
    case ZodFirstPartyTypeKind.ZodBigInt:
      return parseBigintDef(def, refs);
    case ZodFirstPartyTypeKind.ZodBoolean:
      return parseBooleanDef();
    case ZodFirstPartyTypeKind.ZodDate:
      return parseDateDef(def, refs);
    case ZodFirstPartyTypeKind.ZodUndefined:
      return parseUndefinedDef();
    case ZodFirstPartyTypeKind.ZodNull:
      return parseNullDef(refs);
    case ZodFirstPartyTypeKind.ZodArray:
      return parseArrayDef(def, refs);
    case ZodFirstPartyTypeKind.ZodUnion:
    case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
      return parseUnionDef(def, refs);
    case ZodFirstPartyTypeKind.ZodIntersection:
      return parseIntersectionDef(def, refs);
    case ZodFirstPartyTypeKind.ZodTuple:
      return parseTupleDef(def, refs);
    case ZodFirstPartyTypeKind.ZodRecord:
      return parseRecordDef(def, refs);
    case ZodFirstPartyTypeKind.ZodLiteral:
      return parseLiteralDef(def, refs);
    case ZodFirstPartyTypeKind.ZodEnum:
      return parseEnumDef(def);
    case ZodFirstPartyTypeKind.ZodNativeEnum:
      return parseNativeEnumDef(def);
    case ZodFirstPartyTypeKind.ZodNullable:
      return parseNullableDef(def, refs);
    case ZodFirstPartyTypeKind.ZodOptional:
      return parseOptionalDef(def, refs);
    case ZodFirstPartyTypeKind.ZodMap:
      return parseMapDef(def, refs);
    case ZodFirstPartyTypeKind.ZodSet:
      return parseSetDef(def, refs);
    case ZodFirstPartyTypeKind.ZodLazy:
      return parseDef(def.getter()._def, refs);
    case ZodFirstPartyTypeKind.ZodPromise:
      return parsePromiseDef(def, refs);
    case ZodFirstPartyTypeKind.ZodNaN:
    case ZodFirstPartyTypeKind.ZodNever:
      return parseNeverDef();
    case ZodFirstPartyTypeKind.ZodEffects:
      return parseEffectsDef(def, refs);
    case ZodFirstPartyTypeKind.ZodAny:
      return parseAnyDef();
    case ZodFirstPartyTypeKind.ZodUnknown:
      return parseUnknownDef();
    case ZodFirstPartyTypeKind.ZodDefault:
      return parseDefaultDef(def, refs);
    case ZodFirstPartyTypeKind.ZodBranded:
      return parseBrandedDef(def, refs);
    case ZodFirstPartyTypeKind.ZodReadonly:
      return parseReadonlyDef(def, refs);
    case ZodFirstPartyTypeKind.ZodCatch:
      return parseCatchDef(def, refs);
    case ZodFirstPartyTypeKind.ZodPipeline:
      return parsePipelineDef(def, refs);
    case ZodFirstPartyTypeKind.ZodFunction:
    case ZodFirstPartyTypeKind.ZodVoid:
    case ZodFirstPartyTypeKind.ZodSymbol:
      return;
    default:
      return ((_) => {
        return;
      })(typeName);
  }
};
var addMeta = (def, refs, jsonSchema) => {
  if (def.description) {
    jsonSchema.description = def.description;
    if (refs.markdownDescription) {
      jsonSchema.markdownDescription = def.description;
    }
  }
  return jsonSchema;
};
// node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
var zodToJsonSchema = (schema, options) => {
  const refs = getRefs(options);
  const definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name15, schema2]) => ({
    ...acc,
    [name15]: parseDef(schema2._def, {
      ...refs,
      currentPath: [...refs.basePath, refs.definitionPath, name15]
    }, true) ?? {}
  }), {}) : undefined;
  const name14 = typeof options === "string" ? options : options?.nameStrategy === "title" ? undefined : options?.name;
  const main = parseDef(schema._def, name14 === undefined ? refs : {
    ...refs,
    currentPath: [...refs.basePath, refs.definitionPath, name14]
  }, false) ?? {};
  const title = typeof options === "object" && options.name !== undefined && options.nameStrategy === "title" ? options.name : undefined;
  if (title !== undefined) {
    main.title = title;
  }
  const combined = name14 === undefined ? definitions ? {
    ...main,
    [refs.definitionPath]: definitions
  } : main : {
    $ref: [
      ...refs.$refStrategy === "relative" ? [] : refs.basePath,
      refs.definitionPath,
      name14
    ].join("/"),
    [refs.definitionPath]: {
      ...definitions,
      [name14]: main
    }
  };
  if (refs.target === "jsonSchema7") {
    combined.$schema = "http://json-schema.org/draft-07/schema#";
  } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
    combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
  }
  if (refs.target === "openAi" && (("anyOf" in combined) || ("oneOf" in combined) || ("allOf" in combined) || ("type" in combined) && Array.isArray(combined.type))) {
    console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
  }
  return combined;
};
// node_modules/zod-to-json-schema/dist/esm/index.js
var esm_default = zodToJsonSchema;

// node_modules/@ai-sdk/ui-utils/dist/index.mjs
var textStreamPart = {
  code: "0",
  name: "text",
  parse: (value) => {
    if (typeof value !== "string") {
      throw new Error('"text" parts expect a string value.');
    }
    return { type: "text", value };
  }
};
var errorStreamPart = {
  code: "3",
  name: "error",
  parse: (value) => {
    if (typeof value !== "string") {
      throw new Error('"error" parts expect a string value.');
    }
    return { type: "error", value };
  }
};
var assistantMessageStreamPart = {
  code: "4",
  name: "assistant_message",
  parse: (value) => {
    if (value == null || typeof value !== "object" || !("id" in value) || !("role" in value) || !("content" in value) || typeof value.id !== "string" || typeof value.role !== "string" || value.role !== "assistant" || !Array.isArray(value.content) || !value.content.every((item) => item != null && typeof item === "object" && ("type" in item) && item.type === "text" && ("text" in item) && item.text != null && typeof item.text === "object" && ("value" in item.text) && typeof item.text.value === "string")) {
      throw new Error('"assistant_message" parts expect an object with an "id", "role", and "content" property.');
    }
    return {
      type: "assistant_message",
      value
    };
  }
};
var assistantControlDataStreamPart = {
  code: "5",
  name: "assistant_control_data",
  parse: (value) => {
    if (value == null || typeof value !== "object" || !("threadId" in value) || !("messageId" in value) || typeof value.threadId !== "string" || typeof value.messageId !== "string") {
      throw new Error('"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.');
    }
    return {
      type: "assistant_control_data",
      value: {
        threadId: value.threadId,
        messageId: value.messageId
      }
    };
  }
};
var dataMessageStreamPart = {
  code: "6",
  name: "data_message",
  parse: (value) => {
    if (value == null || typeof value !== "object" || !("role" in value) || !("data" in value) || typeof value.role !== "string" || value.role !== "data") {
      throw new Error('"data_message" parts expect an object with a "role" and "data" property.');
    }
    return {
      type: "data_message",
      value
    };
  }
};
var assistantStreamParts = [
  textStreamPart,
  errorStreamPart,
  assistantMessageStreamPart,
  assistantControlDataStreamPart,
  dataMessageStreamPart
];
var assistantStreamPartsByCode = {
  [textStreamPart.code]: textStreamPart,
  [errorStreamPart.code]: errorStreamPart,
  [assistantMessageStreamPart.code]: assistantMessageStreamPart,
  [assistantControlDataStreamPart.code]: assistantControlDataStreamPart,
  [dataMessageStreamPart.code]: dataMessageStreamPart
};
var StreamStringPrefixes = {
  [textStreamPart.name]: textStreamPart.code,
  [errorStreamPart.name]: errorStreamPart.code,
  [assistantMessageStreamPart.name]: assistantMessageStreamPart.code,
  [assistantControlDataStreamPart.name]: assistantControlDataStreamPart.code,
  [dataMessageStreamPart.name]: dataMessageStreamPart.code
};
var validCodes = assistantStreamParts.map((part) => part.code);
var textStreamPart2 = {
  code: "0",
  name: "text",
  parse: (value) => {
    if (typeof value !== "string") {
      throw new Error('"text" parts expect a string value.');
    }
    return { type: "text", value };
  }
};
var dataStreamPart = {
  code: "2",
  name: "data",
  parse: (value) => {
    if (!Array.isArray(value)) {
      throw new Error('"data" parts expect an array value.');
    }
    return { type: "data", value };
  }
};
var errorStreamPart2 = {
  code: "3",
  name: "error",
  parse: (value) => {
    if (typeof value !== "string") {
      throw new Error('"error" parts expect a string value.');
    }
    return { type: "error", value };
  }
};
var messageAnnotationsStreamPart = {
  code: "8",
  name: "message_annotations",
  parse: (value) => {
    if (!Array.isArray(value)) {
      throw new Error('"message_annotations" parts expect an array value.');
    }
    return { type: "message_annotations", value };
  }
};
var toolCallStreamPart = {
  code: "9",
  name: "tool_call",
  parse: (value) => {
    if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string" || !("args" in value) || typeof value.args !== "object") {
      throw new Error('"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.');
    }
    return {
      type: "tool_call",
      value
    };
  }
};
var toolResultStreamPart = {
  code: "a",
  name: "tool_result",
  parse: (value) => {
    if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("result" in value)) {
      throw new Error('"tool_result" parts expect an object with a "toolCallId" and a "result" property.');
    }
    return {
      type: "tool_result",
      value
    };
  }
};
var toolCallStreamingStartStreamPart = {
  code: "b",
  name: "tool_call_streaming_start",
  parse: (value) => {
    if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("toolName" in value) || typeof value.toolName !== "string") {
      throw new Error('"tool_call_streaming_start" parts expect an object with a "toolCallId" and "toolName" property.');
    }
    return {
      type: "tool_call_streaming_start",
      value
    };
  }
};
var toolCallDeltaStreamPart = {
  code: "c",
  name: "tool_call_delta",
  parse: (value) => {
    if (value == null || typeof value !== "object" || !("toolCallId" in value) || typeof value.toolCallId !== "string" || !("argsTextDelta" in value) || typeof value.argsTextDelta !== "string") {
      throw new Error('"tool_call_delta" parts expect an object with a "toolCallId" and "argsTextDelta" property.');
    }
    return {
      type: "tool_call_delta",
      value
    };
  }
};
var finishMessageStreamPart = {
  code: "d",
  name: "finish_message",
  parse: (value) => {
    if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") {
      throw new Error('"finish_message" parts expect an object with a "finishReason" property.');
    }
    const result = {
      finishReason: value.finishReason
    };
    if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) {
      result.usage = {
        promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : Number.NaN,
        completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : Number.NaN
      };
    }
    return {
      type: "finish_message",
      value: result
    };
  }
};
var finishStepStreamPart = {
  code: "e",
  name: "finish_step",
  parse: (value) => {
    if (value == null || typeof value !== "object" || !("finishReason" in value) || typeof value.finishReason !== "string") {
      throw new Error('"finish_step" parts expect an object with a "finishReason" property.');
    }
    const result = {
      finishReason: value.finishReason,
      isContinued: false
    };
    if ("usage" in value && value.usage != null && typeof value.usage === "object" && "promptTokens" in value.usage && "completionTokens" in value.usage) {
      result.usage = {
        promptTokens: typeof value.usage.promptTokens === "number" ? value.usage.promptTokens : Number.NaN,
        completionTokens: typeof value.usage.completionTokens === "number" ? value.usage.completionTokens : Number.NaN
      };
    }
    if ("isContinued" in value && typeof value.isContinued === "boolean") {
      result.isContinued = value.isContinued;
    }
    return {
      type: "finish_step",
      value: result
    };
  }
};
var dataStreamParts = [
  textStreamPart2,
  dataStreamPart,
  errorStreamPart2,
  messageAnnotationsStreamPart,
  toolCallStreamPart,
  toolResultStreamPart,
  toolCallStreamingStartStreamPart,
  toolCallDeltaStreamPart,
  finishMessageStreamPart,
  finishStepStreamPart
];
var dataStreamPartsByCode = {
  [textStreamPart2.code]: textStreamPart2,
  [dataStreamPart.code]: dataStreamPart,
  [errorStreamPart2.code]: errorStreamPart2,
  [messageAnnotationsStreamPart.code]: messageAnnotationsStreamPart,
  [toolCallStreamPart.code]: toolCallStreamPart,
  [toolResultStreamPart.code]: toolResultStreamPart,
  [toolCallStreamingStartStreamPart.code]: toolCallStreamingStartStreamPart,
  [toolCallDeltaStreamPart.code]: toolCallDeltaStreamPart,
  [finishMessageStreamPart.code]: finishMessageStreamPart,
  [finishStepStreamPart.code]: finishStepStreamPart
};
var DataStreamStringPrefixes = {
  [textStreamPart2.name]: textStreamPart2.code,
  [dataStreamPart.name]: dataStreamPart.code,
  [errorStreamPart2.name]: errorStreamPart2.code,
  [messageAnnotationsStreamPart.name]: messageAnnotationsStreamPart.code,
  [toolCallStreamPart.name]: toolCallStreamPart.code,
  [toolResultStreamPart.name]: toolResultStreamPart.code,
  [toolCallStreamingStartStreamPart.name]: toolCallStreamingStartStreamPart.code,
  [toolCallDeltaStreamPart.name]: toolCallDeltaStreamPart.code,
  [finishMessageStreamPart.name]: finishMessageStreamPart.code,
  [finishStepStreamPart.name]: finishStepStreamPart.code
};
var validCodes2 = dataStreamParts.map((part) => part.code);
function formatDataStreamPart(type, value) {
  const streamPart = dataStreamParts.find((part) => part.name === type);
  if (!streamPart) {
    throw new Error(`Invalid stream part type: ${type}`);
  }
  return `${streamPart.code}:${JSON.stringify(value)}
`;
}
var schemaSymbol = Symbol.for("vercel.ai.schema");
function jsonSchema(jsonSchema2, {
  validate
} = {}) {
  return {
    [schemaSymbol]: true,
    _type: undefined,
    [validatorSymbol]: true,
    jsonSchema: jsonSchema2,
    validate
  };
}
function isSchema(value) {
  return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
}
function asSchema(schema) {
  return isSchema(schema) ? schema : zodSchema(schema);
}
function zodSchema(zodSchema2) {
  return jsonSchema(esm_default(zodSchema2), {
    validate: (value) => {
      const result = zodSchema2.safeParse(value);
      return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
    }
  });
}

// node_modules/ai/dist/index.mjs
var import_api = __toESM(require_src(), 1);
var import_api2 = __toESM(require_src(), 1);
var __defProp3 = Object.defineProperty;
var __export = (target, all) => {
  for (var name132 in all)
    __defProp3(target, name132, { get: all[name132], enumerable: true });
};
function prepareResponseHeaders(headers, {
  contentType,
  dataStreamVersion
}) {
  const responseHeaders = new Headers(headers != null ? headers : {});
  if (!responseHeaders.has("Content-Type")) {
    responseHeaders.set("Content-Type", contentType);
  }
  if (dataStreamVersion !== undefined) {
    responseHeaders.set("X-Vercel-AI-Data-Stream", dataStreamVersion);
  }
  return responseHeaders;
}
function prepareOutgoingHttpHeaders(headers, {
  contentType,
  dataStreamVersion
}) {
  const outgoingHeaders = {};
  if (headers != null) {
    for (const [key, value] of Object.entries(headers)) {
      outgoingHeaders[key] = value;
    }
  }
  if (outgoingHeaders["Content-Type"] == null) {
    outgoingHeaders["Content-Type"] = contentType;
  }
  if (dataStreamVersion !== undefined) {
    outgoingHeaders["X-Vercel-AI-Data-Stream"] = dataStreamVersion;
  }
  return outgoingHeaders;
}
function writeToServerResponse({
  response,
  status,
  statusText,
  headers,
  stream
}) {
  response.writeHead(status != null ? status : 200, statusText, headers);
  const reader = stream.getReader();
  const read = async () => {
    try {
      while (true) {
        const { done, value } = await reader.read();
        if (done)
          break;
        response.write(value);
      }
    } catch (error) {
      throw error;
    } finally {
      response.end();
    }
  };
  read();
}
var name14 = "AI_InvalidArgumentError";
var marker15 = `vercel.ai.error.${name14}`;
var symbol15 = Symbol.for(marker15);
var _a15;
var InvalidArgumentError2 = class extends AISDKError {
  constructor({
    parameter,
    value,
    message
  }) {
    super({
      name: name14,
      message: `Invalid argument for parameter ${parameter}: ${message}`
    });
    this[_a15] = true;
    this.parameter = parameter;
    this.value = value;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker15);
  }
};
_a15 = symbol15;
async function delay(delayInMs) {
  return delayInMs === undefined ? Promise.resolve() : new Promise((resolve) => setTimeout(resolve, delayInMs));
}
var name22 = "AI_RetryError";
var marker22 = `vercel.ai.error.${name22}`;
var symbol22 = Symbol.for(marker22);
var _a22;
var RetryError = class extends AISDKError {
  constructor({
    message,
    reason,
    errors
  }) {
    super({ name: name22, message });
    this[_a22] = true;
    this.reason = reason;
    this.errors = errors;
    this.lastError = errors[errors.length - 1];
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker22);
  }
};
_a22 = symbol22;
var retryWithExponentialBackoff = ({
  maxRetries = 2,
  initialDelayInMs = 2000,
  backoffFactor = 2
} = {}) => async (f) => _retryWithExponentialBackoff(f, {
  maxRetries,
  delayInMs: initialDelayInMs,
  backoffFactor
});
async function _retryWithExponentialBackoff(f, {
  maxRetries,
  delayInMs,
  backoffFactor
}, errors = []) {
  try {
    return await f();
  } catch (error) {
    if (isAbortError(error)) {
      throw error;
    }
    if (maxRetries === 0) {
      throw error;
    }
    const errorMessage = getErrorMessage2(error);
    const newErrors = [...errors, error];
    const tryNumber = newErrors.length;
    if (tryNumber > maxRetries) {
      throw new RetryError({
        message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
        reason: "maxRetriesExceeded",
        errors: newErrors
      });
    }
    if (error instanceof Error && APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
      await delay(delayInMs);
      return _retryWithExponentialBackoff(f, { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor }, newErrors);
    }
    if (tryNumber === 1) {
      throw error;
    }
    throw new RetryError({
      message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
      reason: "errorNotRetryable",
      errors: newErrors
    });
  }
}
function prepareRetries({
  maxRetries
}) {
  if (maxRetries != null) {
    if (!Number.isInteger(maxRetries)) {
      throw new InvalidArgumentError2({
        parameter: "maxRetries",
        value: maxRetries,
        message: "maxRetries must be an integer"
      });
    }
    if (maxRetries < 0) {
      throw new InvalidArgumentError2({
        parameter: "maxRetries",
        value: maxRetries,
        message: "maxRetries must be >= 0"
      });
    }
  }
  const maxRetriesResult = maxRetries != null ? maxRetries : 2;
  return {
    maxRetries: maxRetriesResult,
    retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult })
  };
}
function assembleOperationName({
  operationId,
  telemetry
}) {
  return {
    "operation.name": `${operationId}${(telemetry == null ? undefined : telemetry.functionId) != null ? ` ${telemetry.functionId}` : ""}`,
    "resource.name": telemetry == null ? undefined : telemetry.functionId,
    "ai.operationId": operationId,
    "ai.telemetry.functionId": telemetry == null ? undefined : telemetry.functionId
  };
}
function getBaseTelemetryAttributes({
  model,
  settings,
  telemetry,
  headers
}) {
  var _a132;
  return {
    "ai.model.provider": model.provider,
    "ai.model.id": model.modelId,
    ...Object.entries(settings).reduce((attributes, [key, value]) => {
      attributes[`ai.settings.${key}`] = value;
      return attributes;
    }, {}),
    ...Object.entries((_a132 = telemetry == null ? undefined : telemetry.metadata) != null ? _a132 : {}).reduce((attributes, [key, value]) => {
      attributes[`ai.telemetry.metadata.${key}`] = value;
      return attributes;
    }, {}),
    ...Object.entries(headers != null ? headers : {}).reduce((attributes, [key, value]) => {
      if (value !== undefined) {
        attributes[`ai.request.headers.${key}`] = value;
      }
      return attributes;
    }, {})
  };
}
var noopTracer = {
  startSpan() {
    return noopSpan;
  },
  startActiveSpan(name132, arg1, arg2, arg3) {
    if (typeof arg1 === "function") {
      return arg1(noopSpan);
    }
    if (typeof arg2 === "function") {
      return arg2(noopSpan);
    }
    if (typeof arg3 === "function") {
      return arg3(noopSpan);
    }
  }
};
var noopSpan = {
  spanContext() {
    return noopSpanContext;
  },
  setAttribute() {
    return this;
  },
  setAttributes() {
    return this;
  },
  addEvent() {
    return this;
  },
  addLink() {
    return this;
  },
  addLinks() {
    return this;
  },
  setStatus() {
    return this;
  },
  updateName() {
    return this;
  },
  end() {
    return this;
  },
  isRecording() {
    return false;
  },
  recordException() {
    return this;
  }
};
var noopSpanContext = {
  traceId: "",
  spanId: "",
  traceFlags: 0
};
function getTracer({
  isEnabled = false,
  tracer
} = {}) {
  if (!isEnabled) {
    return noopTracer;
  }
  if (tracer) {
    return tracer;
  }
  return import_api.trace.getTracer("ai");
}
function recordSpan({
  name: name132,
  tracer,
  attributes,
  fn,
  endWhenDone = true
}) {
  return tracer.startActiveSpan(name132, { attributes }, async (span) => {
    try {
      const result = await fn(span);
      if (endWhenDone) {
        span.end();
      }
      return result;
    } catch (error) {
      try {
        if (error instanceof Error) {
          span.recordException({
            name: error.name,
            message: error.message,
            stack: error.stack
          });
          span.setStatus({
            code: import_api2.SpanStatusCode.ERROR,
            message: error.message
          });
        } else {
          span.setStatus({ code: import_api2.SpanStatusCode.ERROR });
        }
      } finally {
        span.end();
      }
      throw error;
    }
  });
}
function selectTelemetryAttributes({
  telemetry,
  attributes
}) {
  if ((telemetry == null ? undefined : telemetry.isEnabled) !== true) {
    return {};
  }
  return Object.entries(attributes).reduce((attributes2, [key, value]) => {
    if (value === undefined) {
      return attributes2;
    }
    if (typeof value === "object" && "input" in value && typeof value.input === "function") {
      if ((telemetry == null ? undefined : telemetry.recordInputs) === false) {
        return attributes2;
      }
      const result = value.input();
      return result === undefined ? attributes2 : { ...attributes2, [key]: result };
    }
    if (typeof value === "object" && "output" in value && typeof value.output === "function") {
      if ((telemetry == null ? undefined : telemetry.recordOutputs) === false) {
        return attributes2;
      }
      const result = value.output();
      return result === undefined ? attributes2 : { ...attributes2, [key]: result };
    }
    return { ...attributes2, [key]: value };
  }, {});
}
var name32 = "AI_NoObjectGeneratedError";
var marker32 = `vercel.ai.error.${name32}`;
var symbol32 = Symbol.for(marker32);
var _a32;
var NoObjectGeneratedError = class extends AISDKError {
  constructor({
    message = "No object generated.",
    cause,
    text: text2,
    response,
    usage
  }) {
    super({ name: name32, message, cause });
    this[_a32] = true;
    this.text = text2;
    this.response = response;
    this.usage = usage;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker32);
  }
};
_a32 = symbol32;
var name42 = "AI_DownloadError";
var marker42 = `vercel.ai.error.${name42}`;
var symbol42 = Symbol.for(marker42);
var _a42;
var DownloadError = class extends AISDKError {
  constructor({
    url,
    statusCode,
    statusText,
    cause,
    message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
  }) {
    super({ name: name42, message, cause });
    this[_a42] = true;
    this.url = url;
    this.statusCode = statusCode;
    this.statusText = statusText;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker42);
  }
};
_a42 = symbol42;
async function download({
  url,
  fetchImplementation = fetch
}) {
  var _a132;
  const urlText = url.toString();
  try {
    const response = await fetchImplementation(urlText);
    if (!response.ok) {
      throw new DownloadError({
        url: urlText,
        statusCode: response.status,
        statusText: response.statusText
      });
    }
    return {
      data: new Uint8Array(await response.arrayBuffer()),
      mimeType: (_a132 = response.headers.get("content-type")) != null ? _a132 : undefined
    };
  } catch (error) {
    if (DownloadError.isInstance(error)) {
      throw error;
    }
    throw new DownloadError({ url: urlText, cause: error });
  }
}
var mimeTypeSignatures = [
  { mimeType: "image/gif", bytes: [71, 73, 70] },
  { mimeType: "image/png", bytes: [137, 80, 78, 71] },
  { mimeType: "image/jpeg", bytes: [255, 216] },
  { mimeType: "image/webp", bytes: [82, 73, 70, 70] }
];
function detectImageMimeType(image) {
  for (const { bytes, mimeType } of mimeTypeSignatures) {
    if (image.length >= bytes.length && bytes.every((byte, index) => image[index] === byte)) {
      return mimeType;
    }
  }
  return;
}
var name52 = "AI_InvalidDataContentError";
var marker52 = `vercel.ai.error.${name52}`;
var symbol52 = Symbol.for(marker52);
var _a52;
var InvalidDataContentError = class extends AISDKError {
  constructor({
    content,
    cause,
    message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`
  }) {
    super({ name: name52, message, cause });
    this[_a52] = true;
    this.content = content;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker52);
  }
};
_a52 = symbol52;
var dataContentSchema = z.union([
  z.string(),
  z.instanceof(Uint8Array),
  z.instanceof(ArrayBuffer),
  z.custom((value) => {
    var _a132, _b;
    return (_b = (_a132 = globalThis.Buffer) == null ? undefined : _a132.isBuffer(value)) != null ? _b : false;
  }, { message: "Must be a Buffer" })
]);
function convertDataContentToBase64String(content) {
  if (typeof content === "string") {
    return content;
  }
  if (content instanceof ArrayBuffer) {
    return convertUint8ArrayToBase64(new Uint8Array(content));
  }
  return convertUint8ArrayToBase64(content);
}
function convertDataContentToUint8Array(content) {
  if (content instanceof Uint8Array) {
    return content;
  }
  if (typeof content === "string") {
    try {
      return convertBase64ToUint8Array(content);
    } catch (error) {
      throw new InvalidDataContentError({
        message: "Invalid data content. Content string is not a base64-encoded media.",
        content,
        cause: error
      });
    }
  }
  if (content instanceof ArrayBuffer) {
    return new Uint8Array(content);
  }
  throw new InvalidDataContentError({ content });
}
function convertUint8ArrayToText(uint8Array) {
  try {
    return new TextDecoder().decode(uint8Array);
  } catch (error) {
    throw new Error("Error decoding Uint8Array to text");
  }
}
var name62 = "AI_InvalidMessageRoleError";
var marker62 = `vercel.ai.error.${name62}`;
var symbol62 = Symbol.for(marker62);
var _a62;
var InvalidMessageRoleError = class extends AISDKError {
  constructor({
    role,
    message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".`
  }) {
    super({ name: name62, message });
    this[_a62] = true;
    this.role = role;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker62);
  }
};
_a62 = symbol62;
function splitDataUrl(dataUrl) {
  try {
    const [header, base64Content] = dataUrl.split(",");
    return {
      mimeType: header.split(";")[0].split(":")[1],
      base64Content
    };
  } catch (error) {
    return {
      mimeType: undefined,
      base64Content: undefined
    };
  }
}
async function convertToLanguageModelPrompt({
  prompt,
  modelSupportsImageUrls = true,
  modelSupportsUrl = () => false,
  downloadImplementation = download
}) {
  const downloadedAssets = await downloadAssets(prompt.messages, downloadImplementation, modelSupportsImageUrls, modelSupportsUrl);
  return [
    ...prompt.system != null ? [{ role: "system", content: prompt.system }] : [],
    ...prompt.messages.map((message) => convertToLanguageModelMessage(message, downloadedAssets))
  ];
}
function convertToLanguageModelMessage(message, downloadedAssets) {
  const role = message.role;
  switch (role) {
    case "system": {
      return {
        role: "system",
        content: message.content,
        providerMetadata: message.experimental_providerMetadata
      };
    }
    case "user": {
      if (typeof message.content === "string") {
        return {
          role: "user",
          content: [{ type: "text", text: message.content }],
          providerMetadata: message.experimental_providerMetadata
        };
      }
      return {
        role: "user",
        content: message.content.map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== "text" || part.text !== ""),
        providerMetadata: message.experimental_providerMetadata
      };
    }
    case "assistant": {
      if (typeof message.content === "string") {
        return {
          role: "assistant",
          content: [{ type: "text", text: message.content }],
          providerMetadata: message.experimental_providerMetadata
        };
      }
      return {
        role: "assistant",
        content: message.content.filter((part) => part.type !== "text" || part.text !== "").map((part) => {
          const { experimental_providerMetadata, ...rest } = part;
          return {
            ...rest,
            providerMetadata: experimental_providerMetadata
          };
        }),
        providerMetadata: message.experimental_providerMetadata
      };
    }
    case "tool": {
      return {
        role: "tool",
        content: message.content.map((part) => ({
          type: "tool-result",
          toolCallId: part.toolCallId,
          toolName: part.toolName,
          result: part.result,
          content: part.experimental_content,
          isError: part.isError,
          providerMetadata: part.experimental_providerMetadata
        })),
        providerMetadata: message.experimental_providerMetadata
      };
    }
    default: {
      const _exhaustiveCheck = role;
      throw new InvalidMessageRoleError({ role: _exhaustiveCheck });
    }
  }
}
async function downloadAssets(messages, downloadImplementation, modelSupportsImageUrls, modelSupportsUrl) {
  const urls = messages.filter((message) => message.role === "user").map((message) => message.content).filter((content) => Array.isArray(content)).flat().filter((part) => part.type === "image" || part.type === "file").filter((part) => !(part.type === "image" && modelSupportsImageUrls === true)).map((part) => part.type === "image" ? part.image : part.data).map((part) => typeof part === "string" && (part.startsWith("http:") || part.startsWith("https:")) ? new URL(part) : part).filter((image) => image instanceof URL).filter((url) => !modelSupportsUrl(url));
  const downloadedImages = await Promise.all(urls.map(async (url) => ({
    url,
    data: await downloadImplementation({ url })
  })));
  return Object.fromEntries(downloadedImages.map(({ url, data }) => [url.toString(), data]));
}
function convertPartToLanguageModelPart(part, downloadedAssets) {
  if (part.type === "text") {
    return {
      type: "text",
      text: part.text,
      providerMetadata: part.experimental_providerMetadata
    };
  }
  let mimeType = part.mimeType;
  let data;
  let content;
  let normalizedData;
  const type = part.type;
  switch (type) {
    case "image":
      data = part.image;
      break;
    case "file":
      data = part.data;
      break;
    default:
      throw new Error(`Unsupported part type: ${type}`);
  }
  try {
    content = typeof data === "string" ? new URL(data) : data;
  } catch (error) {
    content = data;
  }
  if (content instanceof URL) {
    if (content.protocol === "data:") {
      const { mimeType: dataUrlMimeType, base64Content } = splitDataUrl(content.toString());
      if (dataUrlMimeType == null || base64Content == null) {
        throw new Error(`Invalid data URL format in part ${type}`);
      }
      mimeType = dataUrlMimeType;
      normalizedData = convertDataContentToUint8Array(base64Content);
    } else {
      const downloadedFile = downloadedAssets[content.toString()];
      if (downloadedFile) {
        normalizedData = downloadedFile.data;
        mimeType != null || (mimeType = downloadedFile.mimeType);
      } else {
        normalizedData = content;
      }
    }
  } else {
    normalizedData = convertDataContentToUint8Array(content);
  }
  switch (type) {
    case "image":
      if (mimeType == null && normalizedData instanceof Uint8Array) {
        mimeType = detectImageMimeType(normalizedData);
      }
      return {
        type: "image",
        image: normalizedData,
        mimeType,
        providerMetadata: part.experimental_providerMetadata
      };
    case "file":
      if (mimeType == null) {
        throw new Error(`Mime type is missing for file part`);
      }
      return {
        type: "file",
        data: normalizedData instanceof Uint8Array ? convertDataContentToBase64String(normalizedData) : normalizedData,
        mimeType,
        providerMetadata: part.experimental_providerMetadata
      };
  }
}
function prepareCallSettings({
  maxTokens,
  temperature,
  topP,
  topK,
  presencePenalty,
  frequencyPenalty,
  stopSequences,
  seed
}) {
  if (maxTokens != null) {
    if (!Number.isInteger(maxTokens)) {
      throw new InvalidArgumentError2({
        parameter: "maxTokens",
        value: maxTokens,
        message: "maxTokens must be an integer"
      });
    }
    if (maxTokens < 1) {
      throw new InvalidArgumentError2({
        parameter: "maxTokens",
        value: maxTokens,
        message: "maxTokens must be >= 1"
      });
    }
  }
  if (temperature != null) {
    if (typeof temperature !== "number") {
      throw new InvalidArgumentError2({
        parameter: "temperature",
        value: temperature,
        message: "temperature must be a number"
      });
    }
  }
  if (topP != null) {
    if (typeof topP !== "number") {
      throw new InvalidArgumentError2({
        parameter: "topP",
        value: topP,
        message: "topP must be a number"
      });
    }
  }
  if (topK != null) {
    if (typeof topK !== "number") {
      throw new InvalidArgumentError2({
        parameter: "topK",
        value: topK,
        message: "topK must be a number"
      });
    }
  }
  if (presencePenalty != null) {
    if (typeof presencePenalty !== "number") {
      throw new InvalidArgumentError2({
        parameter: "presencePenalty",
        value: presencePenalty,
        message: "presencePenalty must be a number"
      });
    }
  }
  if (frequencyPenalty != null) {
    if (typeof frequencyPenalty !== "number") {
      throw new InvalidArgumentError2({
        parameter: "frequencyPenalty",
        value: frequencyPenalty,
        message: "frequencyPenalty must be a number"
      });
    }
  }
  if (seed != null) {
    if (!Number.isInteger(seed)) {
      throw new InvalidArgumentError2({
        parameter: "seed",
        value: seed,
        message: "seed must be an integer"
      });
    }
  }
  return {
    maxTokens,
    temperature: temperature != null ? temperature : 0,
    topP,
    topK,
    presencePenalty,
    frequencyPenalty,
    stopSequences: stopSequences != null && stopSequences.length > 0 ? stopSequences : undefined,
    seed
  };
}
var jsonValueSchema = z.lazy(() => z.union([
  z.null(),
  z.string(),
  z.number(),
  z.boolean(),
  z.record(z.string(), jsonValueSchema),
  z.array(jsonValueSchema)
]));
var providerMetadataSchema = z.record(z.string(), z.record(z.string(), jsonValueSchema));
var toolResultContentSchema = z.array(z.union([
  z.object({ type: z.literal("text"), text: z.string() }),
  z.object({
    type: z.literal("image"),
    data: z.string(),
    mimeType: z.string().optional()
  })
]));
var textPartSchema = z.object({
  type: z.literal("text"),
  text: z.string(),
  experimental_providerMetadata: providerMetadataSchema.optional()
});
var imagePartSchema = z.object({
  type: z.literal("image"),
  image: z.union([dataContentSchema, z.instanceof(URL)]),
  mimeType: z.string().optional(),
  experimental_providerMetadata: providerMetadataSchema.optional()
});
var filePartSchema = z.object({
  type: z.literal("file"),
  data: z.union([dataContentSchema, z.instanceof(URL)]),
  mimeType: z.string(),
  experimental_providerMetadata: providerMetadataSchema.optional()
});
var toolCallPartSchema = z.object({
  type: z.literal("tool-call"),
  toolCallId: z.string(),
  toolName: z.string(),
  args: z.unknown()
});
var toolResultPartSchema = z.object({
  type: z.literal("tool-result"),
  toolCallId: z.string(),
  toolName: z.string(),
  result: z.unknown(),
  content: toolResultContentSchema.optional(),
  isError: z.boolean().optional(),
  experimental_providerMetadata: providerMetadataSchema.optional()
});
var coreSystemMessageSchema = z.object({
  role: z.literal("system"),
  content: z.string(),
  experimental_providerMetadata: providerMetadataSchema.optional()
});
var coreUserMessageSchema = z.object({
  role: z.literal("user"),
  content: z.union([
    z.string(),
    z.array(z.union([textPartSchema, imagePartSchema, filePartSchema]))
  ]),
  experimental_providerMetadata: providerMetadataSchema.optional()
});
var coreAssistantMessageSchema = z.object({
  role: z.literal("assistant"),
  content: z.union([
    z.string(),
    z.array(z.union([textPartSchema, toolCallPartSchema]))
  ]),
  experimental_providerMetadata: providerMetadataSchema.optional()
});
var coreToolMessageSchema = z.object({
  role: z.literal("tool"),
  content: z.array(toolResultPartSchema),
  experimental_providerMetadata: providerMetadataSchema.optional()
});
var coreMessageSchema = z.union([
  coreSystemMessageSchema,
  coreUserMessageSchema,
  coreAssistantMessageSchema,
  coreToolMessageSchema
]);
function detectPromptType(prompt) {
  if (!Array.isArray(prompt)) {
    return "other";
  }
  if (prompt.length === 0) {
    return "messages";
  }
  const characteristics = prompt.map(detectSingleMessageCharacteristics);
  if (characteristics.some((c) => c === "has-ui-specific-parts")) {
    return "ui-messages";
  } else if (characteristics.every((c) => c === "has-core-specific-parts" || c === "message")) {
    return "messages";
  } else {
    return "other";
  }
}
function detectSingleMessageCharacteristics(message) {
  if (typeof message === "object" && message !== null && (message.role === "function" || message.role === "data" || ("toolInvocations" in message) || ("experimental_attachments" in message))) {
    return "has-ui-specific-parts";
  } else if (typeof message === "object" && message !== null && "content" in message && (Array.isArray(message.content) || ("experimental_providerMetadata" in message))) {
    return "has-core-specific-parts";
  } else if (typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.content === "string" && ["system", "user", "assistant", "tool"].includes(message.role)) {
    return "message";
  } else {
    return "other";
  }
}
function attachmentsToParts(attachments) {
  var _a132, _b, _c;
  const parts = [];
  for (const attachment of attachments) {
    let url;
    try {
      url = new URL(attachment.url);
    } catch (error) {
      throw new Error(`Invalid URL: ${attachment.url}`);
    }
    switch (url.protocol) {
      case "http:":
      case "https:": {
        if ((_a132 = attachment.contentType) == null ? undefined : _a132.startsWith("image/")) {
          parts.push({ type: "image", image: url });
        } else {
          if (!attachment.contentType) {
            throw new Error("If the attachment is not an image, it must specify a content type");
          }
          parts.push({
            type: "file",
            data: url,
            mimeType: attachment.contentType
          });
        }
        break;
      }
      case "data:": {
        let header;
        let base64Content;
        let mimeType;
        try {
          [header, base64Content] = attachment.url.split(",");
          mimeType = header.split(";")[0].split(":")[1];
        } catch (error) {
          throw new Error(`Error processing data URL: ${attachment.url}`);
        }
        if (mimeType == null || base64Content == null) {
          throw new Error(`Invalid data URL format: ${attachment.url}`);
        }
        if ((_b = attachment.contentType) == null ? undefined : _b.startsWith("image/")) {
          parts.push({
            type: "image",
            image: convertDataContentToUint8Array(base64Content)
          });
        } else if ((_c = attachment.contentType) == null ? undefined : _c.startsWith("text/")) {
          parts.push({
            type: "text",
            text: convertUint8ArrayToText(convertDataContentToUint8Array(base64Content))
          });
        } else {
          if (!attachment.contentType) {
            throw new Error("If the attachment is not an image or text, it must specify a content type");
          }
          parts.push({
            type: "file",
            data: base64Content,
            mimeType: attachment.contentType
          });
        }
        break;
      }
      default: {
        throw new Error(`Unsupported URL protocol: ${url.protocol}`);
      }
    }
  }
  return parts;
}
var name72 = "AI_MessageConversionError";
var marker72 = `vercel.ai.error.${name72}`;
var symbol72 = Symbol.for(marker72);
var _a72;
var MessageConversionError = class extends AISDKError {
  constructor({
    originalMessage,
    message
  }) {
    super({ name: name72, message });
    this[_a72] = true;
    this.originalMessage = originalMessage;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker72);
  }
};
_a72 = symbol72;
function convertToCoreMessages(messages, options) {
  var _a132;
  const tools = (_a132 = options == null ? undefined : options.tools) != null ? _a132 : {};
  const coreMessages = [];
  for (const message of messages) {
    const { role, content, toolInvocations, experimental_attachments } = message;
    switch (role) {
      case "system": {
        coreMessages.push({
          role: "system",
          content
        });
        break;
      }
      case "user": {
        coreMessages.push({
          role: "user",
          content: experimental_attachments ? [
            { type: "text", text: content },
            ...attachmentsToParts(experimental_attachments)
          ] : content
        });
        break;
      }
      case "assistant": {
        if (toolInvocations == null) {
          coreMessages.push({ role: "assistant", content });
          break;
        }
        coreMessages.push({
          role: "assistant",
          content: [
            { type: "text", text: content },
            ...toolInvocations.map(({ toolCallId, toolName, args }) => ({
              type: "tool-call",
              toolCallId,
              toolName,
              args
            }))
          ]
        });
        coreMessages.push({
          role: "tool",
          content: toolInvocations.map((toolInvocation) => {
            if (!("result" in toolInvocation)) {
              throw new MessageConversionError({
                originalMessage: message,
                message: "ToolInvocation must have a result: " + JSON.stringify(toolInvocation)
              });
            }
            const { toolCallId, toolName, result } = toolInvocation;
            const tool2 = tools[toolName];
            return (tool2 == null ? undefined : tool2.experimental_toToolResultContent) != null ? {
              type: "tool-result",
              toolCallId,
              toolName,
              result: tool2.experimental_toToolResultContent(result),
              experimental_content: tool2.experimental_toToolResultContent(result)
            } : {
              type: "tool-result",
              toolCallId,
              toolName,
              result
            };
          })
        });
        break;
      }
      case "data": {
        break;
      }
      default: {
        const _exhaustiveCheck = role;
        throw new MessageConversionError({
          originalMessage: message,
          message: `Unsupported role: ${_exhaustiveCheck}`
        });
      }
    }
  }
  return coreMessages;
}
function standardizePrompt({
  prompt,
  tools
}) {
  if (prompt.prompt == null && prompt.messages == null) {
    throw new InvalidPromptError({
      prompt,
      message: "prompt or messages must be defined"
    });
  }
  if (prompt.prompt != null && prompt.messages != null) {
    throw new InvalidPromptError({
      prompt,
      message: "prompt and messages cannot be defined at the same time"
    });
  }
  if (prompt.system != null && typeof prompt.system !== "string") {
    throw new InvalidPromptError({
      prompt,
      message: "system must be a string"
    });
  }
  if (prompt.prompt != null) {
    if (typeof prompt.prompt !== "string") {
      throw new InvalidPromptError({
        prompt,
        message: "prompt must be a string"
      });
    }
    return {
      type: "prompt",
      system: prompt.system,
      messages: [
        {
          role: "user",
          content: prompt.prompt
        }
      ]
    };
  }
  if (prompt.messages != null) {
    const promptType = detectPromptType(prompt.messages);
    if (promptType === "other") {
      throw new InvalidPromptError({
        prompt,
        message: "messages must be an array of CoreMessage or UIMessage"
      });
    }
    const messages = promptType === "ui-messages" ? convertToCoreMessages(prompt.messages, {
      tools
    }) : prompt.messages;
    const validationResult = safeValidateTypes({
      value: messages,
      schema: z.array(coreMessageSchema)
    });
    if (!validationResult.success) {
      throw new InvalidPromptError({
        prompt,
        message: "messages must be an array of CoreMessage or UIMessage",
        cause: validationResult.error
      });
    }
    return {
      type: "messages",
      messages,
      system: prompt.system
    };
  }
  throw new Error("unreachable");
}
function calculateLanguageModelUsage({
  promptTokens,
  completionTokens
}) {
  return {
    promptTokens,
    completionTokens,
    totalTokens: promptTokens + completionTokens
  };
}
function addLanguageModelUsage(usage1, usage2) {
  return {
    promptTokens: usage1.promptTokens + usage2.promptTokens,
    completionTokens: usage1.completionTokens + usage2.completionTokens,
    totalTokens: usage1.totalTokens + usage2.totalTokens
  };
}
var DEFAULT_SCHEMA_PREFIX = "JSON schema:";
var DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above.";
var DEFAULT_GENERIC_SUFFIX = "You MUST answer with JSON.";
function injectJsonInstruction({
  prompt,
  schema,
  schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : undefined,
  schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX
}) {
  return [
    prompt != null && prompt.length > 0 ? prompt : undefined,
    prompt != null && prompt.length > 0 ? "" : undefined,
    schemaPrefix,
    schema != null ? JSON.stringify(schema) : undefined,
    schemaSuffix
  ].filter((line) => line != null).join(`
`);
}
function createAsyncIterableStream(source, transformer) {
  const transformedStream = source.pipeThrough(new TransformStream(transformer));
  transformedStream[Symbol.asyncIterator] = () => {
    const reader = transformedStream.getReader();
    return {
      async next() {
        const { done, value } = await reader.read();
        return done ? { done: true, value: undefined } : { done: false, value };
      }
    };
  };
  return transformedStream;
}
var originalGenerateId = createIdGenerator({ prefix: "aiobj", size: 24 });
var DelayedPromise = class {
  constructor() {
    this.status = { type: "pending" };
    this._resolve = undefined;
    this._reject = undefined;
  }
  get value() {
    if (this.promise) {
      return this.promise;
    }
    this.promise = new Promise((resolve, reject) => {
      if (this.status.type === "resolved") {
        resolve(this.status.value);
      } else if (this.status.type === "rejected") {
        reject(this.status.error);
      }
      this._resolve = resolve;
      this._reject = reject;
    });
    return this.promise;
  }
  resolve(value) {
    var _a132;
    this.status = { type: "resolved", value };
    if (this.promise) {
      (_a132 = this._resolve) == null || _a132.call(this, value);
    }
  }
  reject(error) {
    var _a132;
    this.status = { type: "rejected", error };
    if (this.promise) {
      (_a132 = this._reject) == null || _a132.call(this, error);
    }
  }
};
function createResolvablePromise() {
  let resolve;
  let reject;
  const promise2 = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return {
    promise: promise2,
    resolve,
    reject
  };
}
function createStitchableStream() {
  let innerStreamReaders = [];
  let controller = null;
  let isClosed = false;
  let waitForNewStream = createResolvablePromise();
  const processPull = async () => {
    if (isClosed && innerStreamReaders.length === 0) {
      controller == null || controller.close();
      return;
    }
    if (innerStreamReaders.length === 0) {
      waitForNewStream = createResolvablePromise();
      await waitForNewStream.promise;
      return processPull();
    }
    try {
      const { value, done } = await innerStreamReaders[0].read();
      if (done) {
        innerStreamReaders.shift();
        if (innerStreamReaders.length > 0) {
          await processPull();
        } else if (isClosed) {
          controller == null || controller.close();
        }
      } else {
        controller == null || controller.enqueue(value);
      }
    } catch (error) {
      controller == null || controller.error(error);
      innerStreamReaders.shift();
      if (isClosed && innerStreamReaders.length === 0) {
        controller == null || controller.close();
      }
    }
  };
  return {
    stream: new ReadableStream({
      start(controllerParam) {
        controller = controllerParam;
      },
      pull: processPull,
      async cancel() {
        for (const reader of innerStreamReaders) {
          await reader.cancel();
        }
        innerStreamReaders = [];
        isClosed = true;
      }
    }),
    addStream: (innerStream) => {
      if (isClosed) {
        throw new Error("Cannot add inner stream: outer stream is closed");
      }
      innerStreamReaders.push(innerStream.getReader());
      waitForNewStream.resolve();
    },
    close: () => {
      isClosed = true;
      waitForNewStream.resolve();
      if (innerStreamReaders.length === 0) {
        controller == null || controller.close();
      }
    }
  };
}
function now() {
  var _a132, _b;
  return (_b = (_a132 = globalThis == null ? undefined : globalThis.performance) == null ? undefined : _a132.now()) != null ? _b : Date.now();
}
var originalGenerateId2 = createIdGenerator({ prefix: "aiobj", size: 24 });
var name82 = "AI_InvalidToolArgumentsError";
var marker82 = `vercel.ai.error.${name82}`;
var symbol82 = Symbol.for(marker82);
var _a82;
var InvalidToolArgumentsError = class extends AISDKError {
  constructor({
    toolArgs,
    toolName,
    cause,
    message = `Invalid arguments for tool ${toolName}: ${getErrorMessage(cause)}`
  }) {
    super({ name: name82, message, cause });
    this[_a82] = true;
    this.toolArgs = toolArgs;
    this.toolName = toolName;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker82);
  }
};
_a82 = symbol82;
var name92 = "AI_NoSuchToolError";
var marker92 = `vercel.ai.error.${name92}`;
var symbol92 = Symbol.for(marker92);
var _a92;
var NoSuchToolError = class extends AISDKError {
  constructor({
    toolName,
    availableTools = undefined,
    message = `Model tried to call unavailable tool '${toolName}'. ${availableTools === undefined ? "No tools are available." : `Available tools: ${availableTools.join(", ")}.`}`
  }) {
    super({ name: name92, message });
    this[_a92] = true;
    this.toolName = toolName;
    this.availableTools = availableTools;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker92);
  }
};
_a92 = symbol92;
var name102 = "AI_ToolCallRepairError";
var marker102 = `vercel.ai.error.${name102}`;
var symbol102 = Symbol.for(marker102);
var _a102;
var ToolCallRepairError = class extends AISDKError {
  constructor({
    cause,
    originalError,
    message = `Error repairing tool call: ${getErrorMessage(cause)}`
  }) {
    super({ name: name102, message, cause });
    this[_a102] = true;
    this.originalError = originalError;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker102);
  }
};
_a102 = symbol102;
var name112 = "AI_ToolExecutionError";
var marker112 = `vercel.ai.error.${name112}`;
var symbol112 = Symbol.for(marker112);
var _a112;
var ToolExecutionError = class extends AISDKError {
  constructor({
    toolArgs,
    toolName,
    cause,
    message = `Error executing tool ${toolName}: ${getErrorMessage(cause)}`
  }) {
    super({ name: name112, message, cause });
    this[_a112] = true;
    this.toolArgs = toolArgs;
    this.toolName = toolName;
  }
  static isInstance(error) {
    return AISDKError.hasMarker(error, marker112);
  }
};
_a112 = symbol112;
function isNonEmptyObject(object2) {
  return object2 != null && Object.keys(object2).length > 0;
}
function prepareToolsAndToolChoice({
  tools,
  toolChoice,
  activeTools
}) {
  if (!isNonEmptyObject(tools)) {
    return {
      tools: undefined,
      toolChoice: undefined
    };
  }
  const filteredTools = activeTools != null ? Object.entries(tools).filter(([name132]) => activeTools.includes(name132)) : Object.entries(tools);
  return {
    tools: filteredTools.map(([name132, tool2]) => {
      const toolType = tool2.type;
      switch (toolType) {
        case undefined:
        case "function":
          return {
            type: "function",
            name: name132,
            description: tool2.description,
            parameters: asSchema(tool2.parameters).jsonSchema
          };
        case "provider-defined":
          return {
            type: "provider-defined",
            name: name132,
            id: tool2.id,
            args: tool2.args
          };
        default: {
          const exhaustiveCheck = toolType;
          throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);
        }
      }
    }),
    toolChoice: toolChoice == null ? { type: "auto" } : typeof toolChoice === "string" ? { type: toolChoice } : { type: "tool", toolName: toolChoice.toolName }
  };
}
var lastWhitespaceRegexp = /^([\s\S]*?)(\s+)(\S*)$/;
function splitOnLastWhitespace(text2) {
  const match = text2.match(lastWhitespaceRegexp);
  return match ? { prefix: match[1], whitespace: match[2], suffix: match[3] } : undefined;
}
function removeTextAfterLastWhitespace(text2) {
  const match = splitOnLastWhitespace(text2);
  return match ? match.prefix + match.whitespace : text2;
}
async function parseToolCall({
  toolCall,
  tools,
  repairToolCall,
  system,
  messages
}) {
  if (tools == null) {
    throw new NoSuchToolError({ toolName: toolCall.toolName });
  }
  try {
    return await doParseToolCall({ toolCall, tools });
  } catch (error) {
    if (repairToolCall == null || !(NoSuchToolError.isInstance(error) || InvalidToolArgumentsError.isInstance(error))) {
      throw error;
    }
    let repairedToolCall = null;
    try {
      repairedToolCall = await repairToolCall({
        toolCall,
        tools,
        parameterSchema: ({ toolName }) => asSchema(tools[toolName].parameters).jsonSchema,
        system,
        messages,
        error
      });
    } catch (repairError) {
      throw new ToolCallRepairError({
        cause: repairError,
        originalError: error
      });
    }
    if (repairedToolCall == null) {
      throw error;
    }
    return await doParseToolCall({ toolCall: repairedToolCall, tools });
  }
}
async function doParseToolCall({
  toolCall,
  tools
}) {
  const toolName = toolCall.toolName;
  const tool2 = tools[toolName];
  if (tool2 == null) {
    throw new NoSuchToolError({
      toolName: toolCall.toolName,
      availableTools: Object.keys(tools)
    });
  }
  const schema = asSchema(tool2.parameters);
  const parseResult = toolCall.args.trim() === "" ? safeValidateTypes({ value: {}, schema }) : safeParseJSON({ text: toolCall.args, schema });
  if (parseResult.success === false) {
    throw new InvalidToolArgumentsError({
      toolName,
      toolArgs: toolCall.args,
      cause: parseResult.error
    });
  }
  return {
    type: "tool-call",
    toolCallId: toolCall.toolCallId,
    toolName,
    args: parseResult.value
  };
}
function toResponseMessages({
  text: text2 = "",
  tools,
  toolCalls,
  toolResults
}) {
  const responseMessages = [];
  responseMessages.push({
    role: "assistant",
    content: [{ type: "text", text: text2 }, ...toolCalls]
  });
  if (toolResults.length > 0) {
    responseMessages.push({
      role: "tool",
      content: toolResults.map((toolResult) => {
        const tool2 = tools[toolResult.toolName];
        return (tool2 == null ? undefined : tool2.experimental_toToolResultContent) != null ? {
          type: "tool-result",
          toolCallId: toolResult.toolCallId,
          toolName: toolResult.toolName,
          result: tool2.experimental_toToolResultContent(toolResult.result),
          experimental_content: tool2.experimental_toToolResultContent(toolResult.result)
        } : {
          type: "tool-result",
          toolCallId: toolResult.toolCallId,
          toolName: toolResult.toolName,
          result: toolResult.result
        };
      })
    });
  }
  return responseMessages;
}
var originalGenerateId3 = createIdGenerator({ prefix: "aitxt", size: 24 });
async function generateText({
  model,
  tools,
  toolChoice,
  system,
  prompt,
  messages,
  maxRetries: maxRetriesArg,
  abortSignal,
  headers,
  maxSteps = 1,
  experimental_output: output,
  experimental_continueSteps: continueSteps = false,
  experimental_telemetry: telemetry,
  experimental_providerMetadata: providerMetadata,
  experimental_activeTools: activeTools,
  experimental_repairToolCall: repairToolCall,
  _internal: {
    generateId: generateId3 = originalGenerateId3,
    currentDate = () => /* @__PURE__ */ new Date
  } = {},
  onStepFinish,
  ...settings
}) {
  var _a132;
  if (maxSteps < 1) {
    throw new InvalidArgumentError2({
      parameter: "maxSteps",
      value: maxSteps,
      message: "maxSteps must be at least 1"
    });
  }
  const { maxRetries, retry } = prepareRetries({ maxRetries: maxRetriesArg });
  const baseTelemetryAttributes = getBaseTelemetryAttributes({
    model,
    telemetry,
    headers,
    settings: { ...settings, maxRetries }
  });
  const initialPrompt = standardizePrompt({
    prompt: {
      system: (_a132 = output == null ? undefined : output.injectIntoSystemPrompt({ system, model })) != null ? _a132 : system,
      prompt,
      messages
    },
    tools
  });
  const tracer = getTracer(telemetry);
  return recordSpan({
    name: "ai.generateText",
    attributes: selectTelemetryAttributes({
      telemetry,
      attributes: {
        ...assembleOperationName({
          operationId: "ai.generateText",
          telemetry
        }),
        ...baseTelemetryAttributes,
        "ai.prompt": {
          input: () => JSON.stringify({ system, prompt, messages })
        },
        "ai.settings.maxSteps": maxSteps
      }
    }),
    tracer,
    fn: async (span) => {
      var _a142, _b, _c, _d, _e, _f;
      const mode = {
        type: "regular",
        ...prepareToolsAndToolChoice({ tools, toolChoice, activeTools })
      };
      const callSettings = prepareCallSettings(settings);
      let currentModelResponse;
      let currentToolCalls = [];
      let currentToolResults = [];
      let stepCount = 0;
      const responseMessages = [];
      let text2 = "";
      const steps = [];
      let usage = {
        completionTokens: 0,
        promptTokens: 0,
        totalTokens: 0
      };
      let stepType = "initial";
      do {
        const promptFormat = stepCount === 0 ? initialPrompt.type : "messages";
        const stepInputMessages = [
          ...initialPrompt.messages,
          ...responseMessages
        ];
        const promptMessages = await convertToLanguageModelPrompt({
          prompt: {
            type: promptFormat,
            system: initialPrompt.system,
            messages: stepInputMessages
          },
          modelSupportsImageUrls: model.supportsImageUrls,
          modelSupportsUrl: model.supportsUrl
        });
        currentModelResponse = await retry(() => recordSpan({
          name: "ai.generateText.doGenerate",
          attributes: selectTelemetryAttributes({
            telemetry,
            attributes: {
              ...assembleOperationName({
                operationId: "ai.generateText.doGenerate",
                telemetry
              }),
              ...baseTelemetryAttributes,
              "ai.prompt.format": { input: () => promptFormat },
              "ai.prompt.messages": {
                input: () => JSON.stringify(promptMessages)
              },
              "ai.prompt.tools": {
                input: () => {
                  var _a152;
                  return (_a152 = mode.tools) == null ? undefined : _a152.map((tool2) => JSON.stringify(tool2));
                }
              },
              "ai.prompt.toolChoice": {
                input: () => mode.toolChoice != null ? JSON.stringify(mode.toolChoice) : undefined
              },
              "gen_ai.system": model.provider,
              "gen_ai.request.model": model.modelId,
              "gen_ai.request.frequency_penalty": settings.frequencyPenalty,
              "gen_ai.request.max_tokens": settings.maxTokens,
              "gen_ai.request.presence_penalty": settings.presencePenalty,
              "gen_ai.request.stop_sequences": settings.stopSequences,
              "gen_ai.request.temperature": settings.temperature,
              "gen_ai.request.top_k": settings.topK,
              "gen_ai.request.top_p": settings.topP
            }
          }),
          tracer,
          fn: async (span2) => {
            var _a152, _b2, _c2, _d2, _e2, _f2;
            const result = await model.doGenerate({
              mode,
              ...callSettings,
              inputFormat: promptFormat,
              responseFormat: output == null ? undefined : output.responseFormat({ model }),
              prompt: promptMessages,
              providerMetadata,
              abortSignal,
              headers
            });
            const responseData = {
              id: (_b2 = (_a152 = result.response) == null ? undefined : _a152.id) != null ? _b2 : generateId3(),
              timestamp: (_d2 = (_c2 = result.response) == null ? undefined : _c2.timestamp) != null ? _d2 : currentDate(),
              modelId: (_f2 = (_e2 = result.response) == null ? undefined : _e2.modelId) != null ? _f2 : model.modelId
            };
            span2.setAttributes(selectTelemetryAttributes({
              telemetry,
              attributes: {
                "ai.response.finishReason": result.finishReason,
                "ai.response.text": {
                  output: () => result.text
                },
                "ai.response.toolCalls": {
                  output: () => JSON.stringify(result.toolCalls)
                },
                "ai.response.id": responseData.id,
                "ai.response.model": responseData.modelId,
                "ai.response.timestamp": responseData.timestamp.toISOString(),
                "ai.usage.promptTokens": result.usage.promptTokens,
                "ai.usage.completionTokens": result.usage.completionTokens,
                "gen_ai.response.finish_reasons": [result.finishReason],
                "gen_ai.response.id": responseData.id,
                "gen_ai.response.model": responseData.modelId,
                "gen_ai.usage.input_tokens": result.usage.promptTokens,
                "gen_ai.usage.output_tokens": result.usage.completionTokens
              }
            }));
            return { ...result, response: responseData };
          }
        }));
        currentToolCalls = await Promise.all(((_a142 = currentModelResponse.toolCalls) != null ? _a142 : []).map((toolCall) => parseToolCall({
          toolCall,
          tools,
          repairToolCall,
          system,
          messages: stepInputMessages
        })));
        currentToolResults = tools == null ? [] : await executeTools({
          toolCalls: currentToolCalls,
          tools,
          tracer,
          telemetry,
          messages: stepInputMessages,
          abortSignal
        });
        const currentUsage = calculateLanguageModelUsage(currentModelResponse.usage);
        usage = addLanguageModelUsage(usage, currentUsage);
        let nextStepType = "done";
        if (++stepCount < maxSteps) {
          if (continueSteps && currentModelResponse.finishReason === "length" && currentToolCalls.length === 0) {
            nextStepType = "continue";
          } else if (currentToolCalls.length > 0 && currentToolResults.length === currentToolCalls.length) {
            nextStepType = "tool-result";
          }
        }
        const originalText = (_b = currentModelResponse.text) != null ? _b : "";
        const stepTextLeadingWhitespaceTrimmed = stepType === "continue" && text2.trimEnd() !== text2 ? originalText.trimStart() : originalText;
        const stepText = nextStepType === "continue" ? removeTextAfterLastWhitespace(stepTextLeadingWhitespaceTrimmed) : stepTextLeadingWhitespaceTrimmed;
        text2 = nextStepType === "continue" || stepType === "continue" ? text2 + stepText : stepText;
        if (stepType === "continue") {
          const lastMessage = responseMessages[responseMessages.length - 1];
          if (typeof lastMessage.content === "string") {
            lastMessage.content += stepText;
          } else {
            lastMessage.content.push({
              text: stepText,
              type: "text"
            });
          }
        } else {
          responseMessages.push(...toResponseMessages({
            text: text2,
            tools: tools != null ? tools : {},
            toolCalls: currentToolCalls,
            toolResults: currentToolResults
          }));
        }
        const currentStepResult = {
          stepType,
          text: stepText,
          toolCalls: currentToolCalls,
          toolResults: currentToolResults,
          finishReason: currentModelResponse.finishReason,
          usage: currentUsage,
          warnings: currentModelResponse.warnings,
          logprobs: currentModelResponse.logprobs,
          request: (_c = currentModelResponse.request) != null ? _c : {},
          response: {
            ...currentModelResponse.response,
            headers: (_d = currentModelResponse.rawResponse) == null ? undefined : _d.headers,
            messages: JSON.parse(JSON.stringify(responseMessages))
          },
          experimental_providerMetadata: currentModelResponse.providerMetadata,
          isContinued: nextStepType === "continue"
        };
        steps.push(currentStepResult);
        await (onStepFinish == null ? undefined : onStepFinish(currentStepResult));
        stepType = nextStepType;
      } while (stepType !== "done");
      span.setAttributes(selectTelemetryAttributes({
        telemetry,
        attributes: {
          "ai.response.finishReason": currentModelResponse.finishReason,
          "ai.response.text": {
            output: () => currentModelResponse.text
          },
          "ai.response.toolCalls": {
            output: () => JSON.stringify(currentModelResponse.toolCalls)
          },
          "ai.usage.promptTokens": currentModelResponse.usage.promptTokens,
          "ai.usage.completionTokens": currentModelResponse.usage.completionTokens
        }
      }));
      return new DefaultGenerateTextResult({
        text: text2,
        output: output == null ? undefined : output.parseOutput({ text: text2 }, {
          response: currentModelResponse.response,
          usage
        }),
        toolCalls: currentToolCalls,
        toolResults: currentToolResults,
        finishReason: currentModelResponse.finishReason,
        usage,
        warnings: currentModelResponse.warnings,
        request: (_e = currentModelResponse.request) != null ? _e : {},
        response: {
          ...currentModelResponse.response,
          headers: (_f = currentModelResponse.rawResponse) == null ? undefined : _f.headers,
          messages: responseMessages
        },
        logprobs: currentModelResponse.logprobs,
        steps,
        providerMetadata: currentModelResponse.providerMetadata
      });
    }
  });
}
async function executeTools({
  toolCalls,
  tools,
  tracer,
  telemetry,
  messages,
  abortSignal
}) {
  const toolResults = await Promise.all(toolCalls.map(async ({ toolCallId, toolName, args }) => {
    const tool2 = tools[toolName];
    if ((tool2 == null ? undefined : tool2.execute) == null) {
      return;
    }
    const result = await recordSpan({
      name: "ai.toolCall",
      attributes: selectTelemetryAttributes({
        telemetry,
        attributes: {
          ...assembleOperationName({
            operationId: "ai.toolCall",
            telemetry
          }),
          "ai.toolCall.name": toolName,
          "ai.toolCall.id": toolCallId,
          "ai.toolCall.args": {
            output: () => JSON.stringify(args)
          }
        }
      }),
      tracer,
      fn: async (span) => {
        try {
          const result2 = await tool2.execute(args, {
            toolCallId,
            messages,
            abortSignal
          });
          try {
            span.setAttributes(selectTelemetryAttributes({
              telemetry,
              attributes: {
                "ai.toolCall.result": {
                  output: () => JSON.stringify(result2)
                }
              }
            }));
          } catch (ignored) {
          }
          return result2;
        } catch (error) {
          throw new ToolExecutionError({
            toolName,
            toolArgs: args,
            cause: error
          });
        }
      }
    });
    return {
      toolCallId,
      toolName,
      args,
      result
    };
  }));
  return toolResults.filter((result) => result != null);
}
var DefaultGenerateTextResult = class {
  constructor(options) {
    this.text = options.text;
    this.toolCalls = options.toolCalls;
    this.toolResults = options.toolResults;
    this.finishReason = options.finishReason;
    this.usage = options.usage;
    this.warnings = options.warnings;
    this.request = options.request;
    this.response = options.response;
    this.steps = options.steps;
    this.experimental_providerMetadata = options.providerMetadata;
    this.logprobs = options.logprobs;
    this.experimental_output = options.output;
  }
};
var output_exports = {};
__export(output_exports, {
  object: () => object2,
  text: () => text
});
var text = () => ({
  type: "text",
  responseFormat: () => ({ type: "text" }),
  injectIntoSystemPrompt({ system }) {
    return system;
  },
  parseOutput({ text: text2 }) {
    return text2;
  }
});
var object2 = ({
  schema: inputSchema
}) => {
  const schema = asSchema(inputSchema);
  return {
    type: "object",
    responseFormat: ({ model }) => ({
      type: "json",
      schema: model.supportsStructuredOutputs ? schema.jsonSchema : undefined
    }),
    injectIntoSystemPrompt({ system, model }) {
      return model.supportsStructuredOutputs ? system : injectJsonInstruction({
        prompt: system,
        schema: schema.jsonSchema
      });
    },
    parseOutput({ text: text2 }, context) {
      const parseResult = safeParseJSON({ text: text2 });
      if (!parseResult.success) {
        throw new NoObjectGeneratedError({
          message: "No object generated: could not parse the response.",
          cause: parseResult.error,
          text: text2,
          response: context.response,
          usage: context.usage
        });
      }
      const validationResult = safeValidateTypes({
        value: parseResult.value,
        schema
      });
      if (!validationResult.success) {
        throw new NoObjectGeneratedError({
          message: "No object generated: response did not match schema.",
          cause: validationResult.error,
          text: text2,
          response: context.response,
          usage: context.usage
        });
      }
      return validationResult.value;
    }
  };
};
function mergeStreams(stream1, stream2) {
  const reader1 = stream1.getReader();
  const reader2 = stream2.getReader();
  let lastRead1 = undefined;
  let lastRead2 = undefined;
  let stream1Done = false;
  let stream2Done = false;
  async function readStream1(controller) {
    try {
      if (lastRead1 == null) {
        lastRead1 = reader1.read();
      }
      const result = await lastRead1;
      lastRead1 = undefined;
      if (!result.done) {
        controller.enqueue(result.value);
      } else {
        controller.close();
      }
    } catch (error) {
      controller.error(error);
    }
  }
  async function readStream2(controller) {
    try {
      if (lastRead2 == null) {
        lastRead2 = reader2.read();
      }
      const result = await lastRead2;
      lastRead2 = undefined;
      if (!result.done) {
        controller.enqueue(result.value);
      } else {
        controller.close();
      }
    } catch (error) {
      controller.error(error);
    }
  }
  return new ReadableStream({
    async pull(controller) {
      try {
        if (stream1Done) {
          await readStream2(controller);
          return;
        }
        if (stream2Done) {
          await readStream1(controller);
          return;
        }
        if (lastRead1 == null) {
          lastRead1 = reader1.read();
        }
        if (lastRead2 == null) {
          lastRead2 = reader2.read();
        }
        const { result, reader } = await Promise.race([
          lastRead1.then((result2) => ({ result: result2, reader: reader1 })),
          lastRead2.then((result2) => ({ result: result2, reader: reader2 }))
        ]);
        if (!result.done) {
          controller.enqueue(result.value);
        }
        if (reader === reader1) {
          lastRead1 = undefined;
          if (result.done) {
            await readStream2(controller);
            stream1Done = true;
          }
        } else {
          lastRead2 = undefined;
          if (result.done) {
            stream2Done = true;
            await readStream1(controller);
          }
        }
      } catch (error) {
        controller.error(error);
      }
    },
    cancel() {
      reader1.cancel();
      reader2.cancel();
    }
  });
}
function runToolsTransformation({
  tools,
  generatorStream,
  toolCallStreaming,
  tracer,
  telemetry,
  system,
  messages,
  abortSignal,
  repairToolCall
}) {
  let toolResultsStreamController = null;
  const toolResultsStream = new ReadableStream({
    start(controller) {
      toolResultsStreamController = controller;
    }
  });
  const activeToolCalls = {};
  const outstandingToolResults = /* @__PURE__ */ new Set;
  let canClose = false;
  let finishChunk = undefined;
  function attemptClose() {
    if (canClose && outstandingToolResults.size === 0) {
      if (finishChunk != null) {
        toolResultsStreamController.enqueue(finishChunk);
      }
      toolResultsStreamController.close();
    }
  }
  const forwardStream = new TransformStream({
    async transform(chunk, controller) {
      const chunkType = chunk.type;
      switch (chunkType) {
        case "text-delta":
        case "response-metadata":
        case "error": {
          controller.enqueue(chunk);
          break;
        }
        case "tool-call-delta": {
          if (toolCallStreaming) {
            if (!activeToolCalls[chunk.toolCallId]) {
              controller.enqueue({
                type: "tool-call-streaming-start",
                toolCallId: chunk.toolCallId,
                toolName: chunk.toolName
              });
              activeToolCalls[chunk.toolCallId] = true;
            }
            controller.enqueue({
              type: "tool-call-delta",
              toolCallId: chunk.toolCallId,
              toolName: chunk.toolName,
              argsTextDelta: chunk.argsTextDelta
            });
          }
          break;
        }
        case "tool-call": {
          try {
            const toolCall = await parseToolCall({
              toolCall: chunk,
              tools,
              repairToolCall,
              system,
              messages
            });
            controller.enqueue(toolCall);
            const tool2 = tools[toolCall.toolName];
            if (tool2.execute != null) {
              const toolExecutionId = generateId();
              outstandingToolResults.add(toolExecutionId);
              recordSpan({
                name: "ai.toolCall",
                attributes: selectTelemetryAttributes({
                  telemetry,
                  attributes: {
                    ...assembleOperationName({
                      operationId: "ai.toolCall",
                      telemetry
                    }),
                    "ai.toolCall.name": toolCall.toolName,
                    "ai.toolCall.id": toolCall.toolCallId,
                    "ai.toolCall.args": {
                      output: () => JSON.stringify(toolCall.args)
                    }
                  }
                }),
                tracer,
                fn: async (span) => tool2.execute(toolCall.args, {
                  toolCallId: toolCall.toolCallId,
                  messages,
                  abortSignal
                }).then((result) => {
                  toolResultsStreamController.enqueue({
                    ...toolCall,
                    type: "tool-result",
                    result
                  });
                  outstandingToolResults.delete(toolExecutionId);
                  attemptClose();
                  try {
                    span.setAttributes(selectTelemetryAttributes({
                      telemetry,
                      attributes: {
                        "ai.toolCall.result": {
                          output: () => JSON.stringify(result)
                        }
                      }
                    }));
                  } catch (ignored) {
                  }
                }, (error) => {
                  toolResultsStreamController.enqueue({
                    type: "error",
                    error: new ToolExecutionError({
                      toolName: toolCall.toolName,
                      toolArgs: toolCall.args,
                      cause: error
                    })
                  });
                  outstandingToolResults.delete(toolExecutionId);
                  attemptClose();
                })
              });
            }
          } catch (error) {
            toolResultsStreamController.enqueue({
              type: "error",
              error
            });
          }
          break;
        }
        case "finish": {
          finishChunk = {
            type: "finish",
            finishReason: chunk.finishReason,
            logprobs: chunk.logprobs,
            usage: calculateLanguageModelUsage(chunk.usage),
            experimental_providerMetadata: chunk.providerMetadata
          };
          break;
        }
        default: {
          const _exhaustiveCheck = chunkType;
          throw new Error(`Unhandled chunk type: ${_exhaustiveCheck}`);
        }
      }
    },
    flush() {
      canClose = true;
      attemptClose();
    }
  });
  return new ReadableStream({
    async start(controller) {
      return Promise.all([
        generatorStream.pipeThrough(forwardStream).pipeTo(new WritableStream({
          write(chunk) {
            controller.enqueue(chunk);
          },
          close() {
          }
        })),
        toolResultsStream.pipeTo(new WritableStream({
          write(chunk) {
            controller.enqueue(chunk);
          },
          close() {
            controller.close();
          }
        }))
      ]);
    }
  });
}
var originalGenerateId4 = createIdGenerator({ prefix: "aitxt", size: 24 });
function streamText({
  model,
  tools,
  toolChoice,
  system,
  prompt,
  messages,
  maxRetries,
  abortSignal,
  headers,
  maxSteps = 1,
  experimental_continueSteps: continueSteps = false,
  experimental_telemetry: telemetry,
  experimental_providerMetadata: providerMetadata,
  experimental_toolCallStreaming: toolCallStreaming = false,
  experimental_activeTools: activeTools,
  experimental_repairToolCall: repairToolCall,
  experimental_transform: transform,
  onChunk,
  onFinish,
  onStepFinish,
  _internal: {
    now: now2 = now,
    generateId: generateId3 = originalGenerateId4,
    currentDate = () => /* @__PURE__ */ new Date
  } = {},
  ...settings
}) {
  return new DefaultStreamTextResult({
    model,
    telemetry,
    headers,
    settings,
    maxRetries,
    abortSignal,
    system,
    prompt,
    messages,
    tools,
    toolChoice,
    toolCallStreaming,
    transform: transform == null ? undefined : transform({ tools }),
    activeTools,
    repairToolCall,
    maxSteps,
    continueSteps,
    providerMetadata,
    onChunk,
    onFinish,
    onStepFinish,
    now: now2,
    currentDate,
    generateId: generateId3
  });
}
var DefaultStreamTextResult = class {
  constructor({
    model,
    telemetry,
    headers,
    settings,
    maxRetries: maxRetriesArg,
    abortSignal,
    system,
    prompt,
    messages,
    tools,
    toolChoice,
    toolCallStreaming,
    transform,
    activeTools,
    repairToolCall,
    maxSteps,
    continueSteps,
    providerMetadata,
    onChunk,
    onFinish,
    onStepFinish,
    now: now2,
    currentDate,
    generateId: generateId3
  }) {
    this.warningsPromise = new DelayedPromise;
    this.usagePromise = new DelayedPromise;
    this.finishReasonPromise = new DelayedPromise;
    this.providerMetadataPromise = new DelayedPromise;
    this.textPromise = new DelayedPromise;
    this.toolCallsPromise = new DelayedPromise;
    this.toolResultsPromise = new DelayedPromise;
    this.requestPromise = new DelayedPromise;
    this.responsePromise = new DelayedPromise;
    this.stepsPromise = new DelayedPromise;
    if (maxSteps < 1) {
      throw new InvalidArgumentError2({
        parameter: "maxSteps",
        value: maxSteps,
        message: "maxSteps must be at least 1"
      });
    }
    let recordedStepText = "";
    let recordedContinuationText = "";
    let recordedFullText = "";
    let recordedRequest = undefined;
    const recordedResponse = {
      id: generateId3(),
      timestamp: currentDate(),
      modelId: model.modelId,
      messages: []
    };
    let recordedToolCalls = [];
    let recordedToolResults = [];
    let recordedFinishReason = undefined;
    let recordedUsage = undefined;
    let recordedProviderMetadata = undefined;
    let stepType = "initial";
    const recordedSteps = [];
    let rootSpan;
    const eventProcessor = new TransformStream({
      async transform(chunk, controller) {
        controller.enqueue(chunk);
        if (chunk.type === "text-delta" || chunk.type === "tool-call" || chunk.type === "tool-result" || chunk.type === "tool-call-streaming-start" || chunk.type === "tool-call-delta") {
          await (onChunk == null ? undefined : onChunk({ chunk }));
        }
        if (chunk.type === "text-delta") {
          recordedStepText += chunk.textDelta;
          recordedContinuationText += chunk.textDelta;
          recordedFullText += chunk.textDelta;
        }
        if (chunk.type === "tool-call") {
          recordedToolCalls.push(chunk);
        }
        if (chunk.type === "tool-result") {
          recordedToolResults.push(chunk);
        }
        if (chunk.type === "step-finish") {
          const stepMessages = toResponseMessages({
            text: recordedContinuationText,
            tools: tools != null ? tools : {},
            toolCalls: recordedToolCalls,
            toolResults: recordedToolResults
          });
          const currentStep = recordedSteps.length;
          let nextStepType = "done";
          if (currentStep + 1 < maxSteps) {
            if (continueSteps && chunk.finishReason === "length" && recordedToolCalls.length === 0) {
              nextStepType = "continue";
            } else if (recordedToolCalls.length > 0 && recordedToolResults.length === recordedToolCalls.length) {
              nextStepType = "tool-result";
            }
          }
          const currentStepResult = {
            stepType,
            text: recordedStepText,
            toolCalls: recordedToolCalls,
            toolResults: recordedToolResults,
            finishReason: chunk.finishReason,
            usage: chunk.usage,
            warnings: chunk.warnings,
            logprobs: chunk.logprobs,
            request: chunk.request,
            response: {
              ...chunk.response,
              messages: [...recordedResponse.messages, ...stepMessages]
            },
            experimental_providerMetadata: chunk.experimental_providerMetadata,
            isContinued: chunk.isContinued
          };
          await (onStepFinish == null ? undefined : onStepFinish(currentStepResult));
          recordedSteps.push(currentStepResult);
          recordedToolCalls = [];
          recordedToolResults = [];
          recordedStepText = "";
          recordedRequest = chunk.request;
          if (nextStepType !== "done") {
            stepType = nextStepType;
          }
          if (nextStepType !== "continue") {
            recordedResponse.messages.push(...stepMessages);
            recordedContinuationText = "";
          }
        }
        if (chunk.type === "finish") {
          recordedResponse.id = chunk.response.id;
          recordedResponse.timestamp = chunk.response.timestamp;
          recordedResponse.modelId = chunk.response.modelId;
          recordedResponse.headers = chunk.response.headers;
          recordedUsage = chunk.usage;
          recordedFinishReason = chunk.finishReason;
          recordedProviderMetadata = chunk.experimental_providerMetadata;
        }
      },
      async flush(controller) {
        var _a132;
        try {
          const lastStep = recordedSteps[recordedSteps.length - 1];
          if (lastStep) {
            self.warningsPromise.resolve(lastStep.warnings);
            self.requestPromise.resolve(lastStep.request);
            self.responsePromise.resolve(lastStep.response);
            self.toolCallsPromise.resolve(lastStep.toolCalls);
            self.toolResultsPromise.resolve(lastStep.toolResults);
            self.providerMetadataPromise.resolve(lastStep.experimental_providerMetadata);
          }
          const finishReason = recordedFinishReason != null ? recordedFinishReason : "unknown";
          const usage = recordedUsage != null ? recordedUsage : {
            completionTokens: NaN,
            promptTokens: NaN,
            totalTokens: NaN
          };
          self.finishReasonPromise.resolve(finishReason);
          self.usagePromise.resolve(usage);
          self.textPromise.resolve(recordedFullText);
          self.stepsPromise.resolve(recordedSteps);
          await (onFinish == null ? undefined : onFinish({
            finishReason,
            logprobs: undefined,
            usage,
            text: recordedFullText,
            toolCalls: lastStep.toolCalls,
            toolResults: lastStep.toolResults,
            request: (_a132 = lastStep.request) != null ? _a132 : {},
            response: lastStep.response,
            warnings: lastStep.warnings,
            experimental_providerMetadata: lastStep.experimental_providerMetadata,
            steps: recordedSteps
          }));
          rootSpan.setAttributes(selectTelemetryAttributes({
            telemetry,
            attributes: {
              "ai.response.finishReason": finishReason,
              "ai.response.text": { output: () => recordedFullText },
              "ai.response.toolCalls": {
                output: () => {
                  var _a142;
                  return ((_a142 = lastStep.toolCalls) == null ? undefined : _a142.length) ? JSON.stringify(lastStep.toolCalls) : undefined;
                }
              },
              "ai.usage.promptTokens": usage.promptTokens,
              "ai.usage.completionTokens": usage.completionTokens
            }
          }));
        } catch (error) {
          controller.error(error);
        } finally {
          rootSpan.end();
        }
      }
    });
    const stitchableStream = createStitchableStream();
    this.addStream = stitchableStream.addStream;
    this.closeStream = stitchableStream.close;
    this.baseStream = (transform ? stitchableStream.stream.pipeThrough(transform) : stitchableStream.stream).pipeThrough(eventProcessor);
    const { maxRetries, retry } = prepareRetries({
      maxRetries: maxRetriesArg
    });
    const tracer = getTracer(telemetry);
    const baseTelemetryAttributes = getBaseTelemetryAttributes({
      model,
      telemetry,
      headers,
      settings: { ...settings, maxRetries }
    });
    const initialPrompt = standardizePrompt({
      prompt: { system, prompt, messages },
      tools
    });
    const self = this;
    recordSpan({
      name: "ai.streamText",
      attributes: selectTelemetryAttributes({
        telemetry,
        attributes: {
          ...assembleOperationName({ operationId: "ai.streamText", telemetry }),
          ...baseTelemetryAttributes,
          "ai.prompt": {
            input: () => JSON.stringify({ system, prompt, messages })
          },
          "ai.settings.maxSteps": maxSteps
        }
      }),
      tracer,
      endWhenDone: false,
      fn: async (rootSpanArg) => {
        rootSpan = rootSpanArg;
        async function streamStep({
          currentStep,
          responseMessages,
          usage,
          stepType: stepType2,
          previousStepText,
          hasLeadingWhitespace
        }) {
          const promptFormat = responseMessages.length === 0 ? initialPrompt.type : "messages";
          const stepInputMessages = [
            ...initialPrompt.messages,
            ...responseMessages
          ];
          const promptMessages = await convertToLanguageModelPrompt({
            prompt: {
              type: promptFormat,
              system: initialPrompt.system,
              messages: stepInputMessages
            },
            modelSupportsImageUrls: model.supportsImageUrls,
            modelSupportsUrl: model.supportsUrl
          });
          const mode = {
            type: "regular",
            ...prepareToolsAndToolChoice({ tools, toolChoice, activeTools })
          };
          const {
            result: { stream, warnings, rawResponse, request },
            doStreamSpan,
            startTimestampMs
          } = await retry(() => recordSpan({
            name: "ai.streamText.doStream",
            attributes: selectTelemetryAttributes({
              telemetry,
              attributes: {
                ...assembleOperationName({
                  operationId: "ai.streamText.doStream",
                  telemetry
                }),
                ...baseTelemetryAttributes,
                "ai.prompt.format": {
                  input: () => promptFormat
                },
                "ai.prompt.messages": {
                  input: () => JSON.stringify(promptMessages)
                },
                "ai.prompt.tools": {
                  input: () => {
                    var _a132;
                    return (_a132 = mode.tools) == null ? undefined : _a132.map((tool2) => JSON.stringify(tool2));
                  }
                },
                "ai.prompt.toolChoice": {
                  input: () => mode.toolChoice != null ? JSON.stringify(mode.toolChoice) : undefined
                },
                "gen_ai.system": model.provider,
                "gen_ai.request.model": model.modelId,
                "gen_ai.request.frequency_penalty": settings.frequencyPenalty,
                "gen_ai.request.max_tokens": settings.maxTokens,
                "gen_ai.request.presence_penalty": settings.presencePenalty,
                "gen_ai.request.stop_sequences": settings.stopSequences,
                "gen_ai.request.temperature": settings.temperature,
                "gen_ai.request.top_k": settings.topK,
                "gen_ai.request.top_p": settings.topP
              }
            }),
            tracer,
            endWhenDone: false,
            fn: async (doStreamSpan2) => ({
              startTimestampMs: now2(),
              doStreamSpan: doStreamSpan2,
              result: await model.doStream({
                mode,
                ...prepareCallSettings(settings),
                inputFormat: promptFormat,
                prompt: promptMessages,
                providerMetadata,
                abortSignal,
                headers
              })
            })
          }));
          const transformedStream = runToolsTransformation({
            tools,
            generatorStream: stream,
            toolCallStreaming,
            tracer,
            telemetry,
            system,
            messages: stepInputMessages,
            repairToolCall,
            abortSignal
          });
          const stepRequest = request != null ? request : {};
          const stepToolCalls = [];
          const stepToolResults = [];
          let stepFinishReason = "unknown";
          let stepUsage = {
            promptTokens: 0,
            completionTokens: 0,
            totalTokens: 0
          };
          let stepProviderMetadata;
          let stepFirstChunk = true;
          let stepText = "";
          let fullStepText = stepType2 === "continue" ? previousStepText : "";
          let stepLogProbs;
          let stepResponse = {
            id: generateId3(),
            timestamp: currentDate(),
            modelId: model.modelId
          };
          let chunkBuffer = "";
          let chunkTextPublished = false;
          let inWhitespacePrefix = true;
          let hasWhitespaceSuffix = false;
          async function publishTextChunk({
            controller,
            chunk
          }) {
            controller.enqueue(chunk);
            stepText += chunk.textDelta;
            fullStepText += chunk.textDelta;
            chunkTextPublished = true;
            hasWhitespaceSuffix = chunk.textDelta.trimEnd() !== chunk.textDelta;
          }
          self.addStream(transformedStream.pipeThrough(new TransformStream({
            async transform(chunk, controller) {
              var _a132, _b, _c;
              if (stepFirstChunk) {
                const msToFirstChunk = now2() - startTimestampMs;
                stepFirstChunk = false;
                doStreamSpan.addEvent("ai.stream.firstChunk", {
                  "ai.response.msToFirstChunk": msToFirstChunk
                });
                doStreamSpan.setAttributes({
                  "ai.response.msToFirstChunk": msToFirstChunk
                });
              }
              if (chunk.type === "text-delta" && chunk.textDelta.length === 0) {
                return;
              }
              const chunkType = chunk.type;
              switch (chunkType) {
                case "text-delta": {
                  if (continueSteps) {
                    const trimmedChunkText = inWhitespacePrefix && hasLeadingWhitespace ? chunk.textDelta.trimStart() : chunk.textDelta;
                    if (trimmedChunkText.length === 0) {
                      break;
                    }
                    inWhitespacePrefix = false;
                    chunkBuffer += trimmedChunkText;
                    const split = splitOnLastWhitespace(chunkBuffer);
                    if (split != null) {
                      chunkBuffer = split.suffix;
                      await publishTextChunk({
                        controller,
                        chunk: {
                          type: "text-delta",
                          textDelta: split.prefix + split.whitespace
                        }
                      });
                    }
                  } else {
                    await publishTextChunk({ controller, chunk });
                  }
                  break;
                }
                case "tool-call": {
                  controller.enqueue(chunk);
                  stepToolCalls.push(chunk);
                  break;
                }
                case "tool-result": {
                  controller.enqueue(chunk);
                  stepToolResults.push(chunk);
                  break;
                }
                case "response-metadata": {
                  stepResponse = {
                    id: (_a132 = chunk.id) != null ? _a132 : stepResponse.id,
                    timestamp: (_b = chunk.timestamp) != null ? _b : stepResponse.timestamp,
                    modelId: (_c = chunk.modelId) != null ? _c : stepResponse.modelId
                  };
                  break;
                }
                case "finish": {
                  stepUsage = chunk.usage;
                  stepFinishReason = chunk.finishReason;
                  stepProviderMetadata = chunk.experimental_providerMetadata;
                  stepLogProbs = chunk.logprobs;
                  const msToFinish = now2() - startTimestampMs;
                  doStreamSpan.addEvent("ai.stream.finish");
                  doStreamSpan.setAttributes({
                    "ai.response.msToFinish": msToFinish,
                    "ai.response.avgCompletionTokensPerSecond": 1000 * stepUsage.completionTokens / msToFinish
                  });
                  break;
                }
                case "tool-call-streaming-start":
                case "tool-call-delta": {
                  controller.enqueue(chunk);
                  break;
                }
                case "error": {
                  controller.enqueue(chunk);
                  stepFinishReason = "error";
                  break;
                }
                default: {
                  const exhaustiveCheck = chunkType;
                  throw new Error(`Unknown chunk type: ${exhaustiveCheck}`);
                }
              }
            },
            async flush(controller) {
              const stepToolCallsJson = stepToolCalls.length > 0 ? JSON.stringify(stepToolCalls) : undefined;
              let nextStepType = "done";
              if (currentStep + 1 < maxSteps) {
                if (continueSteps && stepFinishReason === "length" && stepToolCalls.length === 0) {
                  nextStepType = "continue";
                } else if (stepToolCalls.length > 0 && stepToolResults.length === stepToolCalls.length) {
                  nextStepType = "tool-result";
                }
              }
              if (continueSteps && chunkBuffer.length > 0 && (nextStepType !== "continue" || stepType2 === "continue" && !chunkTextPublished)) {
                await publishTextChunk({
                  controller,
                  chunk: {
                    type: "text-delta",
                    textDelta: chunkBuffer
                  }
                });
                chunkBuffer = "";
              }
              try {
                doStreamSpan.setAttributes(selectTelemetryAttributes({
                  telemetry,
                  attributes: {
                    "ai.response.finishReason": stepFinishReason,
                    "ai.response.text": { output: () => stepText },
                    "ai.response.toolCalls": {
                      output: () => stepToolCallsJson
                    },
                    "ai.response.id": stepResponse.id,
                    "ai.response.model": stepResponse.modelId,
                    "ai.response.timestamp": stepResponse.timestamp.toISOString(),
                    "ai.usage.promptTokens": stepUsage.promptTokens,
                    "ai.usage.completionTokens": stepUsage.completionTokens,
                    "gen_ai.response.finish_reasons": [stepFinishReason],
                    "gen_ai.response.id": stepResponse.id,
                    "gen_ai.response.model": stepResponse.modelId,
                    "gen_ai.usage.input_tokens": stepUsage.promptTokens,
                    "gen_ai.usage.output_tokens": stepUsage.completionTokens
                  }
                }));
              } catch (error) {
              } finally {
                doStreamSpan.end();
              }
              controller.enqueue({
                type: "step-finish",
                finishReason: stepFinishReason,
                usage: stepUsage,
                experimental_providerMetadata: stepProviderMetadata,
                logprobs: stepLogProbs,
                request: stepRequest,
                response: {
                  ...stepResponse,
                  headers: rawResponse == null ? undefined : rawResponse.headers
                },
                warnings,
                isContinued: nextStepType === "continue"
              });
              const combinedUsage = addLanguageModelUsage(usage, stepUsage);
              if (nextStepType === "done") {
                controller.enqueue({
                  type: "finish",
                  finishReason: stepFinishReason,
                  usage: combinedUsage,
                  experimental_providerMetadata: stepProviderMetadata,
                  logprobs: stepLogProbs,
                  response: {
                    ...stepResponse,
                    headers: rawResponse == null ? undefined : rawResponse.headers
                  }
                });
                self.closeStream();
              } else {
                if (stepType2 === "continue") {
                  const lastMessage = responseMessages[responseMessages.length - 1];
                  if (typeof lastMessage.content === "string") {
                    lastMessage.content += stepText;
                  } else {
                    lastMessage.content.push({
                      text: stepText,
                      type: "text"
                    });
                  }
                } else {
                  responseMessages.push(...toResponseMessages({
                    text: stepText,
                    tools: tools != null ? tools : {},
                    toolCalls: stepToolCalls,
                    toolResults: stepToolResults
                  }));
                }
                await streamStep({
                  currentStep: currentStep + 1,
                  responseMessages,
                  usage: combinedUsage,
                  stepType: nextStepType,
                  previousStepText: fullStepText,
                  hasLeadingWhitespace: hasWhitespaceSuffix
                });
              }
            }
          })));
        }
        await streamStep({
          currentStep: 0,
          responseMessages: [],
          usage: {
            promptTokens: 0,
            completionTokens: 0,
            totalTokens: 0
          },
          previousStepText: "",
          stepType: "initial",
          hasLeadingWhitespace: false
        });
      }
    }).catch((error) => {
      self.addStream(new ReadableStream({
        start(controller) {
          controller.enqueue({ type: "error", error });
          controller.close();
        }
      }));
      self.closeStream();
    });
  }
  get warnings() {
    return this.warningsPromise.value;
  }
  get usage() {
    return this.usagePromise.value;
  }
  get finishReason() {
    return this.finishReasonPromise.value;
  }
  get experimental_providerMetadata() {
    return this.providerMetadataPromise.value;
  }
  get text() {
    return this.textPromise.value;
  }
  get toolCalls() {
    return this.toolCallsPromise.value;
  }
  get toolResults() {
    return this.toolResultsPromise.value;
  }
  get request() {
    return this.requestPromise.value;
  }
  get response() {
    return this.responsePromise.value;
  }
  get steps() {
    return this.stepsPromise.value;
  }
  teeStream() {
    const [stream1, stream2] = this.baseStream.tee();
    this.baseStream = stream2;
    return stream1;
  }
  get textStream() {
    return createAsyncIterableStream(this.teeStream(), {
      transform(chunk, controller) {
        if (chunk.type === "text-delta") {
          controller.enqueue(chunk.textDelta);
        } else if (chunk.type === "error") {
          controller.error(chunk.error);
        }
      }
    });
  }
  get fullStream() {
    return createAsyncIterableStream(this.teeStream(), {
      transform(chunk, controller) {
        controller.enqueue(chunk);
      }
    });
  }
  toDataStreamInternal({
    getErrorMessage: getErrorMessage5 = () => "An error occurred.",
    sendUsage = true
  } = {}) {
    let aggregatedResponse = "";
    const callbackTransformer = new TransformStream({
      async transform(chunk, controller) {
        controller.enqueue(chunk);
        if (chunk.type === "text-delta") {
          aggregatedResponse += chunk.textDelta;
        }
      }
    });
    const streamPartsTransformer = new TransformStream({
      transform: async (chunk, controller) => {
        const chunkType = chunk.type;
        switch (chunkType) {
          case "text-delta": {
            controller.enqueue(formatDataStreamPart("text", chunk.textDelta));
            break;
          }
          case "tool-call-streaming-start": {
            controller.enqueue(formatDataStreamPart("tool_call_streaming_start", {
              toolCallId: chunk.toolCallId,
              toolName: chunk.toolName
            }));
            break;
          }
          case "tool-call-delta": {
            controller.enqueue(formatDataStreamPart("tool_call_delta", {
              toolCallId: chunk.toolCallId,
              argsTextDelta: chunk.argsTextDelta
            }));
            break;
          }
          case "tool-call": {
            controller.enqueue(formatDataStreamPart("tool_call", {
              toolCallId: chunk.toolCallId,
              toolName: chunk.toolName,
              args: chunk.args
            }));
            break;
          }
          case "tool-result": {
            controller.enqueue(formatDataStreamPart("tool_result", {
              toolCallId: chunk.toolCallId,
              result: chunk.result
            }));
            break;
          }
          case "error": {
            controller.enqueue(formatDataStreamPart("error", getErrorMessage5(chunk.error)));
            break;
          }
          case "step-finish": {
            controller.enqueue(formatDataStreamPart("finish_step", {
              finishReason: chunk.finishReason,
              usage: sendUsage ? {
                promptTokens: chunk.usage.promptTokens,
                completionTokens: chunk.usage.completionTokens
              } : undefined,
              isContinued: chunk.isContinued
            }));
            break;
          }
          case "finish": {
            controller.enqueue(formatDataStreamPart("finish_message", {
              finishReason: chunk.finishReason,
              usage: sendUsage ? {
                promptTokens: chunk.usage.promptTokens,
                completionTokens: chunk.usage.completionTokens
              } : undefined
            }));
            break;
          }
          default: {
            const exhaustiveCheck = chunkType;
            throw new Error(`Unknown chunk type: ${exhaustiveCheck}`);
          }
        }
      }
    });
    return this.fullStream.pipeThrough(callbackTransformer).pipeThrough(streamPartsTransformer);
  }
  pipeDataStreamToResponse(response, {
    status,
    statusText,
    headers,
    data,
    getErrorMessage: getErrorMessage5,
    sendUsage
  } = {}) {
    writeToServerResponse({
      response,
      status,
      statusText,
      headers: prepareOutgoingHttpHeaders(headers, {
        contentType: "text/plain; charset=utf-8",
        dataStreamVersion: "v1"
      }),
      stream: this.toDataStream({ data, getErrorMessage: getErrorMessage5, sendUsage })
    });
  }
  pipeTextStreamToResponse(response, init) {
    writeToServerResponse({
      response,
      status: init == null ? undefined : init.status,
      statusText: init == null ? undefined : init.statusText,
      headers: prepareOutgoingHttpHeaders(init == null ? undefined : init.headers, {
        contentType: "text/plain; charset=utf-8"
      }),
      stream: this.textStream.pipeThrough(new TextEncoderStream)
    });
  }
  toDataStream(options) {
    const stream = this.toDataStreamInternal({
      getErrorMessage: options == null ? undefined : options.getErrorMessage,
      sendUsage: options == null ? undefined : options.sendUsage
    }).pipeThrough(new TextEncoderStream);
    return (options == null ? undefined : options.data) ? mergeStreams(options == null ? undefined : options.data.stream, stream) : stream;
  }
  mergeIntoDataStream(writer) {
    writer.merge(this.toDataStreamInternal({
      getErrorMessage: writer.onError
    }));
  }
  toDataStreamResponse({
    headers,
    status,
    statusText,
    data,
    getErrorMessage: getErrorMessage5,
    sendUsage
  } = {}) {
    return new Response(this.toDataStream({ data, getErrorMessage: getErrorMessage5, sendUsage }), {
      status,
      statusText,
      headers: prepareResponseHeaders(headers, {
        contentType: "text/plain; charset=utf-8",
        dataStreamVersion: "v1"
      })
    });
  }
  toTextStreamResponse(init) {
    var _a132;
    return new Response(this.textStream.pipeThrough(new TextEncoderStream), {
      status: (_a132 = init == null ? undefined : init.status) != null ? _a132 : 200,
      headers: prepareResponseHeaders(init == null ? undefined : init.headers, {
        contentType: "text/plain; charset=utf-8"
      })
    });
  }
};
var name122 = "AI_NoSuchProviderError";
var marker122 = `vercel.ai.error.${name122}`;
var symbol122 = Symbol.for(marker122);
var _a122;
_a122 = symbol122;
function tool(tool2) {
  return tool2;
}
var langchain_adapter_exports = {};
__export(langchain_adapter_exports, {
  mergeIntoDataStream: () => mergeIntoDataStream,
  toDataStream: () => toDataStream,
  toDataStreamResponse: () => toDataStreamResponse
});
function createCallbacksTransformer(callbacks = {}) {
  const textEncoder = new TextEncoder;
  let aggregatedResponse = "";
  return new TransformStream({
    async start() {
      if (callbacks.onStart)
        await callbacks.onStart();
    },
    async transform(message, controller) {
      controller.enqueue(textEncoder.encode(message));
      aggregatedResponse += message;
      if (callbacks.onToken)
        await callbacks.onToken(message);
      if (callbacks.onText && typeof message === "string") {
        await callbacks.onText(message);
      }
    },
    async flush() {
      if (callbacks.onCompletion) {
        await callbacks.onCompletion(aggregatedResponse);
      }
      if (callbacks.onFinal) {
        await callbacks.onFinal(aggregatedResponse);
      }
    }
  });
}
function toDataStreamInternal(stream, callbacks) {
  return stream.pipeThrough(new TransformStream({
    transform: async (value, controller) => {
      var _a132;
      if (typeof value === "string") {
        controller.enqueue(value);
        return;
      }
      if ("event" in value) {
        if (value.event === "on_chat_model_stream") {
          forwardAIMessageChunk((_a132 = value.data) == null ? undefined : _a132.chunk, controller);
        }
        return;
      }
      forwardAIMessageChunk(value, controller);
    }
  })).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({
    transform: async (chunk, controller) => {
      controller.enqueue(formatDataStreamPart("text", chunk));
    }
  }));
}
function toDataStream(stream, callbacks) {
  return toDataStreamInternal(stream, callbacks).pipeThrough(new TextEncoderStream);
}
function toDataStreamResponse(stream, options) {
  var _a132;
  const dataStream = toDataStreamInternal(stream, options == null ? undefined : options.callbacks).pipeThrough(new TextEncoderStream);
  const data = options == null ? undefined : options.data;
  const init = options == null ? undefined : options.init;
  const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
  return new Response(responseStream, {
    status: (_a132 = init == null ? undefined : init.status) != null ? _a132 : 200,
    statusText: init == null ? undefined : init.statusText,
    headers: prepareResponseHeaders(init == null ? undefined : init.headers, {
      contentType: "text/plain; charset=utf-8",
      dataStreamVersion: "v1"
    })
  });
}
function mergeIntoDataStream(stream, options) {
  options.dataStream.merge(toDataStreamInternal(stream, options.callbacks));
}
function forwardAIMessageChunk(chunk, controller) {
  if (typeof chunk.content === "string") {
    controller.enqueue(chunk.content);
  } else {
    const content = chunk.content;
    for (const item of content) {
      if (item.type === "text") {
        controller.enqueue(item.text);
      }
    }
  }
}
var llamaindex_adapter_exports = {};
__export(llamaindex_adapter_exports, {
  mergeIntoDataStream: () => mergeIntoDataStream2,
  toDataStream: () => toDataStream2,
  toDataStreamResponse: () => toDataStreamResponse2
});
function toDataStreamInternal2(stream, callbacks) {
  const trimStart = trimStartOfStream();
  return convertAsyncIteratorToReadableStream(stream[Symbol.asyncIterator]()).pipeThrough(new TransformStream({
    async transform(message, controller) {
      controller.enqueue(trimStart(message.delta));
    }
  })).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({
    transform: async (chunk, controller) => {
      controller.enqueue(formatDataStreamPart("text", chunk));
    }
  }));
}
function toDataStream2(stream, callbacks) {
  return toDataStreamInternal2(stream, callbacks).pipeThrough(new TextEncoderStream);
}
function toDataStreamResponse2(stream, options = {}) {
  var _a132;
  const { init, data, callbacks } = options;
  const dataStream = toDataStreamInternal2(stream, callbacks).pipeThrough(new TextEncoderStream);
  const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
  return new Response(responseStream, {
    status: (_a132 = init == null ? undefined : init.status) != null ? _a132 : 200,
    statusText: init == null ? undefined : init.statusText,
    headers: prepareResponseHeaders(init == null ? undefined : init.headers, {
      contentType: "text/plain; charset=utf-8",
      dataStreamVersion: "v1"
    })
  });
}
function mergeIntoDataStream2(stream, options) {
  options.dataStream.merge(toDataStreamInternal2(stream, options.callbacks));
}
function trimStartOfStream() {
  let isStreamStart = true;
  return (text2) => {
    if (isStreamStart) {
      text2 = text2.trimStart();
      if (text2)
        isStreamStart = false;
    }
    return text2;
  };
}
var HANGING_STREAM_WARNING_TIME_MS = 15 * 1000;

// src/utils.ts
var jsonValueSchema2 = z.lazy(() => z.union([
  z.null(),
  z.string(),
  z.number(),
  z.boolean(),
  z.record(jsonValueSchema2),
  z.array(jsonValueSchema2)
]));
function createAsyncIterableStream2(source) {
  const stream = source.pipeThrough(new TransformStream);
  stream[Symbol.asyncIterator] = () => {
    const reader = stream.getReader();
    return {
      async next() {
        const { done, value } = await reader.read();
        return done ? { done: true, value: undefined } : { done: false, value };
      }
    };
  };
  return stream;
}
function createStitchableStream2() {
  let innerStreamReaders = [];
  let controller = null;
  let isClosed = false;
  let waitForNewStream = createResolvablePromise2();
  const processPull = async () => {
    if (isClosed && innerStreamReaders.length === 0) {
      controller?.close();
      return;
    }
    if (innerStreamReaders.length === 0) {
      waitForNewStream = createResolvablePromise2();
      await waitForNewStream.promise;
      return processPull();
    }
    try {
      const { value, done } = await innerStreamReaders[0].read();
      if (done) {
        innerStreamReaders.shift();
        if (innerStreamReaders.length > 0) {
          await processPull();
        } else if (isClosed) {
          controller?.close();
        }
      } else {
        controller?.enqueue(value);
      }
    } catch (error) {
      controller?.error(error);
      innerStreamReaders.shift();
      if (isClosed && innerStreamReaders.length === 0) {
        controller?.close();
      }
    }
  };
  const stream = new ReadableStream({
    start(controllerParam) {
      controller = controllerParam;
    },
    pull: processPull,
    async cancel() {
      for (const reader of innerStreamReaders) {
        await reader.cancel();
      }
      innerStreamReaders = [];
      isClosed = true;
    }
  });
  return {
    stream,
    enqueue: (c) => controller?.enqueue(c),
    addStream: (innerStream) => {
      if (isClosed) {
        throw new Error("Cannot add inner stream: outer stream is closed");
      }
      innerStreamReaders.push(innerStream.getReader());
      waitForNewStream.resolve();
    },
    close: () => {
      isClosed = true;
      waitForNewStream.resolve();
      if (innerStreamReaders.length === 0) {
        controller?.close();
      }
    }
  };
}
function createResolvablePromise2() {
  let resolve;
  let reject;
  const promise2 = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return {
    promise: promise2,
    resolve,
    reject
  };
}

// node_modules/@ai-sdk/openai/dist/index.mjs
function convertToOpenAIChatMessages({
  prompt,
  useLegacyFunctionCalling = false
}) {
  const messages = [];
  for (const { role, content } of prompt) {
    switch (role) {
      case "system": {
        messages.push({ role: "system", content });
        break;
      }
      case "user": {
        if (content.length === 1 && content[0].type === "text") {
          messages.push({ role: "user", content: content[0].text });
          break;
        }
        messages.push({
          role: "user",
          content: content.map((part) => {
            var _a16, _b, _c;
            switch (part.type) {
              case "text": {
                return { type: "text", text: part.text };
              }
              case "image": {
                return {
                  type: "image_url",
                  image_url: {
                    url: part.image instanceof URL ? part.image.toString() : `data:${(_a16 = part.mimeType) != null ? _a16 : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`,
                    detail: (_c = (_b = part.providerMetadata) == null ? undefined : _b.openai) == null ? undefined : _c.imageDetail
                  }
                };
              }
              case "file": {
                if (part.data instanceof URL) {
                  throw new UnsupportedFunctionalityError({
                    functionality: "'File content parts with URL data' functionality not supported."
                  });
                }
                switch (part.mimeType) {
                  case "audio/wav": {
                    return {
                      type: "input_audio",
                      input_audio: { data: part.data, format: "wav" }
                    };
                  }
                  case "audio/mp3":
                  case "audio/mpeg": {
                    return {
                      type: "input_audio",
                      input_audio: { data: part.data, format: "mp3" }
                    };
                  }
                  default: {
                    throw new UnsupportedFunctionalityError({
                      functionality: `File content part type ${part.mimeType} in user messages`
                    });
                  }
                }
              }
            }
          })
        });
        break;
      }
      case "assistant": {
        let text2 = "";
        const toolCalls = [];
        for (const part of content) {
          switch (part.type) {
            case "text": {
              text2 += part.text;
              break;
            }
            case "tool-call": {
              toolCalls.push({
                id: part.toolCallId,
                type: "function",
                function: {
                  name: part.toolName,
                  arguments: JSON.stringify(part.args)
                }
              });
              break;
            }
            default: {
              const _exhaustiveCheck = part;
              throw new Error(`Unsupported part: ${_exhaustiveCheck}`);
            }
          }
        }
        if (useLegacyFunctionCalling) {
          if (toolCalls.length > 1) {
            throw new UnsupportedFunctionalityError({
              functionality: "useLegacyFunctionCalling with multiple tool calls in one message"
            });
          }
          messages.push({
            role: "assistant",
            content: text2,
            function_call: toolCalls.length > 0 ? toolCalls[0].function : undefined
          });
        } else {
          messages.push({
            role: "assistant",
            content: text2,
            tool_calls: toolCalls.length > 0 ? toolCalls : undefined
          });
        }
        break;
      }
      case "tool": {
        for (const toolResponse of content) {
          if (useLegacyFunctionCalling) {
            messages.push({
              role: "function",
              name: toolResponse.toolName,
              content: JSON.stringify(toolResponse.result)
            });
          } else {
            messages.push({
              role: "tool",
              tool_call_id: toolResponse.toolCallId,
              content: JSON.stringify(toolResponse.result)
            });
          }
        }
        break;
      }
      default: {
        const _exhaustiveCheck = role;
        throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
      }
    }
  }
  return messages;
}
function mapOpenAIChatLogProbsOutput(logprobs) {
  var _a16, _b;
  return (_b = (_a16 = logprobs == null ? undefined : logprobs.content) == null ? undefined : _a16.map(({ token, logprob, top_logprobs }) => ({
    token,
    logprob,
    topLogprobs: top_logprobs ? top_logprobs.map(({ token: token2, logprob: logprob2 }) => ({
      token: token2,
      logprob: logprob2
    })) : []
  }))) != null ? _b : undefined;
}
function mapOpenAIFinishReason(finishReason) {
  switch (finishReason) {
    case "stop":
      return "stop";
    case "length":
      return "length";
    case "content_filter":
      return "content-filter";
    case "function_call":
    case "tool_calls":
      return "tool-calls";
    default:
      return "unknown";
  }
}
var openaiErrorDataSchema = z.object({
  error: z.object({
    message: z.string(),
    type: z.string().nullish(),
    param: z.any().nullish(),
    code: z.union([z.string(), z.number()]).nullish()
  })
});
var openaiFailedResponseHandler = createJsonErrorResponseHandler({
  errorSchema: openaiErrorDataSchema,
  errorToMessage: (data) => data.error.message
});
function getResponseMetadata({
  id,
  model,
  created
}) {
  return {
    id: id != null ? id : undefined,
    modelId: model != null ? model : undefined,
    timestamp: created != null ? new Date(created * 1000) : undefined
  };
}
function prepareTools({
  mode,
  useLegacyFunctionCalling = false,
  structuredOutputs
}) {
  var _a16;
  const tools = ((_a16 = mode.tools) == null ? undefined : _a16.length) ? mode.tools : undefined;
  const toolWarnings = [];
  if (tools == null) {
    return { tools: undefined, tool_choice: undefined, toolWarnings };
  }
  const toolChoice = mode.toolChoice;
  if (useLegacyFunctionCalling) {
    const openaiFunctions = [];
    for (const tool2 of tools) {
      if (tool2.type === "provider-defined") {
        toolWarnings.push({ type: "unsupported-tool", tool: tool2 });
      } else {
        openaiFunctions.push({
          name: tool2.name,
          description: tool2.description,
          parameters: tool2.parameters
        });
      }
    }
    if (toolChoice == null) {
      return {
        functions: openaiFunctions,
        function_call: undefined,
        toolWarnings
      };
    }
    const type2 = toolChoice.type;
    switch (type2) {
      case "auto":
      case "none":
      case undefined:
        return {
          functions: openaiFunctions,
          function_call: undefined,
          toolWarnings
        };
      case "required":
        throw new UnsupportedFunctionalityError({
          functionality: "useLegacyFunctionCalling and toolChoice: required"
        });
      default:
        return {
          functions: openaiFunctions,
          function_call: { name: toolChoice.toolName },
          toolWarnings
        };
    }
  }
  const openaiTools = [];
  for (const tool2 of tools) {
    if (tool2.type === "provider-defined") {
      toolWarnings.push({ type: "unsupported-tool", tool: tool2 });
    } else {
      openaiTools.push({
        type: "function",
        function: {
          name: tool2.name,
          description: tool2.description,
          parameters: tool2.parameters,
          strict: structuredOutputs ? true : undefined
        }
      });
    }
  }
  if (toolChoice == null) {
    return { tools: openaiTools, tool_choice: undefined, toolWarnings };
  }
  const type = toolChoice.type;
  switch (type) {
    case "auto":
    case "none":
    case "required":
      return { tools: openaiTools, tool_choice: type, toolWarnings };
    case "tool":
      return {
        tools: openaiTools,
        tool_choice: {
          type: "function",
          function: {
            name: toolChoice.toolName
          }
        },
        toolWarnings
      };
    default: {
      const _exhaustiveCheck = type;
      throw new UnsupportedFunctionalityError({
        functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
      });
    }
  }
}
var OpenAIChatLanguageModel = class {
  constructor(modelId, settings, config) {
    this.specificationVersion = "v1";
    this.modelId = modelId;
    this.settings = settings;
    this.config = config;
  }
  get supportsStructuredOutputs() {
    var _a16;
    return (_a16 = this.settings.structuredOutputs) != null ? _a16 : false;
  }
  get defaultObjectGenerationMode() {
    if (isAudioModel(this.modelId)) {
      return "tool";
    }
    return this.supportsStructuredOutputs ? "json" : "tool";
  }
  get provider() {
    return this.config.provider;
  }
  get supportsImageUrls() {
    return !this.settings.downloadImages;
  }
  getArgs({
    mode,
    prompt,
    maxTokens,
    temperature,
    topP,
    topK,
    frequencyPenalty,
    presencePenalty,
    stopSequences,
    responseFormat,
    seed,
    providerMetadata
  }) {
    var _a16, _b, _c, _d, _e, _f, _g, _h;
    const type = mode.type;
    const warnings = [];
    if (topK != null) {
      warnings.push({
        type: "unsupported-setting",
        setting: "topK"
      });
    }
    if ((responseFormat == null ? undefined : responseFormat.type) === "json" && responseFormat.schema != null && !this.supportsStructuredOutputs) {
      warnings.push({
        type: "unsupported-setting",
        setting: "responseFormat",
        details: "JSON response format schema is only supported with structuredOutputs"
      });
    }
    const useLegacyFunctionCalling = this.settings.useLegacyFunctionCalling;
    if (useLegacyFunctionCalling && this.settings.parallelToolCalls === true) {
      throw new UnsupportedFunctionalityError({
        functionality: "useLegacyFunctionCalling with parallelToolCalls"
      });
    }
    if (useLegacyFunctionCalling && this.supportsStructuredOutputs) {
      throw new UnsupportedFunctionalityError({
        functionality: "structuredOutputs with useLegacyFunctionCalling"
      });
    }
    const baseArgs = {
      model: this.modelId,
      logit_bias: this.settings.logitBias,
      logprobs: this.settings.logprobs === true || typeof this.settings.logprobs === "number" ? true : undefined,
      top_logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : undefined : undefined,
      user: this.settings.user,
      parallel_tool_calls: this.settings.parallelToolCalls,
      max_tokens: maxTokens,
      temperature,
      top_p: topP,
      frequency_penalty: frequencyPenalty,
      presence_penalty: presencePenalty,
      response_format: (responseFormat == null ? undefined : responseFormat.type) === "json" ? this.supportsStructuredOutputs && responseFormat.schema != null ? {
        type: "json_schema",
        json_schema: {
          schema: responseFormat.schema,
          strict: true,
          name: (_a16 = responseFormat.name) != null ? _a16 : "response",
          description: responseFormat.description
        }
      } : { type: "json_object" } : undefined,
      stop: stopSequences,
      seed,
      max_completion_tokens: (_b = providerMetadata == null ? undefined : providerMetadata.openai) == null ? undefined : _b.maxCompletionTokens,
      store: (_c = providerMetadata == null ? undefined : providerMetadata.openai) == null ? undefined : _c.store,
      metadata: (_d = providerMetadata == null ? undefined : providerMetadata.openai) == null ? undefined : _d.metadata,
      prediction: (_e = providerMetadata == null ? undefined : providerMetadata.openai) == null ? undefined : _e.prediction,
      reasoning_effort: (_g = (_f = providerMetadata == null ? undefined : providerMetadata.openai) == null ? undefined : _f.reasoningEffort) != null ? _g : this.settings.reasoningEffort,
      messages: convertToOpenAIChatMessages({
        prompt,
        useLegacyFunctionCalling
      })
    };
    if (isReasoningModel(this.modelId)) {
      baseArgs.temperature = undefined;
      baseArgs.top_p = undefined;
      baseArgs.frequency_penalty = undefined;
      baseArgs.presence_penalty = undefined;
    }
    switch (type) {
      case "regular": {
        const { tools, tool_choice, functions, function_call, toolWarnings } = prepareTools({
          mode,
          useLegacyFunctionCalling,
          structuredOutputs: this.supportsStructuredOutputs
        });
        return {
          args: {
            ...baseArgs,
            tools,
            tool_choice,
            functions,
            function_call
          },
          warnings: [...warnings, ...toolWarnings]
        };
      }
      case "object-json": {
        return {
          args: {
            ...baseArgs,
            response_format: this.supportsStructuredOutputs && mode.schema != null ? {
              type: "json_schema",
              json_schema: {
                schema: mode.schema,
                strict: true,
                name: (_h = mode.name) != null ? _h : "response",
                description: mode.description
              }
            } : { type: "json_object" }
          },
          warnings
        };
      }
      case "object-tool": {
        return {
          args: useLegacyFunctionCalling ? {
            ...baseArgs,
            function_call: {
              name: mode.tool.name
            },
            functions: [
              {
                name: mode.tool.name,
                description: mode.tool.description,
                parameters: mode.tool.parameters
              }
            ]
          } : {
            ...baseArgs,
            tool_choice: {
              type: "function",
              function: { name: mode.tool.name }
            },
            tools: [
              {
                type: "function",
                function: {
                  name: mode.tool.name,
                  description: mode.tool.description,
                  parameters: mode.tool.parameters,
                  strict: this.supportsStructuredOutputs ? true : undefined
                }
              }
            ]
          },
          warnings
        };
      }
      default: {
        const _exhaustiveCheck = type;
        throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
      }
    }
  }
  async doGenerate(options) {
    var _a16, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
    const { args: body, warnings } = this.getArgs(options);
    const { responseHeaders, value: response } = await postJsonToApi({
      url: this.config.url({
        path: "/chat/completions",
        modelId: this.modelId
      }),
      headers: combineHeaders(this.config.headers(), options.headers),
      body,
      failedResponseHandler: openaiFailedResponseHandler,
      successfulResponseHandler: createJsonResponseHandler(openaiChatResponseSchema),
      abortSignal: options.abortSignal,
      fetch: this.config.fetch
    });
    const { messages: rawPrompt, ...rawSettings } = body;
    const choice = response.choices[0];
    let providerMetadata;
    if (((_b = (_a16 = response.usage) == null ? undefined : _a16.completion_tokens_details) == null ? undefined : _b.reasoning_tokens) != null || ((_d = (_c = response.usage) == null ? undefined : _c.prompt_tokens_details) == null ? undefined : _d.cached_tokens) != null) {
      providerMetadata = { openai: {} };
      if (((_f = (_e = response.usage) == null ? undefined : _e.completion_tokens_details) == null ? undefined : _f.reasoning_tokens) != null) {
        providerMetadata.openai.reasoningTokens = (_h = (_g = response.usage) == null ? undefined : _g.completion_tokens_details) == null ? undefined : _h.reasoning_tokens;
      }
      if (((_j = (_i = response.usage) == null ? undefined : _i.prompt_tokens_details) == null ? undefined : _j.cached_tokens) != null) {
        providerMetadata.openai.cachedPromptTokens = (_l = (_k = response.usage) == null ? undefined : _k.prompt_tokens_details) == null ? undefined : _l.cached_tokens;
      }
    }
    return {
      text: (_m = choice.message.content) != null ? _m : undefined,
      toolCalls: this.settings.useLegacyFunctionCalling && choice.message.function_call ? [
        {
          toolCallType: "function",
          toolCallId: generateId(),
          toolName: choice.message.function_call.name,
          args: choice.message.function_call.arguments
        }
      ] : (_n = choice.message.tool_calls) == null ? undefined : _n.map((toolCall) => {
        var _a23;
        return {
          toolCallType: "function",
          toolCallId: (_a23 = toolCall.id) != null ? _a23 : generateId(),
          toolName: toolCall.function.name,
          args: toolCall.function.arguments
        };
      }),
      finishReason: mapOpenAIFinishReason(choice.finish_reason),
      usage: {
        promptTokens: (_p = (_o = response.usage) == null ? undefined : _o.prompt_tokens) != null ? _p : NaN,
        completionTokens: (_r = (_q = response.usage) == null ? undefined : _q.completion_tokens) != null ? _r : NaN
      },
      rawCall: { rawPrompt, rawSettings },
      rawResponse: { headers: responseHeaders },
      request: { body: JSON.stringify(body) },
      response: getResponseMetadata(response),
      warnings,
      logprobs: mapOpenAIChatLogProbsOutput(choice.logprobs),
      providerMetadata
    };
  }
  async doStream(options) {
    if (this.settings.simulateStreaming) {
      const result = await this.doGenerate(options);
      const simulatedStream = new ReadableStream({
        start(controller) {
          controller.enqueue({ type: "response-metadata", ...result.response });
          if (result.text) {
            controller.enqueue({
              type: "text-delta",
              textDelta: result.text
            });
          }
          if (result.toolCalls) {
            for (const toolCall of result.toolCalls) {
              controller.enqueue({
                type: "tool-call",
                ...toolCall
              });
            }
          }
          controller.enqueue({
            type: "finish",
            finishReason: result.finishReason,
            usage: result.usage,
            logprobs: result.logprobs,
            providerMetadata: result.providerMetadata
          });
          controller.close();
        }
      });
      return {
        stream: simulatedStream,
        rawCall: result.rawCall,
        rawResponse: result.rawResponse,
        warnings: result.warnings
      };
    }
    const { args, warnings } = this.getArgs(options);
    const body = {
      ...args,
      stream: true,
      stream_options: this.config.compatibility === "strict" ? { include_usage: true } : undefined
    };
    const { responseHeaders, value: response } = await postJsonToApi({
      url: this.config.url({
        path: "/chat/completions",
        modelId: this.modelId
      }),
      headers: combineHeaders(this.config.headers(), options.headers),
      body,
      failedResponseHandler: openaiFailedResponseHandler,
      successfulResponseHandler: createEventSourceResponseHandler(openaiChatChunkSchema),
      abortSignal: options.abortSignal,
      fetch: this.config.fetch
    });
    const { messages: rawPrompt, ...rawSettings } = args;
    const toolCalls = [];
    let finishReason = "unknown";
    let usage = {
      promptTokens: undefined,
      completionTokens: undefined
    };
    let logprobs;
    let isFirstChunk = true;
    const { useLegacyFunctionCalling } = this.settings;
    let providerMetadata;
    return {
      stream: response.pipeThrough(new TransformStream({
        transform(chunk, controller) {
          var _a16, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
          if (!chunk.success) {
            finishReason = "error";
            controller.enqueue({ type: "error", error: chunk.error });
            return;
          }
          const value = chunk.value;
          if ("error" in value) {
            finishReason = "error";
            controller.enqueue({ type: "error", error: value.error });
            return;
          }
          if (isFirstChunk) {
            isFirstChunk = false;
            controller.enqueue({
              type: "response-metadata",
              ...getResponseMetadata(value)
            });
          }
          if (value.usage != null) {
            usage = {
              promptTokens: (_a16 = value.usage.prompt_tokens) != null ? _a16 : undefined,
              completionTokens: (_b = value.usage.completion_tokens) != null ? _b : undefined
            };
            const {
              completion_tokens_details: completionTokenDetails,
              prompt_tokens_details: promptTokenDetails
            } = value.usage;
            if ((completionTokenDetails == null ? undefined : completionTokenDetails.reasoning_tokens) != null || (promptTokenDetails == null ? undefined : promptTokenDetails.cached_tokens) != null) {
              providerMetadata = { openai: {} };
              if ((completionTokenDetails == null ? undefined : completionTokenDetails.reasoning_tokens) != null) {
                providerMetadata.openai.reasoningTokens = completionTokenDetails == null ? undefined : completionTokenDetails.reasoning_tokens;
              }
              if ((promptTokenDetails == null ? undefined : promptTokenDetails.cached_tokens) != null) {
                providerMetadata.openai.cachedPromptTokens = promptTokenDetails == null ? undefined : promptTokenDetails.cached_tokens;
              }
            }
          }
          const choice = value.choices[0];
          if ((choice == null ? undefined : choice.finish_reason) != null) {
            finishReason = mapOpenAIFinishReason(choice.finish_reason);
          }
          if ((choice == null ? undefined : choice.delta) == null) {
            return;
          }
          const delta = choice.delta;
          if (delta.content != null) {
            controller.enqueue({
              type: "text-delta",
              textDelta: delta.content
            });
          }
          const mappedLogprobs = mapOpenAIChatLogProbsOutput(choice == null ? undefined : choice.logprobs);
          if (mappedLogprobs == null ? undefined : mappedLogprobs.length) {
            if (logprobs === undefined)
              logprobs = [];
            logprobs.push(...mappedLogprobs);
          }
          const mappedToolCalls = useLegacyFunctionCalling && delta.function_call != null ? [
            {
              type: "function",
              id: generateId(),
              function: delta.function_call,
              index: 0
            }
          ] : delta.tool_calls;
          if (mappedToolCalls != null) {
            for (const toolCallDelta of mappedToolCalls) {
              const index = toolCallDelta.index;
              if (toolCalls[index] == null) {
                if (toolCallDelta.type !== "function") {
                  throw new InvalidResponseDataError({
                    data: toolCallDelta,
                    message: `Expected 'function' type.`
                  });
                }
                if (toolCallDelta.id == null) {
                  throw new InvalidResponseDataError({
                    data: toolCallDelta,
                    message: `Expected 'id' to be a string.`
                  });
                }
                if (((_c = toolCallDelta.function) == null ? undefined : _c.name) == null) {
                  throw new InvalidResponseDataError({
                    data: toolCallDelta,
                    message: `Expected 'function.name' to be a string.`
                  });
                }
                toolCalls[index] = {
                  id: toolCallDelta.id,
                  type: "function",
                  function: {
                    name: toolCallDelta.function.name,
                    arguments: (_d = toolCallDelta.function.arguments) != null ? _d : ""
                  },
                  hasFinished: false
                };
                const toolCall2 = toolCalls[index];
                if (((_e = toolCall2.function) == null ? undefined : _e.name) != null && ((_f = toolCall2.function) == null ? undefined : _f.arguments) != null) {
                  if (toolCall2.function.arguments.length > 0) {
                    controller.enqueue({
                      type: "tool-call-delta",
                      toolCallType: "function",
                      toolCallId: toolCall2.id,
                      toolName: toolCall2.function.name,
                      argsTextDelta: toolCall2.function.arguments
                    });
                  }
                  if (isParsableJson(toolCall2.function.arguments)) {
                    controller.enqueue({
                      type: "tool-call",
                      toolCallType: "function",
                      toolCallId: (_g = toolCall2.id) != null ? _g : generateId(),
                      toolName: toolCall2.function.name,
                      args: toolCall2.function.arguments
                    });
                    toolCall2.hasFinished = true;
                  }
                }
                continue;
              }
              const toolCall = toolCalls[index];
              if (toolCall.hasFinished) {
                continue;
              }
              if (((_h = toolCallDelta.function) == null ? undefined : _h.arguments) != null) {
                toolCall.function.arguments += (_j = (_i = toolCallDelta.function) == null ? undefined : _i.arguments) != null ? _j : "";
              }
              controller.enqueue({
                type: "tool-call-delta",
                toolCallType: "function",
                toolCallId: toolCall.id,
                toolName: toolCall.function.name,
                argsTextDelta: (_k = toolCallDelta.function.arguments) != null ? _k : ""
              });
              if (((_l = toolCall.function) == null ? undefined : _l.name) != null && ((_m = toolCall.function) == null ? undefined : _m.arguments) != null && isParsableJson(toolCall.function.arguments)) {
                controller.enqueue({
                  type: "tool-call",
                  toolCallType: "function",
                  toolCallId: (_n = toolCall.id) != null ? _n : generateId(),
                  toolName: toolCall.function.name,
                  args: toolCall.function.arguments
                });
                toolCall.hasFinished = true;
              }
            }
          }
        },
        flush(controller) {
          var _a16, _b;
          controller.enqueue({
            type: "finish",
            finishReason,
            logprobs,
            usage: {
              promptTokens: (_a16 = usage.promptTokens) != null ? _a16 : NaN,
              completionTokens: (_b = usage.completionTokens) != null ? _b : NaN
            },
            ...providerMetadata != null ? { providerMetadata } : {}
          });
        }
      })),
      rawCall: { rawPrompt, rawSettings },
      rawResponse: { headers: responseHeaders },
      request: { body: JSON.stringify(body) },
      warnings
    };
  }
};
var openaiTokenUsageSchema = z.object({
  prompt_tokens: z.number().nullish(),
  completion_tokens: z.number().nullish(),
  prompt_tokens_details: z.object({
    cached_tokens: z.number().nullish()
  }).nullish(),
  completion_tokens_details: z.object({
    reasoning_tokens: z.number().nullish()
  }).nullish()
}).nullish();
var openaiChatResponseSchema = z.object({
  id: z.string().nullish(),
  created: z.number().nullish(),
  model: z.string().nullish(),
  choices: z.array(z.object({
    message: z.object({
      role: z.literal("assistant").nullish(),
      content: z.string().nullish(),
      function_call: z.object({
        arguments: z.string(),
        name: z.string()
      }).nullish(),
      tool_calls: z.array(z.object({
        id: z.string().nullish(),
        type: z.literal("function"),
        function: z.object({
          name: z.string(),
          arguments: z.string()
        })
      })).nullish()
    }),
    index: z.number(),
    logprobs: z.object({
      content: z.array(z.object({
        token: z.string(),
        logprob: z.number(),
        top_logprobs: z.array(z.object({
          token: z.string(),
          logprob: z.number()
        }))
      })).nullable()
    }).nullish(),
    finish_reason: z.string().nullish()
  })),
  usage: openaiTokenUsageSchema
});
var openaiChatChunkSchema = z.union([
  z.object({
    id: z.string().nullish(),
    created: z.number().nullish(),
    model: z.string().nullish(),
    choices: z.array(z.object({
      delta: z.object({
        role: z.enum(["assistant"]).nullish(),
        content: z.string().nullish(),
        function_call: z.object({
          name: z.string().optional(),
          arguments: z.string().optional()
        }).nullish(),
        tool_calls: z.array(z.object({
          index: z.number(),
          id: z.string().nullish(),
          type: z.literal("function").optional(),
          function: z.object({
            name: z.string().nullish(),
            arguments: z.string().nullish()
          })
        })).nullish()
      }).nullish(),
      logprobs: z.object({
        content: z.array(z.object({
          token: z.string(),
          logprob: z.number(),
          top_logprobs: z.array(z.object({
            token: z.string(),
            logprob: z.number()
          }))
        })).nullable()
      }).nullish(),
      finish_reason: z.string().nullable().optional(),
      index: z.number()
    })),
    usage: openaiTokenUsageSchema
  }),
  openaiErrorDataSchema
]);
function isReasoningModel(modelId) {
  return modelId.startsWith("o1-");
}
function isAudioModel(modelId) {
  return modelId.startsWith("gpt-4o-audio-preview");
}
function convertToOpenAICompletionPrompt({
  prompt,
  inputFormat,
  user = "user",
  assistant = "assistant"
}) {
  if (inputFormat === "prompt" && prompt.length === 1 && prompt[0].role === "user" && prompt[0].content.length === 1 && prompt[0].content[0].type === "text") {
    return { prompt: prompt[0].content[0].text };
  }
  let text2 = "";
  if (prompt[0].role === "system") {
    text2 += `${prompt[0].content}

`;
    prompt = prompt.slice(1);
  }
  for (const { role, content } of prompt) {
    switch (role) {
      case "system": {
        throw new InvalidPromptError({
          message: "Unexpected system message in prompt: ${content}",
          prompt
        });
      }
      case "user": {
        const userMessage = content.map((part) => {
          switch (part.type) {
            case "text": {
              return part.text;
            }
            case "image": {
              throw new UnsupportedFunctionalityError({
                functionality: "images"
              });
            }
          }
        }).join("");
        text2 += `${user}:
${userMessage}

`;
        break;
      }
      case "assistant": {
        const assistantMessage = content.map((part) => {
          switch (part.type) {
            case "text": {
              return part.text;
            }
            case "tool-call": {
              throw new UnsupportedFunctionalityError({
                functionality: "tool-call messages"
              });
            }
          }
        }).join("");
        text2 += `${assistant}:
${assistantMessage}

`;
        break;
      }
      case "tool": {
        throw new UnsupportedFunctionalityError({
          functionality: "tool messages"
        });
      }
      default: {
        const _exhaustiveCheck = role;
        throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
      }
    }
  }
  text2 += `${assistant}:
`;
  return {
    prompt: text2,
    stopSequences: [`
${user}:`]
  };
}
function mapOpenAICompletionLogProbs(logprobs) {
  return logprobs == null ? undefined : logprobs.tokens.map((token, index) => ({
    token,
    logprob: logprobs.token_logprobs[index],
    topLogprobs: logprobs.top_logprobs ? Object.entries(logprobs.top_logprobs[index]).map(([token2, logprob]) => ({
      token: token2,
      logprob
    })) : []
  }));
}
var OpenAICompletionLanguageModel = class {
  constructor(modelId, settings, config) {
    this.specificationVersion = "v1";
    this.defaultObjectGenerationMode = undefined;
    this.modelId = modelId;
    this.settings = settings;
    this.config = config;
  }
  get provider() {
    return this.config.provider;
  }
  getArgs({
    mode,
    inputFormat,
    prompt,
    maxTokens,
    temperature,
    topP,
    topK,
    frequencyPenalty,
    presencePenalty,
    stopSequences: userStopSequences,
    responseFormat,
    seed
  }) {
    var _a16;
    const type = mode.type;
    const warnings = [];
    if (topK != null) {
      warnings.push({
        type: "unsupported-setting",
        setting: "topK"
      });
    }
    if (responseFormat != null && responseFormat.type !== "text") {
      warnings.push({
        type: "unsupported-setting",
        setting: "responseFormat",
        details: "JSON response format is not supported."
      });
    }
    const { prompt: completionPrompt, stopSequences } = convertToOpenAICompletionPrompt({ prompt, inputFormat });
    const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []];
    const baseArgs = {
      model: this.modelId,
      echo: this.settings.echo,
      logit_bias: this.settings.logitBias,
      logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : undefined : undefined,
      suffix: this.settings.suffix,
      user: this.settings.user,
      max_tokens: maxTokens,
      temperature,
      top_p: topP,
      frequency_penalty: frequencyPenalty,
      presence_penalty: presencePenalty,
      seed,
      prompt: completionPrompt,
      stop: stop.length > 0 ? stop : undefined
    };
    switch (type) {
      case "regular": {
        if ((_a16 = mode.tools) == null ? undefined : _a16.length) {
          throw new UnsupportedFunctionalityError({
            functionality: "tools"
          });
        }
        if (mode.toolChoice) {
          throw new UnsupportedFunctionalityError({
            functionality: "toolChoice"
          });
        }
        return { args: baseArgs, warnings };
      }
      case "object-json": {
        throw new UnsupportedFunctionalityError({
          functionality: "object-json mode"
        });
      }
      case "object-tool": {
        throw new UnsupportedFunctionalityError({
          functionality: "object-tool mode"
        });
      }
      default: {
        const _exhaustiveCheck = type;
        throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
      }
    }
  }
  async doGenerate(options) {
    const { args, warnings } = this.getArgs(options);
    const { responseHeaders, value: response } = await postJsonToApi({
      url: this.config.url({
        path: "/completions",
        modelId: this.modelId
      }),
      headers: combineHeaders(this.config.headers(), options.headers),
      body: args,
      failedResponseHandler: openaiFailedResponseHandler,
      successfulResponseHandler: createJsonResponseHandler(openaiCompletionResponseSchema),
      abortSignal: options.abortSignal,
      fetch: this.config.fetch
    });
    const { prompt: rawPrompt, ...rawSettings } = args;
    const choice = response.choices[0];
    return {
      text: choice.text,
      usage: {
        promptTokens: response.usage.prompt_tokens,
        completionTokens: response.usage.completion_tokens
      },
      finishReason: mapOpenAIFinishReason(choice.finish_reason),
      logprobs: mapOpenAICompletionLogProbs(choice.logprobs),
      rawCall: { rawPrompt, rawSettings },
      rawResponse: { headers: responseHeaders },
      response: getResponseMetadata(response),
      warnings,
      request: { body: JSON.stringify(args) }
    };
  }
  async doStream(options) {
    const { args, warnings } = this.getArgs(options);
    const body = {
      ...args,
      stream: true,
      stream_options: this.config.compatibility === "strict" ? { include_usage: true } : undefined
    };
    const { responseHeaders, value: response } = await postJsonToApi({
      url: this.config.url({
        path: "/completions",
        modelId: this.modelId
      }),
      headers: combineHeaders(this.config.headers(), options.headers),
      body,
      failedResponseHandler: openaiFailedResponseHandler,
      successfulResponseHandler: createEventSourceResponseHandler(openaiCompletionChunkSchema),
      abortSignal: options.abortSignal,
      fetch: this.config.fetch
    });
    const { prompt: rawPrompt, ...rawSettings } = args;
    let finishReason = "unknown";
    let usage = {
      promptTokens: Number.NaN,
      completionTokens: Number.NaN
    };
    let logprobs;
    let isFirstChunk = true;
    return {
      stream: response.pipeThrough(new TransformStream({
        transform(chunk, controller) {
          if (!chunk.success) {
            finishReason = "error";
            controller.enqueue({ type: "error", error: chunk.error });
            return;
          }
          const value = chunk.value;
          if ("error" in value) {
            finishReason = "error";
            controller.enqueue({ type: "error", error: value.error });
            return;
          }
          if (isFirstChunk) {
            isFirstChunk = false;
            controller.enqueue({
              type: "response-metadata",
              ...getResponseMetadata(value)
            });
          }
          if (value.usage != null) {
            usage = {
              promptTokens: value.usage.prompt_tokens,
              completionTokens: value.usage.completion_tokens
            };
          }
          const choice = value.choices[0];
          if ((choice == null ? undefined : choice.finish_reason) != null) {
            finishReason = mapOpenAIFinishReason(choice.finish_reason);
          }
          if ((choice == null ? undefined : choice.text) != null) {
            controller.enqueue({
              type: "text-delta",
              textDelta: choice.text
            });
          }
          const mappedLogprobs = mapOpenAICompletionLogProbs(choice == null ? undefined : choice.logprobs);
          if (mappedLogprobs == null ? undefined : mappedLogprobs.length) {
            if (logprobs === undefined)
              logprobs = [];
            logprobs.push(...mappedLogprobs);
          }
        },
        flush(controller) {
          controller.enqueue({
            type: "finish",
            finishReason,
            logprobs,
            usage
          });
        }
      })),
      rawCall: { rawPrompt, rawSettings },
      rawResponse: { headers: responseHeaders },
      warnings,
      request: { body: JSON.stringify(body) }
    };
  }
};
var openaiCompletionResponseSchema = z.object({
  id: z.string().nullish(),
  created: z.number().nullish(),
  model: z.string().nullish(),
  choices: z.array(z.object({
    text: z.string(),
    finish_reason: z.string(),
    logprobs: z.object({
      tokens: z.array(z.string()),
      token_logprobs: z.array(z.number()),
      top_logprobs: z.array(z.record(z.string(), z.number())).nullable()
    }).nullish()
  })),
  usage: z.object({
    prompt_tokens: z.number(),
    completion_tokens: z.number()
  })
});
var openaiCompletionChunkSchema = z.union([
  z.object({
    id: z.string().nullish(),
    created: z.number().nullish(),
    model: z.string().nullish(),
    choices: z.array(z.object({
      text: z.string(),
      finish_reason: z.string().nullish(),
      index: z.number(),
      logprobs: z.object({
        tokens: z.array(z.string()),
        token_logprobs: z.array(z.number()),
        top_logprobs: z.array(z.record(z.string(), z.number())).nullable()
      }).nullish()
    })),
    usage: z.object({
      prompt_tokens: z.number(),
      completion_tokens: z.number()
    }).nullish()
  }),
  openaiErrorDataSchema
]);
var OpenAIEmbeddingModel = class {
  constructor(modelId, settings, config) {
    this.specificationVersion = "v1";
    this.modelId = modelId;
    this.settings = settings;
    this.config = config;
  }
  get provider() {
    return this.config.provider;
  }
  get maxEmbeddingsPerCall() {
    var _a16;
    return (_a16 = this.settings.maxEmbeddingsPerCall) != null ? _a16 : 2048;
  }
  get supportsParallelCalls() {
    var _a16;
    return (_a16 = this.settings.supportsParallelCalls) != null ? _a16 : true;
  }
  async doEmbed({
    values,
    headers,
    abortSignal
  }) {
    if (values.length > this.maxEmbeddingsPerCall) {
      throw new TooManyEmbeddingValuesForCallError({
        provider: this.provider,
        modelId: this.modelId,
        maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
        values
      });
    }
    const { responseHeaders, value: response } = await postJsonToApi({
      url: this.config.url({
        path: "/embeddings",
        modelId: this.modelId
      }),
      headers: combineHeaders(this.config.headers(), headers),
      body: {
        model: this.modelId,
        input: values,
        encoding_format: "float",
        dimensions: this.settings.dimensions,
        user: this.settings.user
      },
      failedResponseHandler: openaiFailedResponseHandler,
      successfulResponseHandler: createJsonResponseHandler(openaiTextEmbeddingResponseSchema),
      abortSignal,
      fetch: this.config.fetch
    });
    return {
      embeddings: response.data.map((item) => item.embedding),
      usage: response.usage ? { tokens: response.usage.prompt_tokens } : undefined,
      rawResponse: { headers: responseHeaders }
    };
  }
};
var openaiTextEmbeddingResponseSchema = z.object({
  data: z.array(z.object({ embedding: z.array(z.number()) })),
  usage: z.object({ prompt_tokens: z.number() }).nullish()
});
var OpenAIImageModel = class {
  constructor(modelId, config) {
    this.specificationVersion = "v1";
    this.modelId = modelId;
    this.config = config;
  }
  get provider() {
    return this.config.provider;
  }
  async doGenerate({
    prompt,
    n,
    size,
    providerOptions,
    headers,
    abortSignal
  }) {
    var _a16;
    const { value: response } = await postJsonToApi({
      url: this.config.url({
        path: "/images/generations",
        modelId: this.modelId
      }),
      headers: combineHeaders(this.config.headers(), headers),
      body: {
        model: this.modelId,
        prompt,
        n,
        size,
        ...(_a16 = providerOptions.openai) != null ? _a16 : {},
        response_format: "b64_json"
      },
      failedResponseHandler: openaiFailedResponseHandler,
      successfulResponseHandler: createJsonResponseHandler(openaiImageResponseSchema),
      abortSignal,
      fetch: this.config.fetch
    });
    return {
      images: response.data.map((item) => item.b64_json)
    };
  }
};
var openaiImageResponseSchema = z.object({
  data: z.array(z.object({ b64_json: z.string() }))
});
function createOpenAI(options = {}) {
  var _a16, _b, _c;
  const baseURL = (_a16 = withoutTrailingSlash(options.baseURL)) != null ? _a16 : "https://api.openai.com/v1";
  const compatibility = (_b = options.compatibility) != null ? _b : "compatible";
  const providerName = (_c = options.name) != null ? _c : "openai";
  const getHeaders = () => ({
    Authorization: `Bearer ${loadApiKey({
      apiKey: options.apiKey,
      environmentVariableName: "OPENAI_API_KEY",
      description: "OpenAI"
    })}`,
    "OpenAI-Organization": options.organization,
    "OpenAI-Project": options.project,
    ...options.headers
  });
  const createChatModel = (modelId, settings = {}) => new OpenAIChatLanguageModel(modelId, settings, {
    provider: `${providerName}.chat`,
    url: ({ path }) => `${baseURL}${path}`,
    headers: getHeaders,
    compatibility,
    fetch: options.fetch
  });
  const createCompletionModel = (modelId, settings = {}) => new OpenAICompletionLanguageModel(modelId, settings, {
    provider: `${providerName}.completion`,
    url: ({ path }) => `${baseURL}${path}`,
    headers: getHeaders,
    compatibility,
    fetch: options.fetch
  });
  const createEmbeddingModel = (modelId, settings = {}) => new OpenAIEmbeddingModel(modelId, settings, {
    provider: `${providerName}.embedding`,
    url: ({ path }) => `${baseURL}${path}`,
    headers: getHeaders,
    fetch: options.fetch
  });
  const createImageModel = (modelId) => new OpenAIImageModel(modelId, {
    provider: `${providerName}.image`,
    url: ({ path }) => `${baseURL}${path}`,
    headers: getHeaders,
    fetch: options.fetch
  });
  const createLanguageModel = (modelId, settings) => {
    if (new.target) {
      throw new Error("The OpenAI model function cannot be called with the new keyword.");
    }
    if (modelId === "gpt-3.5-turbo-instruct") {
      return createCompletionModel(modelId, settings);
    }
    return createChatModel(modelId, settings);
  };
  const provider = function(modelId, settings) {
    return createLanguageModel(modelId, settings);
  };
  provider.languageModel = createLanguageModel;
  provider.chat = createChatModel;
  provider.completion = createCompletionModel;
  provider.embedding = createEmbeddingModel;
  provider.textEmbedding = createEmbeddingModel;
  provider.textEmbeddingModel = createEmbeddingModel;
  provider.image = createImageModel;
  return provider;
}
var openai = createOpenAI({
  compatibility: "strict"
});

// src/swarm.ts
var SWARM_CONTEXT_PROPERTY_NAME = "swarmContext";

class Swarm {
  defaultModel;
  name;
  queen;
  context;
  messages;
  maxTurns;
  returnToQueen;
  constructor(options) {
    this.context = options.initialContext;
    this.defaultModel = options.defaultModel || openai("gpt-4o-mini");
    this.queen = options.queen;
    this._activeAgent = options.queen;
    this.messages = options.messages || [];
    this.name = options.name;
    this.maxTurns = options.maxTurns || 100;
    this.returnToQueen = !!options.returnToQueen;
  }
  _activeAgent;
  get activeAgent() {
    return this._activeAgent;
  }
  async generateText(options) {
    this.handleUpdatesAndOverrides(options);
    const initialMessages = options.messages ? this.messages : [
      ...this.messages,
      { role: "user", content: options.content }
    ];
    let lastResult;
    const responseMessages = [];
    const maxTotalSteps = options.maxTurns ?? this.maxTurns;
    do {
      const initialAgent = this._activeAgent;
      lastResult = await generateText({
        model: this._activeAgent.config.model || this.defaultModel,
        system: this._activeAgent.getInstructions(this.context),
        tools: this.wrapTools(this._activeAgent.tools),
        maxSteps: this._activeAgent.config.maxTurns ?? maxTotalSteps,
        toolChoice: this._activeAgent.config.toolChoice,
        onStepFinish: options.onStepFinish ? (stepResult) => options.onStepFinish(stepResult, this.context) : undefined,
        messages: [...initialMessages, ...responseMessages]
      });
      responseMessages.push(...lastResult.response.messages.map((message) => ({
        ...message,
        sender: this._activeAgent.name
      })));
      if (["stop", "length", "content-filter", "error"].includes(lastResult.finishReason)) {
        break;
      }
      const { toolCalls, toolResults } = lastResult;
      const toolResultIds = toolResults.map((result) => result.toolCallId);
      const unhandledToolCalls = toolCalls.filter((toolCall) => !toolResultIds.includes(toolCall.toolCallId));
      const handoverCalls = unhandledToolCalls.filter((toolCall) => this._activeAgent.tools?.[toolCall.toolName].type === "handover");
      let handoverToolResult;
      if (handoverCalls.length > 0) {
        const handoverTool = this._activeAgent.tools?.[handoverCalls[0].toolName];
        const result = await handoverTool.execute({
          ...handoverCalls[0].args,
          ...this.context
        }, {});
        this._activeAgent = result.agent;
        if (result.context)
          this.context = {
            ...this.context,
            ...result.context
          };
        handoverToolResult = {
          type: "tool-result",
          toolCallId: handoverCalls[0].toolCallId,
          toolName: handoverCalls[0].toolName,
          result: `Handing over to agent ${this._activeAgent.name}`
        };
      }
      const toolMessage = responseMessages.at(-1)?.role === "tool" ? responseMessages.at(-1) : undefined;
      const assistantMessage = responseMessages.at(toolMessage === undefined ? -1 : -2);
      if (handoverToolResult != null) {
        if (toolMessage == null) {
          responseMessages.push({ role: "tool", content: [handoverToolResult] });
        } else {
          toolMessage.content.push(handoverToolResult);
        }
      }
      if (typeof assistantMessage.content !== "string") {
        const unusedToolCallIds = handoverCalls.filter((call, index) => index > 0).map((call) => call.toolCallId);
        assistantMessage.content = assistantMessage.content.filter((part) => {
          return part.type === "tool-call" ? !unusedToolCallIds.includes(part.toolCallId) : true;
        });
      }
      const assistantMessages = lastResult.response.messages.filter((message) => message.role === "assistant");
      if (initialAgent.config.maxTurns && initialAgent.config.maxTurns === assistantMessages.length && responseMessages.filter((message) => message.role === "assistant").length < maxTotalSteps) {
        this._activeAgent = this.queen;
      }
    } while (responseMessages.filter((message) => message.role === "assistant").length < maxTotalSteps);
    this.messages.push(...responseMessages);
    if (this.returnToQueen)
      this._activeAgent = this.queen;
    return {
      finishReason: lastResult.finishReason,
      activeAgent: this._activeAgent,
      text: lastResult.text,
      messages: responseMessages,
      context: this.context
    };
  }
  streamText(options) {
    this.handleUpdatesAndOverrides(options);
    const initialMessages = options.messages ? this.messages : [
      ...this.messages,
      { role: "user", content: options.content }
    ];
    const finishReasonPromise = createResolvablePromise2();
    const activeAgentPromise = createResolvablePromise2();
    const textPromise = createResolvablePromise2();
    const allResponseMessagesPromise = createResolvablePromise2();
    const contextPromise = createResolvablePromise2();
    let stitchableStream = createStitchableStream2();
    let stream = stitchableStream.stream;
    let addStream = stitchableStream.addStream;
    let closeStream = stitchableStream.close;
    let enqueue = stitchableStream.enqueue;
    function teeStream() {
      const [stream1, stream2] = stream.tee();
      stream = stream2;
      return stream1;
    }
    const textStream = createAsyncIterableStream2(teeStream().pipeThrough(new TransformStream({
      transform: (streamPart, controller) => {
        if (streamPart?.type === "text-delta") {
          controller.enqueue(streamPart.textDelta);
        } else if (streamPart?.type === "error") {
          controller.error(streamPart.error);
        }
      }
    })));
    const fullStream = createAsyncIterableStream2(teeStream().pipeThrough(new TransformStream({
      transform: (streamPart, controller) => {
        if ("agent" in streamPart)
          controller.enqueue(streamPart);
        else
          controller.enqueue({
            ...streamPart,
            agent: {
              id: this._activeAgent.uuid,
              name: this._activeAgent.name
            }
          });
      }
    })));
    (async () => {
      let lastResult;
      const responseMessages = [];
      const maxTotalSteps = options.maxTurns ?? this.maxTurns;
      do {
        const initialAgent = this._activeAgent;
        lastResult = streamText({
          model: this._activeAgent.config.model || this.defaultModel,
          system: this._activeAgent.getInstructions(this.context),
          tools: this.wrapTools(this._activeAgent.tools),
          maxSteps: this._activeAgent.config.maxTurns ?? maxTotalSteps,
          toolChoice: this._activeAgent.config.toolChoice,
          onStepFinish: options.onStepFinish ? (stepResult) => options.onStepFinish(stepResult, this.context) : undefined,
          messages: [...initialMessages, ...responseMessages],
          experimental_toolCallStreaming: !(options.experimental_toolCallStreaming === false)
        });
        addStream(lastResult.fullStream);
        const [response, finishReason, toolResults, toolCalls] = await Promise.all([
          lastResult.response,
          lastResult.finishReason,
          lastResult.toolResults,
          lastResult.toolCalls
        ]);
        responseMessages.push(...response.messages.map((message) => ({
          ...message,
          sender: this._activeAgent.name
        })));
        if (["stop", "length", "content-filter", "error"].includes(finishReason)) {
          break;
        }
        const toolResultIds = toolResults.map((result) => result.toolCallId);
        const unhandledToolCalls = toolCalls.filter((toolCall) => !toolResultIds.includes(toolCall.toolCallId));
        const handoverCalls = unhandledToolCalls.filter((toolCall) => this._activeAgent.tools?.[toolCall.toolName].type === "handover");
        let handoverToolResult = undefined;
        if (handoverCalls.length > 0) {
          const handoverTool = this._activeAgent.tools?.[handoverCalls[0].toolName];
          const previousAgent = { name: this._activeAgent.name, id: this._activeAgent.uuid };
          const result = await handoverTool.execute({
            ...handoverCalls[0].args,
            ...this.context
          }, {});
          this._activeAgent = result.agent;
          if (result.context)
            this.context = {
              ...this.context,
              ...result.context
            };
          handoverToolResult = {
            type: "tool-result",
            toolCallId: handoverCalls[0].toolCallId,
            toolName: handoverCalls[0].toolName,
            result: `Handing over to agent ${this._activeAgent.name}`,
            handedOverTo: {
              id: this._activeAgent.uuid,
              name: this._activeAgent.name
            },
            args: handoverCalls[0].args,
            agent: previousAgent
          };
          enqueue(handoverToolResult);
        }
        const toolMessage = responseMessages.at(-1)?.role === "tool" ? responseMessages.at(-1) : undefined;
        const assistantMessage = responseMessages.at(toolMessage === undefined ? -1 : -2);
        if (handoverToolResult) {
          if (toolMessage == null) {
            responseMessages.push({ role: "tool", content: [handoverToolResult] });
          } else {
            toolMessage.content.push(handoverToolResult);
          }
        }
        if (typeof assistantMessage.content !== "string") {
          const unusedToolCallIds = handoverCalls.filter((call, index) => index > 0).map((call) => call.toolCallId);
          assistantMessage.content = assistantMessage.content.filter((part) => {
            return part.type === "tool-call" ? !unusedToolCallIds.includes(part.toolCallId) : true;
          });
        }
        const assistantMessages = response.messages.filter((message) => message.role === "assistant");
        if (initialAgent.config.maxTurns && initialAgent.config.maxTurns === assistantMessages.length && responseMessages.filter((message) => message.role === "assistant").length < maxTotalSteps) {
          this._activeAgent = this.queen;
        }
      } while (responseMessages.filter((message) => message.role === "assistant").length < maxTotalSteps);
      closeStream();
      this.messages.push(...responseMessages);
      if (this.returnToQueen)
        this._activeAgent = this.queen;
      lastResult.finishReason.then((reason) => finishReasonPromise.resolve(reason));
      activeAgentPromise.resolve(this._activeAgent);
      lastResult.text.then((text2) => textPromise.resolve(text2));
      allResponseMessagesPromise.resolve(responseMessages);
      contextPromise.resolve(this.context);
    })();
    return {
      finishReason: finishReasonPromise.promise,
      activeAgent: activeAgentPromise.promise,
      text: textPromise.promise,
      messages: allResponseMessagesPromise.promise,
      context: contextPromise.promise,
      textStream,
      fullStream
    };
  }
  getContext() {
    return this.context;
  }
  updateContext(update) {
    this.context = {
      ...this.context,
      ...update
    };
    return this.context;
  }
  handleUpdatesAndOverrides(invocationOptions) {
    if (invocationOptions.setAgent) {
      this._activeAgent = invocationOptions.setAgent;
    }
    if (invocationOptions.messages) {
      this.messages = invocationOptions.messages;
    }
    this.context = {
      ...this.context,
      ...invocationOptions.contextUpdate
    };
  }
  wrapTools(tools) {
    if (!tools)
      return;
    return Object.fromEntries(Object.entries(tools).map(([toolName, agentTool]) => {
      let parameters = agentTool.parameters;
      let executor = undefined;
      let functionWrapper;
      if (agentTool.type === "function") {
        functionWrapper = async (args, options) => {
          const { result, context } = await agentTool.execute(args, options);
          if (context)
            this.context = {
              ...this.context,
              ...context
            };
          return result;
        };
      }
      if (SWARM_CONTEXT_PROPERTY_NAME in agentTool.parameters.shape) {
        parameters = agentTool.parameters.omit({
          [SWARM_CONTEXT_PROPERTY_NAME]: true
        });
        if (agentTool.execute) {
          executor = async (args, options) => {
            const swarmContext = this.getContext();
            return functionWrapper ? functionWrapper({
              ...args,
              [SWARM_CONTEXT_PROPERTY_NAME]: swarmContext
            }, options) : agentTool.execute({
              ...args,
              [SWARM_CONTEXT_PROPERTY_NAME]: swarmContext
            }, options);
          };
        }
      } else {
        executor = functionWrapper;
      }
      if (agentTool.type === "handover") {
        executor = undefined;
      }
      let wrappedTool;
      if (executor) {
        wrappedTool = tool({
          type: "function",
          description: agentTool.description,
          parameters,
          execute: executor
        });
      } else {
        wrappedTool = tool({
          type: "function",
          description: agentTool.description,
          parameters
        });
      }
      return [toolName, wrappedTool];
    }));
  }
  getMessages() {
    return this.messages;
  }
}
// src/hive.ts
class Hive {
  defaultModel;
  queen;
  defaultInitialContext;
  constructor(options) {
    this.defaultModel = options.defaultModel || openai("gpt-4o-mini");
    this.queen = options.queen;
    this.defaultInitialContext = options.defaultContext;
  }
  spawnSwarm(options) {
    if (!this.defaultInitialContext && !options?.defaultContext)
      throw new Error(`Unable to create swarm from Hive: default context for swarm must be passed in Hive() or in Hive.swarm()`);
    return new Swarm({
      defaultModel: options?.defaultModel || this.defaultModel,
      queen: options?.queen || this.queen,
      initialContext: options?.defaultContext || this.defaultInitialContext,
      messages: options?.messages
    });
  }
}
export {
  a,
  Swarm,
  Hive,
  Agent
};